agentic-qe 3.13.1 → 3.13.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/hooks/aqe-hook.cjs +24 -3
- package/.claude/skills/qe-court/SKILL.md +25 -3
- package/.claude/skills/qe-court/config.json +1 -1
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +72 -0
- package/assets/skills/qe-court/SKILL.md +25 -3
- package/assets/skills/qe-court/config.json +1 -1
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-NIUFP6QX.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-4VM3DE42.js → agent-booster-wasm-YIGGREZN.js} +2 -2
- package/dist/cli/chunks/{agent-handler-ZDLMZQQX.js → agent-handler-64O7R55A.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-P72MDHHV.js → agent-memory-branch-2ZZBYUP3.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-DC4DNCPB.js +2 -0
- package/dist/cli/chunks/{arena-55FZGKEV.js → arena-6YRNQNCX.js} +4 -4
- package/dist/cli/chunks/{arena-GCRBQ26R.js → arena-PF5WL2WM.js} +2 -2
- package/dist/cli/chunks/{audit-VYAYVLIV.js → audit-R53FOYCK.js} +3 -3
- package/dist/cli/chunks/base-EXD3ULZT.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-GMRPPMDM.js → better-sqlite3-OW5HIPEN.js} +2 -2
- package/dist/cli/chunks/{brain-handler-IUKMRGWO.js → brain-handler-J4ICUOUX.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-TUI3RWLX.js → branch-enumerator-YVPD43TG.js} +2 -2
- package/dist/cli/chunks/{browser-NBQTZYX2.js → browser-TKVHX53S.js} +2 -2
- package/dist/cli/chunks/browser-workflow-KOMASCB7.js +2 -0
- package/dist/cli/chunks/{chunk-WINA3XUT.js → chunk-22WFXSXB.js} +2 -2
- package/dist/cli/chunks/chunk-2BYRQ5MV.js +4 -0
- package/dist/cli/chunks/{chunk-ZLCATRXI.js → chunk-2G2XD6EM.js} +2 -2
- package/dist/cli/chunks/{chunk-XN2CD5S6.js → chunk-2MLPO3RZ.js} +2 -2
- package/dist/cli/chunks/{chunk-2ISLQU3G.js → chunk-2QKSIHXO.js} +1 -1
- package/dist/cli/chunks/{chunk-PKMCZFET.js → chunk-33SPAMQZ.js} +2 -2
- package/dist/cli/chunks/{chunk-6C3MZLYW.js → chunk-37GCWGXT.js} +2 -2
- package/dist/cli/chunks/{chunk-FM272B4O.js → chunk-37I4AMCT.js} +2 -2
- package/dist/cli/chunks/{chunk-7D7XFZZI.js → chunk-3CFWNT3F.js} +2 -2
- package/dist/cli/chunks/{chunk-TDGE52HJ.js → chunk-3J2QITXC.js} +1 -1
- package/dist/cli/chunks/{chunk-YRVUYM62.js → chunk-3NML6POU.js} +2 -2
- package/dist/cli/chunks/chunk-46U73TST.js +2 -0
- package/dist/cli/chunks/{chunk-XOQQGZFY.js → chunk-4RYU4WMW.js} +1 -1
- package/dist/cli/chunks/{chunk-2XZ4BHWS.js → chunk-4Z2AKQP4.js} +1 -1
- package/dist/cli/chunks/{chunk-4QMWWYNU.js → chunk-5A5EC5RD.js} +2 -2
- package/dist/cli/chunks/{chunk-FRAGSKXQ.js → chunk-5IH22DLD.js} +3 -3
- package/dist/cli/chunks/{chunk-OCKTPTQ7.js → chunk-5IVOY76M.js} +2 -2
- package/dist/cli/chunks/{chunk-OE4B6LDZ.js → chunk-62F5M5OO.js} +1 -1
- package/dist/cli/chunks/{chunk-IBSBOHUX.js → chunk-64C4SS66.js} +2 -2
- package/dist/cli/chunks/{chunk-ELMUHNXN.js → chunk-66KIIH6V.js} +2 -2
- package/dist/cli/chunks/{chunk-N7WAZ2Y6.js → chunk-6C3PDY72.js} +1 -1
- package/dist/cli/chunks/{chunk-UMCEEXQN.js → chunk-6I2L22WS.js} +1 -1
- package/dist/cli/chunks/{chunk-MCIO7BDK.js → chunk-6R6QGQ7D.js} +1 -1
- package/dist/cli/chunks/{chunk-IJA4WS7B.js → chunk-764G7VK6.js} +1 -1
- package/dist/cli/chunks/{chunk-QG6BXSNJ.js → chunk-7AHQ7ROU.js} +2 -2
- package/dist/cli/chunks/{chunk-BF5BKSDU.js → chunk-7MBPKAQ3.js} +2 -2
- package/dist/cli/chunks/{chunk-MUFYDKVC.js → chunk-7TG7LJAB.js} +2 -2
- package/dist/cli/chunks/{chunk-PIOO2M4W.js → chunk-A22RTEJ3.js} +2 -2
- package/dist/cli/chunks/{chunk-SXADKQJN.js → chunk-A547LEUW.js} +2 -2
- package/dist/cli/chunks/{chunk-JOTNKZ7A.js → chunk-A6J5MAVO.js} +10 -10
- package/dist/cli/chunks/{chunk-XFUF654L.js → chunk-ADBTOUOX.js} +1 -1
- package/dist/cli/chunks/{chunk-3K4YC3GC.js → chunk-AJ45QR3K.js} +2 -2
- package/dist/cli/chunks/{chunk-WWCH5SSF.js → chunk-APXJJRU4.js} +2 -2
- package/dist/cli/chunks/{chunk-IJP42OGW.js → chunk-AXXFY7PX.js} +2 -2
- package/dist/cli/chunks/{chunk-ZYPESQ4M.js → chunk-B7XZJBMT.js} +2 -2
- package/dist/cli/chunks/{chunk-EGMGOWCE.js → chunk-BDOD534O.js} +2 -2
- package/dist/cli/chunks/{chunk-LTWT4GZD.js → chunk-C7AXBCMS.js} +4 -4
- package/dist/cli/chunks/{chunk-MX5ZDKRR.js → chunk-CBLKYGKT.js} +2 -2
- package/dist/cli/chunks/{chunk-NHV4PTG6.js → chunk-CVFUANMU.js} +2 -2
- package/dist/cli/chunks/{chunk-WWP2VXYJ.js → chunk-CW7BWFFF.js} +2 -2
- package/dist/cli/chunks/{chunk-S6VNPKHO.js → chunk-CXPMA7LY.js} +1 -1
- package/dist/cli/chunks/{chunk-UCQ66N6M.js → chunk-DPJLA7JW.js} +2 -2
- package/dist/cli/chunks/{chunk-ZH6ZBDVV.js → chunk-DSGKRXHF.js} +1 -1
- package/dist/cli/chunks/{chunk-2D2XFUKI.js → chunk-DSUEJK33.js} +2 -2
- package/dist/cli/chunks/{chunk-ARTLSAXO.js → chunk-DTOKJKSE.js} +2 -2
- package/dist/cli/chunks/{chunk-THFLRJT6.js → chunk-EEG4G5JG.js} +3 -3
- package/dist/cli/chunks/{chunk-LSKQUUUN.js → chunk-EMH54CO7.js} +2 -2
- package/dist/cli/chunks/{chunk-FDUSWM6O.js → chunk-F6V5POSK.js} +18 -18
- package/dist/cli/chunks/{chunk-ZIBW7CB4.js → chunk-FF53QW6C.js} +1 -1
- package/dist/cli/chunks/{chunk-ZHEKGB4A.js → chunk-FGIZVGIE.js} +2 -2
- package/dist/cli/chunks/{chunk-TQ2MA3SR.js → chunk-GNCGRDQ2.js} +1 -1
- package/dist/cli/chunks/{chunk-HFI5PHG5.js → chunk-GSG5FASF.js} +3 -3
- package/dist/cli/chunks/{chunk-UJ6TMZC6.js → chunk-GTURQ454.js} +2 -2
- package/dist/cli/chunks/{chunk-FQXQJMSF.js → chunk-H2BR5MCX.js} +2 -2
- package/dist/cli/chunks/{chunk-7WEHZCSK.js → chunk-H4XZOIV6.js} +2 -2
- package/dist/cli/chunks/{chunk-UHKXKWMD.js → chunk-HEF6XKA5.js} +2 -2
- package/dist/cli/chunks/{chunk-MPD7RR4P.js → chunk-HJNFXYX4.js} +1 -1
- package/dist/cli/chunks/{chunk-S6F3IJMK.js → chunk-HOIH542Y.js} +1 -1
- package/dist/cli/chunks/{chunk-GJEEPKAT.js → chunk-IH47VGC7.js} +2 -2
- package/dist/cli/chunks/{chunk-DTRFZD7N.js → chunk-IKPBQZQP.js} +2 -2
- package/dist/cli/chunks/{chunk-Y734CWHJ.js → chunk-IRX2THND.js} +2 -2
- package/dist/cli/chunks/{chunk-YVKMHXQK.js → chunk-IZIYFVAZ.js} +3 -3
- package/dist/cli/chunks/{chunk-4WGSMODQ.js → chunk-J5AIMM2J.js} +1 -1
- package/dist/cli/chunks/{chunk-KNWDXI3I.js → chunk-J65XQ6WE.js} +2 -2
- package/dist/cli/chunks/{chunk-L7IOTWWY.js → chunk-JBWXBDJX.js} +1 -1
- package/dist/cli/chunks/{chunk-JAPOMPFD.js → chunk-JG267MVB.js} +2 -2
- package/dist/cli/chunks/{chunk-3Y6CHW67.js → chunk-JHOJG5VO.js} +1 -1
- package/dist/cli/chunks/{chunk-J4T6D2OQ.js → chunk-JLFU5SCI.js} +2 -2
- package/dist/cli/chunks/{chunk-6XZXMEK4.js → chunk-JOHWWTJF.js} +2 -2
- package/dist/cli/chunks/{chunk-HUMQU4ES.js → chunk-JQTDNUHA.js} +2 -2
- package/dist/cli/chunks/{chunk-WZROSTQZ.js → chunk-K2D3YW2N.js} +1 -1
- package/dist/cli/chunks/{chunk-INYS35DV.js → chunk-KBQRYAHZ.js} +2 -2
- package/dist/cli/chunks/{chunk-GASOBSNB.js → chunk-KQ5GLUOB.js} +4 -4
- package/dist/cli/chunks/{chunk-3KGCBAUH.js → chunk-KQFMCVBH.js} +2 -2
- package/dist/cli/chunks/{chunk-A2MG3YXO.js → chunk-L4O2645U.js} +1 -1
- package/dist/cli/chunks/{chunk-ZCLFAOVT.js → chunk-LLQG3F4H.js} +2 -2
- package/dist/cli/chunks/{chunk-5BB5DUL4.js → chunk-LOZRBK2Z.js} +2 -2
- package/dist/cli/chunks/{chunk-YQCAXYBF.js → chunk-LWPCGOQM.js} +2 -2
- package/dist/cli/chunks/{chunk-RSCGBHLM.js → chunk-M7XDTQHX.js} +2 -2
- package/dist/cli/chunks/{chunk-23MT7OBY.js → chunk-MGKJFO57.js} +2 -2
- package/dist/cli/chunks/{chunk-YMMVCOPF.js → chunk-MNEQESQJ.js} +5 -5
- package/dist/cli/chunks/{chunk-ZXX2VFMA.js → chunk-MYR6CBXC.js} +2 -2
- package/dist/cli/chunks/{chunk-AY7S7AWN.js → chunk-N3KQRDTM.js} +1 -1
- package/dist/cli/chunks/{chunk-SS6K4FBH.js → chunk-N4OBRS6S.js} +2 -2
- package/dist/cli/chunks/{chunk-2CQAWYYE.js → chunk-N7IRBQ4D.js} +1 -1
- package/dist/cli/chunks/{chunk-UHGMS2PJ.js → chunk-NF2N2FIY.js} +1 -1
- package/dist/cli/chunks/{chunk-YBPCBFEE.js → chunk-NIA6VTIH.js} +2 -2
- package/dist/cli/chunks/{chunk-P4Y3G6OB.js → chunk-NUPAGPN6.js} +2 -2
- package/dist/cli/chunks/{chunk-J45DX3IK.js → chunk-OD5R7HRI.js} +1 -1
- package/dist/cli/chunks/{chunk-3F4XH4ZA.js → chunk-ORXDKBZC.js} +1 -1
- package/dist/cli/chunks/{chunk-MXKHIZVM.js → chunk-OU5CZFBG.js} +3 -3
- package/dist/cli/chunks/{chunk-QLOOW23R.js → chunk-OX6WPOGR.js} +3 -3
- package/dist/cli/chunks/{chunk-IZO6TPGX.js → chunk-P5CQMDFQ.js} +2 -2
- package/dist/cli/chunks/{chunk-DVPGQG4W.js → chunk-PHBGMXTR.js} +2 -2
- package/dist/cli/chunks/{chunk-55WDVSCM.js → chunk-PHGOMAIS.js} +2 -2
- package/dist/cli/chunks/{chunk-VAJT6QWX.js → chunk-PHNNAIFA.js} +1 -1
- package/dist/cli/chunks/{chunk-USUFTHHT.js → chunk-PS32DXYF.js} +3 -3
- package/dist/cli/chunks/{chunk-TBQTGQ75.js → chunk-PY55ZD2G.js} +2 -2
- package/dist/cli/chunks/{chunk-IMQKEFW6.js → chunk-QFANYWC5.js} +1 -1
- package/dist/cli/chunks/{chunk-LSZZQ7H6.js → chunk-QGJYKXUO.js} +1 -1
- package/dist/cli/chunks/{chunk-MY47CR27.js → chunk-QP4UKSUJ.js} +2 -2
- package/dist/cli/chunks/{chunk-CWXDL7AH.js → chunk-QZ3EIONO.js} +1 -1
- package/dist/cli/chunks/{chunk-V32MDID3.js → chunk-QZS3XCU5.js} +2 -2
- package/dist/cli/chunks/{chunk-UKBDH27A.js → chunk-RMQRSZB4.js} +1 -1
- package/dist/cli/chunks/{chunk-H7YZ2YF2.js → chunk-RRHIEG4Y.js} +2 -2
- package/dist/cli/chunks/{chunk-LVHMXGDI.js → chunk-RU23JXCG.js} +3 -3
- package/dist/cli/chunks/{chunk-LTKNCYMO.js → chunk-RWPWD5GG.js} +2 -2
- package/dist/cli/chunks/{chunk-KW5NBORV.js → chunk-SAMAYDVS.js} +2 -2
- package/dist/cli/chunks/{chunk-EAKHU5YX.js → chunk-SJWTNKPY.js} +3 -3
- package/dist/cli/chunks/{chunk-XSCOEY4C.js → chunk-SSXCHSVM.js} +2 -2
- package/dist/cli/chunks/chunk-T5L65R23.js +2 -0
- package/dist/cli/chunks/{chunk-CE6LYEHT.js → chunk-TGVDKSSS.js} +1 -1
- package/dist/cli/chunks/{chunk-VLUJWI56.js → chunk-TK6CHESH.js} +1 -1
- package/dist/cli/chunks/{chunk-HYIRFJDB.js → chunk-TNM7X2GD.js} +2 -2
- package/dist/cli/chunks/{chunk-GOV2MHLV.js → chunk-TRPRFW27.js} +2 -2
- package/dist/cli/chunks/{chunk-BOCEOLLJ.js → chunk-TW5QWNT4.js} +2 -2
- package/dist/cli/chunks/{chunk-6QKQFHS7.js → chunk-U7DGRHSB.js} +2 -2
- package/dist/cli/chunks/{chunk-M3T6FB54.js → chunk-UAXFRKR3.js} +2 -2
- package/dist/cli/chunks/{chunk-YLAEIS6F.js → chunk-UF7JKDWB.js} +1 -1
- package/dist/cli/chunks/{chunk-OPQY2333.js → chunk-UOJ26GXD.js} +2 -2
- package/dist/cli/chunks/{chunk-2OM3TDC4.js → chunk-UWBHR4EZ.js} +1 -1
- package/dist/cli/chunks/{chunk-NP4CP3LR.js → chunk-UX434RY5.js} +2 -2
- package/dist/cli/chunks/{chunk-CWP4RMOM.js → chunk-V6W4IHS5.js} +2 -2
- package/dist/cli/chunks/{chunk-2G2QWV7B.js → chunk-VFZNVJP2.js} +2 -2
- package/dist/cli/chunks/{chunk-IV2VCR75.js → chunk-VGWHFFK6.js} +5 -5
- package/dist/cli/chunks/{chunk-ORDH4VPL.js → chunk-VKUH57JE.js} +1 -1
- package/dist/cli/chunks/{chunk-RZ6CO3RZ.js → chunk-VRTNRI4H.js} +2 -2
- package/dist/cli/chunks/{chunk-FQUUMC57.js → chunk-W6OIDL4J.js} +2 -2
- package/dist/cli/chunks/{chunk-SHWXADCI.js → chunk-WHUQDBV7.js} +2 -2
- package/dist/cli/chunks/{chunk-JELNVHBF.js → chunk-WRC66JTK.js} +1 -1
- package/dist/cli/chunks/{chunk-AHTOWWSE.js → chunk-WVWWTRKT.js} +1 -1
- package/dist/cli/chunks/{chunk-LJQ27PUE.js → chunk-X737I4SO.js} +1 -1
- package/dist/cli/chunks/{chunk-AYYDO52G.js → chunk-XRF5MX4Q.js} +2 -2
- package/dist/cli/chunks/{chunk-MAYZTGJ2.js → chunk-XRQGWUDX.js} +2 -2
- package/dist/cli/chunks/{chunk-AOMXMFDH.js → chunk-ZI7BWJJW.js} +2 -2
- package/dist/cli/chunks/{chunk-SPJQJWGK.js → chunk-ZIYCZZYD.js} +2 -2
- package/dist/cli/chunks/{chunk-E4D47QTF.js → chunk-ZLTAAROU.js} +2 -2
- package/dist/cli/chunks/{chunk-GTPZVLL6.js → chunk-ZU3XUBDQ.js} +1 -1
- package/dist/cli/chunks/{ci-HHL5WQXQ.js → ci-G2NEYLVO.js} +2 -2
- package/dist/cli/chunks/{ci-output-HVOJC2KN.js → ci-output-SZFEXGBU.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-HRXMIY2G.js → circuit-breaker-ZD7PJY6N.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-3I7WVMZN.js → claude-flow-setup-DAVANGUJ.js} +2 -2
- package/dist/cli/chunks/client-ZJQMJO5N.js +2 -0
- package/dist/cli/chunks/{cline-installer-NBREL4QT.js → cline-installer-WCPKWLY7.js} +2 -2
- package/dist/cli/chunks/{code-TX4E2RWU.js → code-324ZJR3V.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-YELOFLSL.js → code-index-extractor-EWVSXJHR.js} +2 -2
- package/dist/cli/chunks/{codex-installer-HEX3KFRB.js → codex-installer-HVSZBHH2.js} +2 -2
- package/dist/cli/chunks/{completions-72GGFRGG.js → completions-ZAWBZWYK.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-WRAKDYUK.js → complexity-analyzer-S3H2IRON.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-UGYKSKTI.js → continuedev-installer-4DDFAJ26.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-RPCRUKIJ.js → copilot-installer-KBBAL3G5.js} +2 -2
- package/dist/cli/chunks/core-handlers-U2YJLH6O.js +2 -0
- package/dist/cli/chunks/{cost-tracker-CNHJ7G4M.js → cost-tracker-2YM7SGBW.js} +2 -2
- package/dist/cli/chunks/{coverage-RHIQ4XEX.js → coverage-6CCBAORJ.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-E7EMKZEK.js +2 -0
- package/dist/cli/chunks/{cursor-installer-KSRVA4V2.js → cursor-installer-24DKXNU5.js} +2 -2
- package/dist/cli/chunks/{daemon-QBXSJABV.js → daemon-JLF6CRBS.js} +4 -4
- package/dist/cli/chunks/{daemon-IT4AAFBW.js → daemon-M2PSDIZF.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-F7WCQTLY.js → dag-attention-scheduler-Y5HSZDRV.js} +2 -2
- package/dist/cli/chunks/{detect-2IYU332U.js → detect-6Y227IJ6.js} +2 -2
- package/dist/cli/chunks/{dist-node-CIYNYCYN.js → dist-node-EGOJXGTA.js} +2 -2
- package/dist/cli/chunks/{domain-handler-QRYQO2QK.js → domain-handler-G3JEWRE5.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-2OQDOD3G.js → domain-transfer-XOHI3EMJ.js} +2 -2
- package/dist/cli/chunks/dream-ZMNQYBJO.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-P2IFC7JL.js → embed-and-insert-pattern-CSSA55L4.js} +2 -2
- package/dist/cli/chunks/{eval-SBPK37IB.js → eval-NHBXOXDV.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-3GMFND3F.js → experience-capture-middleware-B7ZDV5UY.js} +3 -3
- package/dist/cli/chunks/{fast-paths-4OYYII2F.js → fast-paths-XGKSBALA.js} +2 -2
- package/dist/cli/chunks/{feature-flags-BM6QTMMC.js → feature-flags-NBUDJSWJ.js} +2 -2
- package/dist/cli/chunks/{feature-flags-NFCAYUWO.js → feature-flags-ZVD73ZYK.js} +2 -2
- package/dist/cli/chunks/{file-discovery-2M3ZUAGC.js → file-discovery-C42TEUKT.js} +2 -2
- package/dist/cli/chunks/{fleet-QMGGVIDV.js → fleet-LF77P3BW.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-WGMAGZMO.js → gnn-wrapper-UXNT7BEN.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-5RSMEZGG.js → heartbeat-handler-C4LMU5LA.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-2JL4MAJR.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-AZD6O35G.js +2 -0
- package/dist/cli/chunks/hnsw-index-WJLE4S5L.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-TYPQ2T6P.js → hnsw-legacy-bridge-EHHBIWS3.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-JDDFYVCX.js → hnswlib-node-QOULNHXS.js} +2 -2
- package/dist/cli/chunks/{hooks-NUC5P3OJ.js → hooks-AGE3HCFI.js} +37 -37
- package/dist/cli/chunks/hybrid-router-YTKJBAS2.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-OIB7WK54.js → hypergraph-engine-E5QX5MEB.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-XX2N75QC.js → hypergraph-handler-ZZHBANYB.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-CX56GZXA.js +2 -0
- package/dist/cli/chunks/{init-handler-AKSTJMZY.js → init-handler-PNVRBZZT.js} +6 -6
- package/dist/cli/chunks/init-wizard-WE6HIC66.js +2 -0
- package/dist/cli/chunks/kernel-MT55LNNI.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-375V5ZZB.js → kilocode-installer-TR53QKPU.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-GKY5GB5Q.js → kiro-installer-MJW6LCAX.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-WN3LQ2W7.js +2 -0
- package/dist/cli/chunks/{learning-2CQE3QP6.js → learning-6LLGHP2Q.js} +3 -3
- package/dist/cli/chunks/{llm-router-FTQNRF45.js → llm-router-DBLV3VGG.js} +4 -4
- package/dist/cli/chunks/llm-router-service-NKHEQQMN.js +2 -0
- package/dist/cli/chunks/{load-3DBAO5ZG.js → load-LAZ3E5PE.js} +2 -2
- package/dist/cli/chunks/load-test-3WIQASDF.js +2 -0
- package/dist/cli/chunks/{mcp-AWR6TDXM.js → mcp-L5QXHSEY.js} +2 -2
- package/dist/cli/chunks/{memory-GI4LCNXY.js → memory-YR5PCMWA.js} +5 -5
- package/dist/cli/chunks/memory-backend-W6YSNT6O.js +2 -0
- package/dist/cli/chunks/{memory-handlers-MALKG7GP.js → memory-handlers-BSRTZQYR.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-SWFT5U72.js → multi-model-executor-RECZ3ACW.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-EYXGYJX5.js → opencode-installer-4TDUB7HH.js} +2 -2
- package/dist/cli/chunks/{orchestrator-MP3EAZVC.js → orchestrator-PHDKJ5C4.js} +5 -5
- package/dist/cli/chunks/pattern-null-store-IV3ZESTR.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-25P3R3W7.js → pattern-usage-recorder-QK2FADRS.js} +2 -2
- package/dist/cli/chunks/{pipeline-LSAFL25D.js → pipeline-JQJYSN43.js} +2 -2
- package/dist/cli/chunks/{platform-IJ6DJ2PG.js → platform-FA5TOPTH.js} +2 -2
- package/dist/cli/chunks/{plugin-OXOZRZW2.js → plugin-766MBGK6.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-HJNJQQ3R.js → prime-radiant-advanced-wasm-XQERZNSK.js} +2 -2
- package/dist/cli/chunks/protocol-executor-GFAG5G6K.js +2 -0
- package/dist/cli/chunks/{protocol-handler-TCMUH2HL.js → protocol-handler-FAK4MMNA.js} +2 -2
- package/dist/cli/chunks/{prove-ADXQ2GOX.js → prove-HYBVXOGW.js} +2 -2
- package/dist/cli/chunks/provider-manager-TIVIJIYH.js +2 -0
- package/dist/cli/chunks/qe-reasoning-bank-BYE7YF6Y.js +2 -0
- package/dist/cli/chunks/{quality-EWP36ORX.js → quality-EGSO2RAX.js} +2 -2
- package/dist/cli/chunks/{quality-gate-3BIG7PVU.js → quality-gate-RK32VMO7.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-WOHYVV7A.js +2 -0
- package/dist/cli/chunks/{real-embeddings-D4NBT7W5.js → real-embeddings-GI7CRHE2.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-DOPWH6YV.js → roocode-installer-BS3XWJJI.js} +2 -2
- package/dist/cli/chunks/router-VUW2UVCN.js +2 -0
- package/dist/cli/chunks/routing-feedback-WSUQMZAK.js +2 -0
- package/dist/cli/chunks/{routing-handler-5ADEFOHS.js → routing-handler-XMGRJDHH.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-PLMEIHSN.js → ruvector-commands-NDL3ONNC.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-EQWKVNQB.js → rvf-dual-writer-XAJOYGJ2.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-2OWFUUCG.js → rvf-migration-adapter-WXFRZZ26.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-URAETAPU.js → rvf-migration-coordinator-WFXA2VUQ.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-RHZCXVN6.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-4AWPW4TF.js → rvf-store-integrity-I7PFJZCK.js} +2 -2
- package/dist/cli/chunks/safe-db-NTWEW7ZM.js +2 -0
- package/dist/cli/chunks/schedule-WEVC2GW2.js +2 -0
- package/dist/cli/chunks/scheduler-XHI5AJIS.js +2 -0
- package/dist/cli/chunks/{security-HDLZVM62.js → security-H3WY76GF.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-YQT7PF7X.js → shared-rvf-adapter-GRTJCLW6.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-N5D3NSJ7.js → shared-rvf-dual-writer-46XE5R2B.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-QZUPKMHP.js +2 -0
- package/dist/cli/chunks/{status-handler-KLYRJ2MR.js → status-handler-VUIFMY4F.js} +2 -2
- package/dist/cli/chunks/{structural-health-6LKVRP6Y.js → structural-health-I7HC477E.js} +2 -2
- package/dist/cli/chunks/{sync-YYOW6L6W.js → sync-M6LUV5R4.js} +2 -2
- package/dist/cli/chunks/{sync-7VMFPBVB.js → sync-RO2YGMBF.js} +2 -2
- package/dist/cli/chunks/{task-handler-RKQDGFN2.js → task-handler-BJJTZ7AU.js} +2 -2
- package/dist/cli/chunks/{task-handlers-6YJ4QTEP.js → task-handlers-B6S4NEN3.js} +3 -3
- package/dist/cli/chunks/{test-ASPUIUJH.js → test-BE7EM6Y6.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-I7ABQBBU.js → test-scheduling-4ISKEFR6.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-2XZBTODN.js → token-bootstrap-BOIYBZHW.js} +2 -2
- package/dist/cli/chunks/{token-usage-TMUE6PTF.js → token-usage-6ZZC7RLT.js} +2 -2
- package/dist/cli/chunks/{transformers-FDHHH4SL.js → transformers-55VI4OGW.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-G7PGZA5C.js → tree-sitter-wasm-parser-6GRRGB3K.js} +2 -2
- package/dist/cli/chunks/{types-JGT57UFP.js → types-SXDF7QQT.js} +2 -2
- package/dist/cli/chunks/unified-memory-QKWUSEBV.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-Z2UQZRTK.js +2 -0
- package/dist/cli/chunks/unified-persistence-AVK2NSMI.js +2 -0
- package/dist/cli/chunks/{upgrade-V6UQODJF.js → upgrade-PMPB7NGB.js} +2 -2
- package/dist/cli/chunks/{validate-UBZAE5RW.js → validate-G37QKKXK.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-TSO2MI5X.js → validate-swarm-6X22J3VD.js} +2 -2
- package/dist/cli/chunks/{vibium-7G3VYSQA.js → vibium-SGBJKHQL.js} +2 -2
- package/dist/cli/chunks/visual-security-64UFH23G.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-MIYJSF2L.js → web-tree-sitter-S46Y5BUJ.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-5TLZSQIJ.js → windsurf-installer-PTYCETNM.js} +2 -2
- package/dist/cli/chunks/{witness-chain-LTV7H2HM.js → witness-chain-5SCRFT2K.js} +2 -2
- package/dist/cli/chunks/witness-chain-ZIVSDX6C.js +2 -0
- package/dist/cli/chunks/{witness-key-manager-PAJ2J4AL.js → witness-key-manager-XIAMRVUZ.js} +2 -2
- package/dist/cli/chunks/{workflow-DL3ESR2H.js → workflow-BPQA2NAI.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-TYP4MI2V.js +2 -0
- package/dist/cli/chunks/{wrappers-5HSU665E.js → wrappers-IWZZZOAU.js} +2 -2
- package/dist/cli/commands/hooks-handlers/hooks-shared.d.ts +9 -0
- package/dist/cli/commands/hooks-handlers/hooks-shared.js +38 -0
- package/dist/cli/commands/hooks.d.ts +2 -2
- package/dist/cli/commands/hooks.js +8 -2
- package/dist/coordination/handlers/coverage-collection.js +6 -2
- package/dist/coordination/queen-coordinator.js +4 -3
- package/dist/integrations/ruvector/rvf-store-integrity.js +5 -1
- package/dist/integrations/ruvector/shared-rvf-adapter.js +5 -5
- package/dist/mcp/bundle.js +211 -209
- package/dist/shared/safe-db.js +60 -1
- package/dist/skills/qe-court/referee.d.ts +44 -0
- package/dist/skills/qe-court/referee.js +31 -2
- package/package.json +1 -1
- package/dist/cli/chunks/adapter-VRZNL53W.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-XCNMNERX.js +0 -2
- package/dist/cli/chunks/base-VZZNR4UR.js +0 -2
- package/dist/cli/chunks/browser-workflow-5DZNIFUY.js +0 -2
- package/dist/cli/chunks/chunk-BBLWZT5I.js +0 -2
- package/dist/cli/chunks/chunk-EVDYFGVH.js +0 -2
- package/dist/cli/chunks/chunk-QES4QHQW.js +0 -2
- package/dist/cli/chunks/client-EY2IYQDL.js +0 -2
- package/dist/cli/chunks/core-handlers-G4GLA4DT.js +0 -2
- package/dist/cli/chunks/cross-domain-router-P3K4IH5H.js +0 -2
- package/dist/cli/chunks/dream-IT4ZQGEO.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-UUWSPHF2.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-YUJVSFPD.js +0 -2
- package/dist/cli/chunks/hnsw-index-FQZ47RSJ.js +0 -2
- package/dist/cli/chunks/hybrid-router-T5MF73NF.js +0 -2
- package/dist/cli/chunks/impact-analyzer-AEGELYMD.js +0 -2
- package/dist/cli/chunks/init-wizard-WKX3OGWM.js +0 -2
- package/dist/cli/chunks/kernel-5CVWFIGR.js +0 -2
- package/dist/cli/chunks/knowledge-graph-EGPMNDMT.js +0 -2
- package/dist/cli/chunks/llm-router-service-H4LXOARB.js +0 -2
- package/dist/cli/chunks/load-test-OOOGITSN.js +0 -2
- package/dist/cli/chunks/memory-backend-O2YOT4LW.js +0 -2
- package/dist/cli/chunks/pattern-null-store-WBOHE2XL.js +0 -2
- package/dist/cli/chunks/protocol-executor-JCNTPW5J.js +0 -2
- package/dist/cli/chunks/provider-manager-LPGQ5GOO.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-FWVYVSPP.js +0 -2
- package/dist/cli/chunks/queen-coordinator-UXNALRVD.js +0 -2
- package/dist/cli/chunks/router-C6LUIQYY.js +0 -2
- package/dist/cli/chunks/routing-feedback-KMSGGDVD.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-K54BELUE.js +0 -2
- package/dist/cli/chunks/safe-db-NGOZWF2D.js +0 -2
- package/dist/cli/chunks/schedule-B3Y5P64E.js +0 -2
- package/dist/cli/chunks/scheduler-Z6QVRMTB.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-PLOUGATS.js +0 -2
- package/dist/cli/chunks/unified-memory-P5YVLMFI.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-7HI43A2O.js +0 -2
- package/dist/cli/chunks/unified-persistence-U26YP3N3.js +0 -2
- package/dist/cli/chunks/visual-security-6FCDY5FF.js +0 -2
- package/dist/cli/chunks/witness-chain-I3K3WQID.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-MAALP4WA.js +0 -2
|
@@ -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-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=`
|
|
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.3");process.exit(0)}
|
|
2
|
+
import{d as J,e as B,f as te,g as j}from"./chunk-UWBHR4EZ.js";import{a as ne}from"./chunk-QZ3EIONO.js";import{b as _e}from"./chunk-7TG7LJAB.js";import{a as ie}from"./chunk-ZLTAAROU.js";import{b as De,c as nt}from"./chunk-NIA6VTIH.js";import{a as re,b as Fe,d as Oe,f as it}from"./chunk-PHGOMAIS.js";import{c as Ie}from"./chunk-46U73TST.js";import{b as P,c as w}from"./chunk-ZU3XUBDQ.js";import{a as v,b as xe,c as Ce}from"./chunk-XRF5MX4Q.js";import{i as C}from"./chunk-FF53QW6C.js";import{B as Q,D as H,G as ee,P as M,S as F,b as D}from"./chunk-AXXFY7PX.js";import{a as Te,d as $,f as rt}from"./chunk-62F5M5OO.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-QZUPKMHP.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-2OM3TDC4.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-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};
|
|
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-EHHBIWS3.js"),{HnswAdapter:c}=await import("./hnsw-adapter-AZD6O35G.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-WJLE4S5L.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,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 y,c as v,d as R}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.3");process.exit(0)}
|
|
2
|
+
import{a as y,c as v,d as R}from"./chunk-RRHIEG4Y.js";import{d as u}from"./chunk-EEG4G5JG.js";import{a as p,b as g,c as P,d as s}from"./chunk-QP4UKSUJ.js";import{d as f,e as C}from"./chunk-66KIIH6V.js";C();var E=f("llm/router-service");function m(e){let r={};for(let[i,t]of Object.entries(e.providers??{}))t?.defaultModel&&(r[i]=t.defaultModel);p(e.agentOverrides,r);let o=g();if(o.length===0)return e;let n=e.rules.length>0?e.rules:P;return{...e,rules:[...o,...n]}}var T=["ollama","onnx","gemini","openrouter","openai","claude","azure-openai","bedrock"];async function F(e={}){if(e.providerManager){let a=m(v({projectRoot:e.projectRoot,override:e.override,env:e.env})),d=new s(e.providerManager,a);return await d.initialize(),{router:d,resolvedConfig:a,enabledProviders:x(a)}}if(!R({projectRoot:e.projectRoot,env:e.env}))return null;let r=m(v({projectRoot:e.projectRoot,override:e.override,env:e.env})),o=M(r,e.env??process.env);if(o.length===0)return null;let n=new Set(o);for(let[a,d]of Object.entries(r.agentOverrides??{}))d.provider&&!n.has(d.provider)&&E.warn(`[llm-config] agentOverrides["${a}"] routes to provider "${d.provider}", which is not enabled (no API key detected and not enabled in .agentic-qe/llm-config.json). This override will not take effect until that provider is available.`);let{primary:i,fallbacks:t}=L(r,o),l={primary:i,fallbacks:t,providers:k(r,o),loadBalancing:"round-robin",global:{enableCostTracking:!0,enableMetrics:!0}},b=new u(l),c=new s(b,r);return await c.initialize(),{router:c,resolvedConfig:r,enabledProviders:o}}function M(e,r=process.env){let o=y(r),n=[],i=t=>{n.includes(t)||!e.providers?.[t]?.enabled||o.has(t)&&n.push(t)};i(e.defaultProvider);for(let t of e.fallbackChain?.entries??[])i(t.provider);for(let t of T)i(t);return n}function x(e){let r=new Set([e.defaultProvider]);for(let o of e.fallbackChain?.entries??[])r.add(o.provider);return Array.from(r)}function L(e,r){if(r.length===0)throw new Error("pickPrimaryAndFallbacks: no enabled providers");let o=r.includes(e.defaultProvider)?e.defaultProvider:r[0],n=r.filter(i=>i!==o);return{primary:o,fallbacks:n}}function k(e,r){let o={};for(let n of r){let i=e.providers?.[n];i&&(o[n]=i)}return o}export{F as a,M as b,L as c};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.
|
|
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.3");process.exit(0)}
|
|
2
2
|
function M(u){let e=u|0;return()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}var A=2,y=10,x=200,p=1e-8,b=class{epsilon;seed;constructor(e){if(this.epsilon=e?.epsilon??.3,this.seed=e?.seed,this.epsilon<=0||this.epsilon>=1)throw new Error("SparsifierConfig.epsilon must be in (0, 1)")}sparsify(e){if(e.nodeCount<=0||e.edges.length===0)return{nodeCount:e.nodeCount,edges:[]};let n=this.seed!==void 0?M(this.seed):Math.random,t=this.approximateEffectiveResistances(e),i=e.nodeCount,r=e.edges.length,o=Math.max(1,Math.log(i)),m=this.epsilon*this.epsilon,l=Math.min(r,Math.max(i-1,A*(i-1)*(1-this.epsilon))),s=new Float64Array(r),c=0;for(let a=0;a<r;a++){let d=e.edges[a][2];s[a]=d*t[a],c+=s[a]}if(c<=0)return{nodeCount:e.nodeCount,edges:[]};let f=[];for(let a=0;a<r;a++){let[d,C,E]=e.edges[a],g=Math.min(1,s[a]/c*l);if(n()<g){let w=E/g;f.push([d,C,w])}}return{nodeCount:e.nodeCount,edges:f}}validateSpectral(e,n){let t=Math.min(y,Math.max(1,e.nodeCount-1)),i=this.computeLaplacian(e),r=this.computeLaplacian(n),o=this.computeTopEigenvalues(i,t),m=this.computeTopEigenvalues(r,t),l=[],s=!0,c=this.epsilon;for(let f=0;f<o.length;f++){if(o[f]<1e-10)continue;let a=m[f]/o[f];l.push(a),(a<1-c||a>1+c)&&(s=!1)}return{isValid:s,eigenvalueRatios:l,originalEdgeCount:e.edges.length,sparsifiedEdgeCount:n.edges.length,compressionRatio:e.edges.length>0?n.edges.length/e.edges.length:0}}computeLaplacian(e){let n=e.nodeCount,t=Array.from({length:n},()=>new Array(n).fill(0));for(let[i,r,o]of e.edges)i<0||i>=n||r<0||r>=n||(t[i][i]+=o,t[r][r]+=o,t[i][r]-=o,t[r][i]-=o);return t}computeTopEigenvalues(e,n){let t=e.length;if(t===0)return[];let i=[],r=[],o=e.map(m=>[...m]);for(let m=0;m<Math.min(n,t);m++){let l=this.powerIteration(o,t,r);if(l===null)break;i.push(l.eigenvalue),r.push(l.eigenvector),V(o,l.eigenvalue,l.eigenvector)}return i}approximateEffectiveResistances(e){let n=e.nodeCount,t=new Float64Array(n);for(let[r,o,m]of e.edges)r>=0&&r<n&&(t[r]+=m),o>=0&&o<n&&(t[o]+=m);let i=new Array(e.edges.length);for(let r=0;r<e.edges.length;r++){let[o,m]=e.edges[r],l=t[o]||1,s=t[m]||1;i[r]=1/l+1/s}return i}powerIteration(e,n,t){let i=0;for(let s=0;s<n;s++)for(let c=0;c<n;c++)i+=e[s][c]*e[s][c];if(i<p*p)return null;let r=t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]=Math.sin((s+1)*(r+1)*1.618033988749895)+.1*(s-n/2);for(let s of t)h(o,s);if(R(o)<p)return null;let l=0;for(let s=0;s<x;s++){let c=L(e,o);for(let d of t)h(c,d);let f=S(c,o),a=v(c);if(a<p)return{eigenvalue:0,eigenvector:o};for(let d=0;d<n;d++)o[d]=c[d]/a;if(Math.abs(f-l)<p){l=f;break}l=f}return{eigenvalue:Math.abs(l),eigenvector:o}}};function L(u,e){let n=u.length,t=new Array(n).fill(0);for(let i=0;i<n;i++){let r=0;for(let o=0;o<n;o++)r+=u[i][o]*e[o];t[i]=r}return t}function v(u){let e=0;for(let n=0;n<u.length;n++)e+=u[n]*u[n];return Math.sqrt(e)}function R(u){let e=v(u);if(e>0)for(let n=0;n<u.length;n++)u[n]/=e;return e}function S(u,e){let n=0;for(let t=0;t<u.length;t++)n+=u[t]*e[t];return n}function h(u,e){let n=S(u,e);for(let t=0;t<u.length;t++)u[t]-=n*e[t]}function V(u,e,n){let t=n.length;for(let i=0;i<t;i++)for(let r=0;r<t;r++)u[i][r]-=e*n[i]*n[r]}export{b as a};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.
|
|
2
|
-
function b(n,t){return{ingest(e){n.ingest(e)},search(e,r){return n.search(e,r).map(i=>({id:i.id,score:i.score}))},delete(e){n.delete(e)},status(){let e=n.status();return{totalVectors:e.totalVectors,dimensions:t,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries}},close(){n.close()},compact(){return n.compact()}}}function c(n,t){return(n.prepare("SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' AND name=?").get(t)?.cnt??0)>0}var v=class{db;config;rvfStore=null;rvfAvailable=!1;constructor(t,e){this.db=t,this.config={...e,dimensions:e.dimensions??384}}async initialize(){if(this.config.mode==="sqlite-only"){this.rvfAvailable=!1;return}try{let t=await import("./rvf-native-adapter-
|
|
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.3");process.exit(0)}
|
|
2
|
+
function b(n,t){return{ingest(e){n.ingest(e)},search(e,r){return n.search(e,r).map(i=>({id:i.id,score:i.score}))},delete(e){n.delete(e)},status(){let e=n.status();return{totalVectors:e.totalVectors,dimensions:t,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries}},close(){n.close()},compact(){return n.compact()}}}function c(n,t){return(n.prepare("SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' AND name=?").get(t)?.cnt??0)>0}var v=class{db;config;rvfStore=null;rvfAvailable=!1;constructor(t,e){this.db=t,this.config={...e,dimensions:e.dimensions??384}}async initialize(){if(this.config.mode==="sqlite-only"){this.rvfAvailable=!1;return}try{let t=await import("./rvf-native-adapter-RHZCXVN6.js");if(!t.isRvfNativeAvailable()){this.rvfAvailable=!1;return}let e;try{e=t.openRvfStore(this.config.rvfPath)}catch{try{e=t.createRvfStore(this.config.rvfPath,this.config.dimensions)}catch(r){let{quarantineUnusableStore:i}=await import("./rvf-store-integrity-I7PFJZCK.js");if(!i(this.config.rvfPath,r instanceof Error?r.message:String(r)))throw r;e=t.createRvfStore(this.config.rvfPath,this.config.dimensions)}}this.rvfStore=b(e,this.config.dimensions),this.rvfAvailable=!0}catch(t){this.rvfAvailable=!1,console.warn(`[RVF] Dual-writer disabled for ${this.config.rvfPath}; falling back to SQLite: ${t instanceof Error?t.message:String(t)}`)}}setRvfStore(t){this.rvfStore=t,this.rvfAvailable=!0}writePattern(t,e){let r={sqliteSuccess:!1,rvfSuccess:!1};try{this.writeSqliteEmbedding(t,e),r.sqliteSuccess=!0}catch{r.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.ingest([{id:t,vector:e instanceof Float32Array?Array.from(e):e}]),r.rvfSuccess=!0}catch{r.rvfSuccess=!1,r.divergence="rvf-write-failed"}return r}deletePattern(t){let e={sqliteSuccess:!1,rvfSuccess:!1};try{this.deleteSqliteEmbedding(t),e.sqliteSuccess=!0}catch{e.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.delete([t]),e.rvfSuccess=!0}catch{e.rvfSuccess=!1,e.divergence="rvf-delete-failed"}return e}search(t,e){if(this.config.mode==="rvf-primary"&&this.rvfAvailable&&this.rvfStore)try{return this.rvfStore.search(t,e)}catch{}return this.searchSqlite(t,e)}getDivergenceReport(){let t={totalChecked:0,divergences:0,details:[]},e=this.getSqliteEmbeddingCount();if(t.totalChecked=e,!this.rvfAvailable||!this.rvfStore)return this.config.mode!=="sqlite-only"&&e>0&&(t.divergences=1,t.details.push({patternId:"*",issue:"count-mismatch"})),t;let i=this.rvfStore.status().totalVectors;return e!==i&&(t.divergences=1,t.details.push({patternId:"*",issue:"count-mismatch"})),t}isPromotionSafe(){return this.getDivergenceReport().divergences===0}status(){let t=this.getSqlitePatternCount(),e=this.getSqliteEmbeddingCount(),r=null;if(this.rvfAvailable&&this.rvfStore)try{r=this.rvfStore.status()}catch{r=null}return{sqlite:{patternCount:t,vectorCount:e},rvf:r,mode:this.config.mode}}close(){if(this.rvfStore){try{this.rvfStore.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1}}compact(){if(!this.rvfStore||!this.rvfAvailable||!this.rvfStore.compact)return null;try{return this.rvfStore.compact()??null}catch{return null}}shouldWriteRvf(){return(this.config.mode==="dual-write"||this.config.mode==="rvf-primary")&&this.rvfAvailable&&this.rvfStore!==null}writeSqliteEmbedding(t,e){let r=Buffer.from(e instanceof Float32Array?e.buffer:new Float32Array(e).buffer),i=e.length;c(this.db,"qe_pattern_embeddings")&&this.db.prepare(`
|
|
3
3
|
INSERT INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model, created_at)
|
|
4
4
|
VALUES (?, ?, ?, 'all-MiniLM-L6-v2', datetime('now'))
|
|
5
5
|
ON CONFLICT(pattern_id) DO UPDATE SET
|
|
@@ -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 S}from"./chunk-BBLWZT5I.js";import{c as g}from"./chunk-ELMUHNXN.js";import{S as T,b as l}from"./chunk-IJP42OGW.js";S();T();import{createRequire as B}from"module";var G=B(import.meta.url),d=class{validateTransfer(e,t){return{approved:!0}}};function R(){if(l().useCoherenceGate)try{let{CoherenceGate:o}=G("./coherence-gate.js");return new o}catch{}return new d}S();var x=g.create("transfer-verification"),A={maxSourceRegression:.05,minTargetImprovement:0,maxSourceConfidenceRegression:.1},b=class{config;constructor(e={}){this.config={...A,...e}}verifyTransfer(e){let t=e.sourcePerformanceAfter.successRate-e.sourcePerformanceBefore.successRate,r=e.targetPerformanceAfter.successRate-e.targetPerformanceBefore.successRate,n=e.sourcePerformanceAfter.avgConfidence-e.sourcePerformanceBefore.avgConfidence,a=e.targetPerformanceAfter.avgConfidence-e.targetPerformanceBefore.avgConfidence,s=t>=-this.config.maxSourceRegression&&n>=-this.config.maxSourceConfidenceRegression,c=r>=this.config.minTargetImprovement,u=s&&c,m;if(!u){let i=[];s||i.push(`source domain regressed: successRate delta=${t.toFixed(4)}, confidence delta=${n.toFixed(4)}`),c||i.push(`target domain did not improve: successRate delta=${r.toFixed(4)}`),m=i.join("; ")}return u?x.debug("Transfer verification passed",{transferId:e.transferId,sourceDelta:t,targetDelta:r}):x.warn("Transfer verification failed",{transferId:e.transferId,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourceDelta:t,targetDelta:r,failureReason:m}),{passed:u,sourceStable:s,targetImproved:c,sourceDelta:t,targetDelta:r,sourceConfidenceDelta:n,targetConfidenceDelta:a,failureReason:m}}getConfig(){return{...this.config}}};function M(o){return new b(o)}T();var p=class{alphas=new Map;betas=new Map;sample(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return this.sampleBeta(t,r)}update(e,t){t?this.alphas.set(e,(this.alphas.get(e)??1)+1):this.betas.set(e,(this.betas.get(e)??1)+1)}getMean(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t/(t+r)}getObservationCount(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t-1+(r-1)}getAlpha(e){return this.alphas.get(e)??1}getBeta(e){return this.betas.get(e)??1}sampleBeta(e,t){let r=this.sampleGamma(e),n=this.sampleGamma(t);return r+n===0?.5:r/(r+n)}sampleGamma(e){if(e<1){let n=Math.random();return this.sampleGamma(e+1)*Math.pow(n,1/e)}let t=e-1/3,r=1/Math.sqrt(9*t);for(;;){let n,a;do n=this.standardNormal(),a=1+r*n;while(a<=0);a=a*a*a;let s=Math.random();if(s<1-.0331*n*n*n*n||Math.log(s)<.5*n*n+t*(1-a+Math.log(a)))return t*a}}standardNormal(){let e=Math.random(),t=Math.random();return Math.sqrt(-2*Math.log(e||1e-10))*Math.cos(2*Math.PI*t)}};var I={threshold:5,slack:.5,resetOnAlarm:!0,warmupSamples:20},h=class{config;states=new Map;constructor(e={}){this.config={...I,...e}}update(e,t){let r=this.getOrCreateState(e);if(r.samplesSinceReset++,r.mu===null)return r.warmupSum+=t,r.warmupCount++,r.warmupCount>=this.config.warmupSamples&&(r.mu=r.warmupSum/r.warmupCount),{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:r.samplesSinceReset};r.sPlus=Math.max(0,r.sPlus+(t-r.mu-this.config.slack)),r.sMinus=Math.max(0,r.sMinus+(-t+r.mu-this.config.slack));let n=Math.max(r.sPlus,r.sMinus),a=!1,s="none";r.sPlus>this.config.threshold?(a=!0,s="positive"):r.sMinus>this.config.threshold&&(a=!0,s="negative");let c={driftDetected:a,cumulativeSum:n,direction:s,samplesSinceReset:r.samplesSinceReset};return a&&this.config.resetOnAlarm&&(r.sPlus=0,r.sMinus=0,r.samplesSinceReset=0),c}reset(e){e?this.states.delete(e):this.states.clear()}getState(e){let t=this.states.get(e);if(!t)return{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:0};let r=Math.max(t.sPlus,t.sMinus),n="none";return t.sPlus>this.config.threshold?n="positive":t.sMinus>this.config.threshold&&(n="negative"),{driftDetected:t.sPlus>this.config.threshold||t.sMinus>this.config.threshold,cumulativeSum:r,direction:n,samplesSinceReset:t.samplesSinceReset}}getOrCreateState(e){let t=this.states.get(e);return t||(t={sPlus:0,sMinus:0,samplesSinceReset:0,warmupSum:0,warmupCount:0,mu:null},this.states.set(e,t)),t}};var w=g.create("domain-transfer"),V={minTransferProbability:.3,explorationWarmup:5,verification:{},maxHistorySize:1e3,useMetaLearningEnhancements:!0},v=class{constructor(e=100){this.decayThreshold=e}decayThreshold;getDecayMultiplier(e){return e<=0?1:Math.pow(.5,e/this.decayThreshold)}applyDecay(e,t,r){return t+(e-t)*this.getDecayMultiplier(r)}},y=class{cusum;outcomes=[];windowSize;constructor(e=20){this.windowSize=e,this.cusum=new h({threshold:3,slack:.1,resetOnAlarm:!1,warmupSamples:Math.min(10,Math.floor(e/2))})}record(e){this.outcomes.push(e),this.outcomes.length>this.windowSize*2&&this.outcomes.splice(0,this.outcomes.length-this.windowSize*2);let t=this.getCurrentRate();this.cusum.update("learn",t)}isPlateaued(){return this.outcomes.length<this.windowSize?!1:!this.cusum.getState("learn").driftDetected}getCurrentRate(){if(this.outcomes.length===0)return 0;let e=this.outcomes.slice(-this.windowSize);return e.filter(Boolean).length/e.length}getOutcomeCount(){return this.outcomes.length}getCusumState(){return this.cusum.getState("learn")}},D=class{front=[];dominates(e,t){let r=e.successRate>=t.successRate&&e.speed>=t.speed&&e.confidence>=t.confidence,n=e.successRate>t.successRate||e.speed>t.speed||e.confidence>t.confidence;return r&&n}add(e){for(let t=this.front.length-1;t>=0;t--)this.dominates(e,this.front[t])&&this.front.splice(t,1);this.front.some(t=>this.dominates(t,e))||this.front.push(e)}getFront(){return[...this.front]}isNonDominated(e){return!this.front.some(t=>this.dominates(t,e))}},C=class{constructor(e=.2){this.bonusScale=e}bonusScale;triedPairs=new Set;markTried(e){this.triedPairs.add(e)}isTried(e){return this.triedPairs.has(e)}getBonus(e){return this.triedPairs.has(e)?0:this.bonusScale}apply(e,t){return Math.min(1,e+this.getBonus(t))}getTriedCount(){return this.triedPairs.size}},P=class{config;sampler;verifier;coherenceGate;transferHistory=[];affinityScores=new Map;performanceProvider=null;transferExecutor=null;nativeModule=null;decayingBeta;plateauDetector;paretoFront;curiosityBonus;constructor(e={}){this.config={...V,...e},this.sampler=new p,this.verifier=M(this.config.verification),this.coherenceGate=R(),this.decayingBeta=new v,this.plateauDetector=new y,this.paretoFront=new D,this.curiosityBonus=new C,this.tryLoadNativeModule()}evaluateTransfer(e,t){if(!this.isEnabled())return this.createRejectedCandidate(e,t);let r=this.makePairKey(e,t),n=this.sampler.sample(r),s=this.sampler.getObservationCount(r)<this.config.explorationWarmup,c=this.getAffinityScore(e,t);if(this.isMetaLearningEnabled()){let u=this.sampler.getMean(r),m=this.sampler.getAlpha(r)-1;n=this.decayingBeta.applyDecay(n,u,m),n=this.curiosityBonus.apply(n,r)}return{sourceDomain:e,targetDomain:t,sampledProbability:n,affinityScore:c,isExploration:s,pairKey:r}}executeTransfer(e){let t=`transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=this.coherenceGate.validateTransfer({domain:e.sourceDomain},e.targetDomain);if(!r.approved)return w.info("Transfer blocked by coherence gate",{transferId:t,source:e.sourceDomain,target:e.targetDomain,reason:r.rejectionReason}),this.createBlockedResult(t,e,r);let n=this.getPerformanceSnapshot(e.sourceDomain),a=this.getPerformanceSnapshot(e.targetDomain),s=this.computeSqrtDampening(e),c=this.doTransfer(e.sourceDomain,e.targetDomain,s),u=this.getPerformanceSnapshot(e.sourceDomain),m=this.getPerformanceSnapshot(e.targetDomain),i=this.verifier.verifyTransfer({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m}),f=c&&i.passed;if(this.sampler.update(e.pairKey,f),this.updateAffinityScore(e.pairKey,f),this.isMetaLearningEnabled()){this.plateauDetector.record(f),this.curiosityBonus.markTried(e.pairKey);let F=this.sampler.getMean(e.pairKey);this.paretoFront.add({pairKey:e.pairKey,successRate:F,speed:1/(1+s),confidence:this.getAffinityScore(e.sourceDomain,e.targetDomain)})}return this.addToHistory({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,success:f,sampledProbability:e.sampledProbability,dampeningFactor:s,sourceDelta:i.sourceDelta,targetDelta:i.targetDelta,timestamp:Date.now()}),w.info("Transfer completed",{transferId:t,source:e.sourceDomain,target:e.targetDomain,success:f,dampeningFactor:s.toFixed(4),sourceDelta:i.sourceDelta.toFixed(4),targetDelta:i.targetDelta.toFixed(4)}),{transferId:t,candidate:e,success:f,dampeningFactor:s,verification:i,coherenceResult:r,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m,timestamp:Date.now()}}getAffinityScore(e,t){return this.affinityScores.get(this.makePairKey(e,t))??.5}getTransferHistory(){return[...this.transferHistory]}getExpectedSuccessRate(e,t){return this.sampler.getMean(this.makePairKey(e,t))}getObservationCount(e,t){return this.sampler.getObservationCount(this.makePairKey(e,t))}setPerformanceProvider(e){this.performanceProvider=e}setTransferExecutor(e){this.transferExecutor=e}getSampler(){return this.sampler}getCoherenceGate(){return this.coherenceGate}getDecayingBeta(){return this.decayingBeta}getPlateauDetector(){return this.plateauDetector}getParetoFront(){return this.paretoFront}getCuriosityBonus(){return this.curiosityBonus}isLearningPlateaued(){return this.plateauDetector.isPlateaued()}isEnabled(){return l().useCrossDomainTransfer===!0}isMetaLearningEnabled(){return this.config.useMetaLearningEnhancements===!0&&l().useMetaLearningEnhancements!==!1}makePairKey(e,t){return`${e}->${t}`}computeSqrtDampening(e){let t=this.sampler.getObservationCount(e.pairKey);return Math.sqrt(t/(t+this.config.explorationWarmup))}doTransfer(e,t,r){return this.transferExecutor?this.transferExecutor(e,t,r):!0}getPerformanceSnapshot(e){return this.performanceProvider?this.performanceProvider(e):{domain:e,successRate:.5,avgConfidence:.5,patternCount:0,timestamp:Date.now()}}updateAffinityScore(e,t){let r=this.affinityScores.get(e)??.5;this.affinityScores.set(e,.2*(t?1:0)+.8*r)}addToHistory(e){for(this.transferHistory.push(e);this.transferHistory.length>this.config.maxHistorySize;)this.transferHistory.shift()}createBlockedResult(e,t,r){let n={domain:"",successRate:0,avgConfidence:0,patternCount:0,timestamp:Date.now()};return{transferId:e,candidate:t,success:!1,dampeningFactor:0,verification:{passed:!1,sourceStable:!1,targetImproved:!1,sourceDelta:0,targetDelta:0,sourceConfidenceDelta:0,targetConfidenceDelta:0,failureReason:`Coherence gate rejected: ${r.rejectionReason??"unknown"}`},coherenceResult:r,sourcePerformanceBefore:{...n,domain:t.sourceDomain},sourcePerformanceAfter:{...n,domain:t.sourceDomain},targetPerformanceBefore:{...n,domain:t.targetDomain},targetPerformanceAfter:{...n,domain:t.targetDomain},timestamp:Date.now()}}createRejectedCandidate(e,t){return{sourceDomain:e,targetDomain:t,sampledProbability:0,affinityScore:0,isExploration:!1,pairKey:this.makePairKey(e,t)}}tryLoadNativeModule(){this.nativeModule=null}};function J(o){return new P(o)}export{h as a,p as b,V as c,v as d,y as e,D as f,C as g,P as h,J as i};
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.3");process.exit(0)}
|
|
2
|
+
import{a as S}from"./chunk-T5L65R23.js";import{c as g}from"./chunk-66KIIH6V.js";import{S as T,b as l}from"./chunk-AXXFY7PX.js";S();T();import{createRequire as B}from"module";var G=B(import.meta.url),d=class{validateTransfer(e,t){return{approved:!0}}};function R(){if(l().useCoherenceGate)try{let{CoherenceGate:o}=G("./coherence-gate.js");return new o}catch{}return new d}S();var x=g.create("transfer-verification"),A={maxSourceRegression:.05,minTargetImprovement:0,maxSourceConfidenceRegression:.1},b=class{config;constructor(e={}){this.config={...A,...e}}verifyTransfer(e){let t=e.sourcePerformanceAfter.successRate-e.sourcePerformanceBefore.successRate,r=e.targetPerformanceAfter.successRate-e.targetPerformanceBefore.successRate,n=e.sourcePerformanceAfter.avgConfidence-e.sourcePerformanceBefore.avgConfidence,a=e.targetPerformanceAfter.avgConfidence-e.targetPerformanceBefore.avgConfidence,s=t>=-this.config.maxSourceRegression&&n>=-this.config.maxSourceConfidenceRegression,c=r>=this.config.minTargetImprovement,u=s&&c,m;if(!u){let i=[];s||i.push(`source domain regressed: successRate delta=${t.toFixed(4)}, confidence delta=${n.toFixed(4)}`),c||i.push(`target domain did not improve: successRate delta=${r.toFixed(4)}`),m=i.join("; ")}return u?x.debug("Transfer verification passed",{transferId:e.transferId,sourceDelta:t,targetDelta:r}):x.warn("Transfer verification failed",{transferId:e.transferId,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourceDelta:t,targetDelta:r,failureReason:m}),{passed:u,sourceStable:s,targetImproved:c,sourceDelta:t,targetDelta:r,sourceConfidenceDelta:n,targetConfidenceDelta:a,failureReason:m}}getConfig(){return{...this.config}}};function M(o){return new b(o)}T();var p=class{alphas=new Map;betas=new Map;sample(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return this.sampleBeta(t,r)}update(e,t){t?this.alphas.set(e,(this.alphas.get(e)??1)+1):this.betas.set(e,(this.betas.get(e)??1)+1)}getMean(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t/(t+r)}getObservationCount(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t-1+(r-1)}getAlpha(e){return this.alphas.get(e)??1}getBeta(e){return this.betas.get(e)??1}sampleBeta(e,t){let r=this.sampleGamma(e),n=this.sampleGamma(t);return r+n===0?.5:r/(r+n)}sampleGamma(e){if(e<1){let n=Math.random();return this.sampleGamma(e+1)*Math.pow(n,1/e)}let t=e-1/3,r=1/Math.sqrt(9*t);for(;;){let n,a;do n=this.standardNormal(),a=1+r*n;while(a<=0);a=a*a*a;let s=Math.random();if(s<1-.0331*n*n*n*n||Math.log(s)<.5*n*n+t*(1-a+Math.log(a)))return t*a}}standardNormal(){let e=Math.random(),t=Math.random();return Math.sqrt(-2*Math.log(e||1e-10))*Math.cos(2*Math.PI*t)}};var I={threshold:5,slack:.5,resetOnAlarm:!0,warmupSamples:20},h=class{config;states=new Map;constructor(e={}){this.config={...I,...e}}update(e,t){let r=this.getOrCreateState(e);if(r.samplesSinceReset++,r.mu===null)return r.warmupSum+=t,r.warmupCount++,r.warmupCount>=this.config.warmupSamples&&(r.mu=r.warmupSum/r.warmupCount),{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:r.samplesSinceReset};r.sPlus=Math.max(0,r.sPlus+(t-r.mu-this.config.slack)),r.sMinus=Math.max(0,r.sMinus+(-t+r.mu-this.config.slack));let n=Math.max(r.sPlus,r.sMinus),a=!1,s="none";r.sPlus>this.config.threshold?(a=!0,s="positive"):r.sMinus>this.config.threshold&&(a=!0,s="negative");let c={driftDetected:a,cumulativeSum:n,direction:s,samplesSinceReset:r.samplesSinceReset};return a&&this.config.resetOnAlarm&&(r.sPlus=0,r.sMinus=0,r.samplesSinceReset=0),c}reset(e){e?this.states.delete(e):this.states.clear()}getState(e){let t=this.states.get(e);if(!t)return{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:0};let r=Math.max(t.sPlus,t.sMinus),n="none";return t.sPlus>this.config.threshold?n="positive":t.sMinus>this.config.threshold&&(n="negative"),{driftDetected:t.sPlus>this.config.threshold||t.sMinus>this.config.threshold,cumulativeSum:r,direction:n,samplesSinceReset:t.samplesSinceReset}}getOrCreateState(e){let t=this.states.get(e);return t||(t={sPlus:0,sMinus:0,samplesSinceReset:0,warmupSum:0,warmupCount:0,mu:null},this.states.set(e,t)),t}};var w=g.create("domain-transfer"),V={minTransferProbability:.3,explorationWarmup:5,verification:{},maxHistorySize:1e3,useMetaLearningEnhancements:!0},v=class{constructor(e=100){this.decayThreshold=e}decayThreshold;getDecayMultiplier(e){return e<=0?1:Math.pow(.5,e/this.decayThreshold)}applyDecay(e,t,r){return t+(e-t)*this.getDecayMultiplier(r)}},y=class{cusum;outcomes=[];windowSize;constructor(e=20){this.windowSize=e,this.cusum=new h({threshold:3,slack:.1,resetOnAlarm:!1,warmupSamples:Math.min(10,Math.floor(e/2))})}record(e){this.outcomes.push(e),this.outcomes.length>this.windowSize*2&&this.outcomes.splice(0,this.outcomes.length-this.windowSize*2);let t=this.getCurrentRate();this.cusum.update("learn",t)}isPlateaued(){return this.outcomes.length<this.windowSize?!1:!this.cusum.getState("learn").driftDetected}getCurrentRate(){if(this.outcomes.length===0)return 0;let e=this.outcomes.slice(-this.windowSize);return e.filter(Boolean).length/e.length}getOutcomeCount(){return this.outcomes.length}getCusumState(){return this.cusum.getState("learn")}},D=class{front=[];dominates(e,t){let r=e.successRate>=t.successRate&&e.speed>=t.speed&&e.confidence>=t.confidence,n=e.successRate>t.successRate||e.speed>t.speed||e.confidence>t.confidence;return r&&n}add(e){for(let t=this.front.length-1;t>=0;t--)this.dominates(e,this.front[t])&&this.front.splice(t,1);this.front.some(t=>this.dominates(t,e))||this.front.push(e)}getFront(){return[...this.front]}isNonDominated(e){return!this.front.some(t=>this.dominates(t,e))}},C=class{constructor(e=.2){this.bonusScale=e}bonusScale;triedPairs=new Set;markTried(e){this.triedPairs.add(e)}isTried(e){return this.triedPairs.has(e)}getBonus(e){return this.triedPairs.has(e)?0:this.bonusScale}apply(e,t){return Math.min(1,e+this.getBonus(t))}getTriedCount(){return this.triedPairs.size}},P=class{config;sampler;verifier;coherenceGate;transferHistory=[];affinityScores=new Map;performanceProvider=null;transferExecutor=null;nativeModule=null;decayingBeta;plateauDetector;paretoFront;curiosityBonus;constructor(e={}){this.config={...V,...e},this.sampler=new p,this.verifier=M(this.config.verification),this.coherenceGate=R(),this.decayingBeta=new v,this.plateauDetector=new y,this.paretoFront=new D,this.curiosityBonus=new C,this.tryLoadNativeModule()}evaluateTransfer(e,t){if(!this.isEnabled())return this.createRejectedCandidate(e,t);let r=this.makePairKey(e,t),n=this.sampler.sample(r),s=this.sampler.getObservationCount(r)<this.config.explorationWarmup,c=this.getAffinityScore(e,t);if(this.isMetaLearningEnabled()){let u=this.sampler.getMean(r),m=this.sampler.getAlpha(r)-1;n=this.decayingBeta.applyDecay(n,u,m),n=this.curiosityBonus.apply(n,r)}return{sourceDomain:e,targetDomain:t,sampledProbability:n,affinityScore:c,isExploration:s,pairKey:r}}executeTransfer(e){let t=`transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=this.coherenceGate.validateTransfer({domain:e.sourceDomain},e.targetDomain);if(!r.approved)return w.info("Transfer blocked by coherence gate",{transferId:t,source:e.sourceDomain,target:e.targetDomain,reason:r.rejectionReason}),this.createBlockedResult(t,e,r);let n=this.getPerformanceSnapshot(e.sourceDomain),a=this.getPerformanceSnapshot(e.targetDomain),s=this.computeSqrtDampening(e),c=this.doTransfer(e.sourceDomain,e.targetDomain,s),u=this.getPerformanceSnapshot(e.sourceDomain),m=this.getPerformanceSnapshot(e.targetDomain),i=this.verifier.verifyTransfer({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m}),f=c&&i.passed;if(this.sampler.update(e.pairKey,f),this.updateAffinityScore(e.pairKey,f),this.isMetaLearningEnabled()){this.plateauDetector.record(f),this.curiosityBonus.markTried(e.pairKey);let F=this.sampler.getMean(e.pairKey);this.paretoFront.add({pairKey:e.pairKey,successRate:F,speed:1/(1+s),confidence:this.getAffinityScore(e.sourceDomain,e.targetDomain)})}return this.addToHistory({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,success:f,sampledProbability:e.sampledProbability,dampeningFactor:s,sourceDelta:i.sourceDelta,targetDelta:i.targetDelta,timestamp:Date.now()}),w.info("Transfer completed",{transferId:t,source:e.sourceDomain,target:e.targetDomain,success:f,dampeningFactor:s.toFixed(4),sourceDelta:i.sourceDelta.toFixed(4),targetDelta:i.targetDelta.toFixed(4)}),{transferId:t,candidate:e,success:f,dampeningFactor:s,verification:i,coherenceResult:r,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m,timestamp:Date.now()}}getAffinityScore(e,t){return this.affinityScores.get(this.makePairKey(e,t))??.5}getTransferHistory(){return[...this.transferHistory]}getExpectedSuccessRate(e,t){return this.sampler.getMean(this.makePairKey(e,t))}getObservationCount(e,t){return this.sampler.getObservationCount(this.makePairKey(e,t))}setPerformanceProvider(e){this.performanceProvider=e}setTransferExecutor(e){this.transferExecutor=e}getSampler(){return this.sampler}getCoherenceGate(){return this.coherenceGate}getDecayingBeta(){return this.decayingBeta}getPlateauDetector(){return this.plateauDetector}getParetoFront(){return this.paretoFront}getCuriosityBonus(){return this.curiosityBonus}isLearningPlateaued(){return this.plateauDetector.isPlateaued()}isEnabled(){return l().useCrossDomainTransfer===!0}isMetaLearningEnabled(){return this.config.useMetaLearningEnhancements===!0&&l().useMetaLearningEnhancements!==!1}makePairKey(e,t){return`${e}->${t}`}computeSqrtDampening(e){let t=this.sampler.getObservationCount(e.pairKey);return Math.sqrt(t/(t+this.config.explorationWarmup))}doTransfer(e,t,r){return this.transferExecutor?this.transferExecutor(e,t,r):!0}getPerformanceSnapshot(e){return this.performanceProvider?this.performanceProvider(e):{domain:e,successRate:.5,avgConfidence:.5,patternCount:0,timestamp:Date.now()}}updateAffinityScore(e,t){let r=this.affinityScores.get(e)??.5;this.affinityScores.set(e,.2*(t?1:0)+.8*r)}addToHistory(e){for(this.transferHistory.push(e);this.transferHistory.length>this.config.maxHistorySize;)this.transferHistory.shift()}createBlockedResult(e,t,r){let n={domain:"",successRate:0,avgConfidence:0,patternCount:0,timestamp:Date.now()};return{transferId:e,candidate:t,success:!1,dampeningFactor:0,verification:{passed:!1,sourceStable:!1,targetImproved:!1,sourceDelta:0,targetDelta:0,sourceConfidenceDelta:0,targetConfidenceDelta:0,failureReason:`Coherence gate rejected: ${r.rejectionReason??"unknown"}`},coherenceResult:r,sourcePerformanceBefore:{...n,domain:t.sourceDomain},sourcePerformanceAfter:{...n,domain:t.sourceDomain},targetPerformanceBefore:{...n,domain:t.targetDomain},targetPerformanceAfter:{...n,domain:t.targetDomain},timestamp:Date.now()}}createRejectedCandidate(e,t){return{sourceDomain:e,targetDomain:t,sampledProbability:0,affinityScore:0,isExploration:!1,pairKey:this.makePairKey(e,t)}}tryLoadNativeModule(){this.nativeModule=null}};function J(o){return new P(o)}export{h as a,p as b,V as c,v as d,y as e,D as f,C as g,P as h,J as i};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.
|
|
2
|
-
import{c as R,g as N,i as O}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.3");process.exit(0)}
|
|
2
|
+
import{c as R,g as N,i as O}from"./chunk-5IH22DLD.js";import{i as S,m as w}from"./chunk-DPJLA7JW.js";import{b as g,d as D}from"./chunk-2G2XD6EM.js";import{a as L}from"./chunk-WVWWTRKT.js";import{a as u,c as q}from"./chunk-XRF5MX4Q.js";import{i as f}from"./chunk-FF53QW6C.js";import{a as h,b as C}from"./chunk-2BYRQ5MV.js";C();D();q();w();var P={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:256*1024*1024,cacheSize:-64e3,foreignKeys:!0,useUnified:!0};function F(_,e=384){let n=new Array(e).fill(0),t=_.toLowerCase().trim();for(let a=0;a<3;a++)for(let s=0;s<t.length;s++){let i=t.charCodeAt(s),o=i*(s+1)*(a+1)%e;n[o]+=Math.sin(i*(a+1))/(s+1)}let r=Math.sqrt(n.reduce((a,s)=>a+s*s,0));if(r>0)for(let a=0;a<e;a++)n[a]/=r;return n}var b=class{db=null;config;prepared=new Map;initialized=!1;unifiedMemory=null;constructor(e={}){this.config={...P,...e}}getDatabase(){return this.db}async initialize(){if(!this.initialized)try{if(this.config.useUnified)this.unifiedMemory=S(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[SQLitePatternStore] Using unified storage: ${this.unifiedMemory.getDbPath()}`);else{let e=await import("path"),n=await import("fs"),t=e.dirname(this.config.dbPath);n.existsSync(t)||n.mkdirSync(t,{recursive:!0}),this.db=h(this.config.dbPath),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.config.foreignKeys&&this.db.pragma("foreign_keys = ON"),this.createSchema(),console.log(`[SQLitePatternStore] Initialized (legacy): ${this.config.dbPath}`)}this.deduplicatePatterns(),this.prepareStatements(),this.initialized=!0}catch(e){throw new Error(`Failed to initialize SQLite: ${u(e)}`)}}createSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
|
|
3
3
|
-- QE Patterns table
|
|
4
4
|
CREATE TABLE IF NOT EXISTS qe_patterns (
|
|
5
5
|
id TEXT PRIMARY KEY,
|
|
@@ -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 R}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.3");process.exit(0)}
|
|
2
|
+
import{a as R}from"./chunk-7AHQ7ROU.js";import{m as T}from"./chunk-DPJLA7JW.js";import{b as S}from"./chunk-NIA6VTIH.js";import{a as b,c as P}from"./chunk-XRF5MX4Q.js";import{i as h}from"./chunk-FF53QW6C.js";import{a as M}from"./chunk-3CFWNT3F.js";T();P();import*as f from"path";import*as c from"fs";function C(){return process.env.AQE_MEMORY_BACKEND==="memory"}var s=null,d=null,g=null;function O(o){g=o}async function x(){return s||d||(d=(async()=>{if(C()){let r=new M;return await r.initialize(),s=r,r}let o=S(),e=f.join(o,".agentic-qe");c.existsSync(e)||c.mkdirSync(e,{recursive:!0});let t=new R({sqlite:{path:f.join(e,"memory.db"),walMode:!0,poolSize:3,busyTimeout:5e3},enableFallback:!0,defaultNamespace:"mcp-tools"});return await t.initialize(),s=t,t})(),d)}function E(){if(g)try{g()}catch{}s&&(s.dispose().catch(()=>{}),s=null),d=null}async function q(o){return o?.memory?o.memory:x()}var m=null,l=null;function L(){let o=(process.env.AQE_LLM_ROUTER_DISABLED??"").trim().toLowerCase();return o?o!=="false"&&o!=="0"&&o!=="no"&&o!=="off":!1}function I(o){m=o,l=null}async function w(){return L()?null:m||l||(l=(async()=>{let{createLLMRouterService:o}=await import("./llm-router-service-NKHEQQMN.js"),e=await o();return e?(m=e.router,m):null})(),l)}function H(){m=null,l=null}async function K(o){return o?.llmRouter?o.llmRouter:await w()??void 0}async function N(o){if(o?.kernel)return o.kernel;try{let{getFleetState:e}=await import("./core-handlers-U2YJLH6O.js");return e().kernel??void 0}catch{return}}var v={info:(o,e)=>console.log(`[MCP-TOOL] ${o}`,e||""),warn:(o,e)=>console.warn(`[MCP-TOOL] \u26A0\uFE0F ${o}`,e||""),error:(o,e)=>console.error(`[MCP-TOOL] \u274C ${o}`,e||"")},k=class{logger=v;currentDataSource="real";setLogger(e){this.logger=e}markAsDemoData(e,t){this.currentDataSource=e.demoMode?"demo":"fallback",this.logger.warn(`${this.config.name} returning ${this.currentDataSource} data`,{reason:t,requestId:e.requestId,demoMode:e.demoMode})}markAsRealData(){this.currentDataSource="real"}isDemoMode(e){return e.demoMode===!0}validate(e){let t=[];if(typeof e!="object"||e===null)return{valid:!1,errors:["Parameters must be an object"]};let r=e,{properties:i,required:n}=this.config.schema;if(n)for(let a of n)a in r||t.push(`Missing required field: ${a}`);for(let[a,u]of Object.entries(r)){let p=i[a];if(!p)continue;let y=this.validateType(a,u,p);y&&t.push(y)}return{valid:t.length===0,errors:t}}validateType(e,t,r){if(t==null)return null;let i=Array.isArray(t)?"array":typeof t;if(r.type==="array"&&!Array.isArray(t))return`${e} must be an array`;if(r.type!=="array"&&i!==r.type)return`${e} must be of type ${r.type}, got ${i}`;if(r.enum&&!r.enum.includes(t))return`${e} must be one of: ${r.enum.join(", ")}`;if(r.type==="number"){let n=t;if(r.minimum!==void 0&&n<r.minimum)return`${e} must be >= ${r.minimum}`;if(r.maximum!==void 0&&n>r.maximum)return`${e} must be <= ${r.maximum}`}if(r.type==="string"){let n=t;if(r.minLength!==void 0&&n.length<r.minLength)return`${e} must be at least ${r.minLength} characters`;if(r.maxLength!==void 0&&n.length>r.maxLength)return`${e} must be at most ${r.maxLength} characters`}return null}async invoke(e,t={}){let r=Date.now(),i=h();this.currentDataSource="real";let n=this.validate(e);if(!n.valid)return{success:!1,error:`Validation failed: ${n.errors.join("; ")}`,metadata:this.createMetadata(r,i)};let a={requestId:i,startTime:r,streaming:t.streaming,onStream:t.onStream,abortSignal:t.abortSignal,demoMode:t.demoMode,memory:t.memory,llmRouter:t.llmRouter,kernel:t.kernel};try{let u=await this.execute(e,a);return{...u,metadata:{...u.metadata,...this.createMetadata(r,i)}}}catch(u){return{success:!1,error:b(u),metadata:this.createMetadata(r,i)}}}createMetadata(e,t){return{executionTime:Date.now()-e,timestamp:new Date().toISOString(),requestId:t,domain:this.config.domain,toolName:this.config.name,dataSource:this.currentDataSource}}emitStream(e,t){e.streaming&&e.onStream&&e.onStream(t)}isAborted(e){return e.abortSignal?.aborted??!1}get name(){return this.config.name}get description(){return this.config.description}get domain(){return this.config.domain}getSchema(){return this.config.schema}get timeout(){return this.config.timeout??6e4}get supportsStreaming(){return this.config.streaming??!1}resetInstanceCache(){}};export{C as a,O as b,x as c,E as d,q as e,I as f,w as g,H as h,K as i,N as j,v as k,k as l};
|
|
@@ -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 b}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.3");process.exit(0)}
|
|
2
|
+
import{a as b}from"./chunk-T5L65R23.js";import{c as k}from"./chunk-66KIIH6V.js";import{b as p,d as C}from"./chunk-2G2XD6EM.js";C();b();var m=k.create("skill-validation-learner"),v=class{constructor(e){this.reasoningBank=e}reasoningBank;memoryNamespace="skill-validation";feedbackLoop=null;connectFeedbackLoop(e){this.feedbackLoop=e}async recordValidationOutcome(e){await this.reasoningBank.storeQEPattern({patternType:"test-template",name:`${e.skillName}-validation-${e.validationLevel}`,description:`Validation outcome for ${e.skillName} at level ${e.validationLevel}`,context:{tags:["skill-validation",e.skillName,e.model,e.validationLevel],testType:"integration"},template:{type:"config",content:JSON.stringify({outcome:{skillName:e.skillName,trustTier:e.trustTier,validationLevel:e.validationLevel,model:e.model,passed:e.passed,score:e.score,testCaseCount:e.testCaseResults.length,passedTests:e.testCaseResults.filter(s=>s.passed).length,avgReasoningQuality:this.calculateAvgReasoningQuality(e.testCaseResults),timestamp:e.timestamp.toISOString(),runId:e.runId,metadata:e.metadata}}),variables:[]}}),await this.updateSkillConfidence(e),e.validationLevel==="eval"&&await this.trackCrossModelBehavior(e),this.feedbackLoop&&e.runId&&await this.recordToFeedbackLoop(e)}async updateSkillConfidence(e){let s=`skill-confidence-${e.skillName}`,n=await this.reasoningBank.searchQEPatterns(s,{limit:1}),t;if(n.success&&n.value.length>0)try{let r=n.value[0].pattern.template?.content;if(r){let i=p(r);i&&typeof i=="object"&&Array.isArray(i.outcomes)?t=i:t=this.createEmptyConfidence(e.skillName)}else t=this.createEmptyConfidence(e.skillName)}catch(a){m.debug("Confidence history parse failed",{skill:e.skillName,error:a instanceof Error?a.message:String(a)}),t=this.createEmptyConfidence(e.skillName)}else t=this.createEmptyConfidence(e.skillName);t.outcomes.push({score:e.score,timestamp:e.timestamp,model:e.model,validationLevel:e.validationLevel,passed:e.passed}),t.outcomes.length>100&&(t.outcomes=t.outcomes.slice(-100)),t.avgScore=t.outcomes.reduce((a,r)=>a+r.score,0)/t.outcomes.length,t.lastUpdated=new Date,t.trend=this.calculateTrend(t.outcomes),t.byLevel=this.calculateConfidenceByLevel(t.outcomes),await this.reasoningBank.storeQEPattern({patternType:"test-template",name:s,description:`Skill confidence tracking for ${e.skillName}`,context:{tags:["skill-confidence",e.skillName]},template:{type:"config",content:JSON.stringify(t),variables:[]}})}async trackCrossModelBehavior(e){let s=`cross-model-${e.skillName}`,n=await this.reasoningBank.searchQEPatterns(s,{limit:1}),t;if(n.success&&n.value.length>0)try{let c=n.value[0].pattern.template?.content;if(c){let l=p(c);l&&typeof l=="object"&&typeof l.models=="object"?t=l:t=this.createEmptyCrossModelAnalysis()}else t=this.createEmptyCrossModelAnalysis()}catch(o){m.debug("Cross-model analysis parse failed",{error:o instanceof Error?o.message:String(o)}),t=this.createEmptyCrossModelAnalysis()}else t=this.createEmptyCrossModelAnalysis();t.models||(t.models={}),t.models[e.model]||(t.models[e.model]={scores:[],passRate:0,avgReasoningQuality:0,sampleCount:0});let a=t.models[e.model];a.scores.push(e.score),a.sampleCount++,a.scores.length>50&&(a.scores=a.scores.slice(-50));let r=this.calculateAvgReasoningQuality(e.testCaseResults);a.passRate=a.scores.filter(o=>o>=.9).length/a.scores.length,a.avgReasoningQuality=(a.avgReasoningQuality*(a.sampleCount-1)+r)/a.sampleCount;let i=Object.values(t.models).map(o=>o.passRate);if(i.length>1){let o=i.reduce((l,d)=>l+d,0)/i.length,c=i.reduce((l,d)=>l+Math.pow(d-o,2),0)/i.length;t.variance=c,t.hasAnomalies=c>.04,t.anomalies=[];for(let[l,d]of Object.entries(t.models))Math.abs(d.passRate-o)>.2&&t.anomalies.push({model:l,type:d.passRate<o?"low_performance":"high_variance",description:`Model ${l} has ${((d.passRate-o)*100).toFixed(1)}% difference from average`})}t.lastUpdated=new Date,await this.reasoningBank.storeQEPattern({patternType:"test-template",name:s,description:`Cross-model behavior tracking for ${e.skillName}`,context:{tags:["cross-model",e.skillName]},template:{type:"config",content:JSON.stringify(t),variables:[]}})}async recordToFeedbackLoop(e){if(!this.feedbackLoop)return;let s={taskId:e.runId,taskDescription:`Skill validation: ${e.skillName} (${e.validationLevel})`,recommendedAgent:"skill-validator",usedAgent:"skill-validator",followedRecommendation:!0,success:e.passed,qualityScore:e.score,durationMs:e.metadata?.duration||0,timestamp:e.timestamp};await this.feedbackLoop.recordRoutingOutcome(s)}async getSkillConfidence(e){let s=`skill-confidence-${e}`,n=await this.reasoningBank.searchQEPatterns(s,{limit:1});if(n.success&&n.value.length>0)try{let t=n.value[0].pattern.template?.content;if(t)return p(t)}catch(t){m.debug("Skill confidence pattern content invalid",{skill:e,error:t instanceof Error?t.message:String(t)})}return null}async getCrossModelAnalysis(e){let s=`cross-model-${e}`,n=await this.reasoningBank.searchQEPatterns(s,{limit:1});if(n.success&&n.value.length>0)try{let t=n.value[0].pattern.template?.content;if(t)return p(t)}catch(t){m.debug("Cross-model pattern content invalid",{skill:e,error:t instanceof Error?t.message:String(t)})}return null}async queryValidationPatterns(e,s=10){let n=await this.reasoningBank.searchQEPatterns(`${e} validation`,{limit:s});return n.success?n.value.filter(t=>t.pattern.context?.tags?.includes("skill-validation")).map(t=>t.pattern):[]}async getValidationTrends(e){let s=await this.getSkillConfidence(e),n=await this.getCrossModelAnalysis(e);if(!s)return null;let t={};if(n)for(let i of Object.keys(n.models)){let o=s.outcomes.filter(c=>c.model===i).map(c=>({score:c.score}));t[i]=this.calculateTrend(o)}let a=s.outcomes.slice(-20),r=a.filter(i=>i.passed).length/a.length;return{overall:s.trend||"stable",byModel:t,recentPassRate:r}}async extractLearnedPatterns(e){let s=await this.queryValidationPatterns(e,50),n=[],t=new Map;for(let a of s)try{let i=p(a.template?.content||"{}").outcome?.metadata?.category||"general";t.has(i)||t.set(i,[]),t.get(i).push(a)}catch(r){m.debug("Invalid pattern during category grouping",{error:r instanceof Error?r.message:String(r)})}for(let[a,r]of Array.from(t.entries())){let i=new Set,o=new Set,c=new Set,l=0;for(let d of r)try{let f=p(d.template?.content||"{}").outcome;if(!f)continue;c.add(f.model),l+=f.score;let h=d.context?.tags||[];f.passed?h.filter(g=>!["skill-validation",e].includes(g)).forEach(g=>i.add(g)):h.filter(g=>!["skill-validation",e].includes(g)).forEach(g=>o.add(g))}catch(u){m.debug("Invalid pattern during category extraction",{error:u instanceof Error?u.message:String(u)})}r.length>0&&n.push({id:`${e}-${a}`,skillName:e,category:a,successIndicators:Array.from(i),failureIndicators:Array.from(o),models:Array.from(c),confidence:l/r.length,observationCount:r.length})}return n}createEmptyConfidence(e){return{skillName:e,avgScore:0,outcomes:[],lastUpdated:new Date}}createEmptyCrossModelAnalysis(){return{models:{},variance:0,hasAnomalies:!1,lastUpdated:new Date}}calculateAvgReasoningQuality(e){return e.length===0?0:e.reduce((s,n)=>s+n.reasoningQuality,0)/e.length}calculateTrend(e){if(e.length<5)return"stable";let s=e.slice(-10),n=e.slice(-20,-10);if(n.length===0)return"stable";let t=s.reduce((i,o)=>i+o.score,0)/s.length,a=n.reduce((i,o)=>i+o.score,0)/n.length,r=t-a;return r>.05?"improving":r<-.05?"declining":"stable"}calculateConfidenceByLevel(e){let s={schema:[],validator:[],eval:[]};for(let t of e)t.validationLevel&&s[t.validationLevel].push(t.score);let n={};for(let[t,a]of Object.entries(s))a.length>0&&(n[t]=a.reduce((r,i)=>r+i,0)/a.length);return n}};function L(y){return new v(y)}export{L as a};
|