agentic-qe 3.14.1 → 3.14.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +37 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +7 -7
- package/dist/cli/chunks/adapter-OJF6LAJV.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-OY5Y2CUM.js → agent-booster-wasm-SD5N32MX.js} +2 -2
- package/dist/cli/chunks/{agent-handler-TUOH55LD.js → agent-handler-OZRSJM7F.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-XM3IYKT3.js → agent-memory-branch-NYTRANRN.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-FGT474XB.js +2 -0
- package/dist/cli/chunks/{arena-DOCLIEBL.js → arena-EX3SC2DP.js} +4 -4
- package/dist/cli/chunks/{arena-UMFJZKG7.js → arena-FOTVSRK4.js} +2 -2
- package/dist/cli/chunks/{audit-KZLU5VLW.js → audit-Q5GHSUQY.js} +3 -3
- package/dist/cli/chunks/base-HH765JFV.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-MIEZBNUI.js → better-sqlite3-S7M5R2HS.js} +2 -2
- package/dist/cli/chunks/{brain-handler-6PZN46B7.js → brain-handler-5FSA46R5.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-XCETHA4F.js → branch-enumerator-RWAXTGEU.js} +2 -2
- package/dist/cli/chunks/{browser-UEXISDCJ.js → browser-IGDESJGF.js} +2 -2
- package/dist/cli/chunks/browser-workflow-NPM4FUPI.js +2 -0
- package/dist/cli/chunks/{chunk-UUE5CBZQ.js → chunk-2EHFEMRU.js} +2 -2
- package/dist/cli/chunks/{chunk-7AF55H2D.js → chunk-2H5YJ5ZK.js} +2 -2
- package/dist/cli/chunks/chunk-2LKAMMMI.js +2 -0
- package/dist/cli/chunks/{chunk-JJ4GUO4K.js → chunk-2TG24LYQ.js} +1 -1
- package/dist/cli/chunks/{chunk-3BRR2FLH.js → chunk-3C2K4YMS.js} +3 -3
- package/dist/cli/chunks/{chunk-VUXHJPUS.js → chunk-3DFFFXXO.js} +2 -2
- package/dist/cli/chunks/{chunk-RUEHSOE6.js → chunk-3WV4H33V.js} +1 -1
- package/dist/cli/chunks/{chunk-LQDFWLKK.js → chunk-42WUDDUU.js} +2 -2
- package/dist/cli/chunks/{chunk-EEJP3WTQ.js → chunk-4AKGBUYD.js} +2 -2
- package/dist/cli/chunks/{chunk-HKU5PPS7.js → chunk-4K27ESCA.js} +1 -1
- package/dist/cli/chunks/{chunk-X5G3UDWP.js → chunk-4M6A3PVJ.js} +2 -2
- package/dist/cli/chunks/{chunk-JMULRLD4.js → chunk-4MH22236.js} +1 -1
- package/dist/cli/chunks/{chunk-KXTN3FR4.js → chunk-4N44UJGI.js} +2 -2
- package/dist/cli/chunks/{chunk-UCJEAK7D.js → chunk-4PH7O5ZH.js} +2 -2
- package/dist/cli/chunks/{chunk-HPQU6XZH.js → chunk-4RT7I7PI.js} +1 -1
- package/dist/cli/chunks/{chunk-GYTWUOKU.js → chunk-4UCMTYFQ.js} +4 -4
- package/dist/cli/chunks/{chunk-AESYVAPH.js → chunk-4ZUZDFAA.js} +2 -2
- package/dist/cli/chunks/{chunk-TQ2JZVZ3.js → chunk-57TNBR2P.js} +2 -2
- package/dist/cli/chunks/{chunk-TLD727EF.js → chunk-5EHLGOWW.js} +2 -2
- package/dist/cli/chunks/{chunk-ERTGGFXZ.js → chunk-5WJUNRTY.js} +2 -2
- package/dist/cli/chunks/{chunk-CBWF42ET.js → chunk-67A6PEZM.js} +2 -2
- package/dist/cli/chunks/{chunk-PMUF7WU6.js → chunk-6EHN7Q2Q.js} +2 -2
- package/dist/cli/chunks/{chunk-FZ47ZCRL.js → chunk-6F4WHN7D.js} +1 -1
- package/dist/cli/chunks/{chunk-S53ZUAVI.js → chunk-6LMLN5R2.js} +2 -2
- package/dist/cli/chunks/{chunk-Y63V33M6.js → chunk-6SZKLWZT.js} +5 -5
- package/dist/cli/chunks/{chunk-EHW62JL2.js → chunk-6VKJAMZY.js} +1 -1
- package/dist/cli/chunks/{chunk-ND6JBUVH.js → chunk-7AFBNU6K.js} +2 -2
- package/dist/cli/chunks/{chunk-LMPK63PO.js → chunk-7FWP7CZY.js} +3 -3
- package/dist/cli/chunks/{chunk-LSXQPMPI.js → chunk-7SK6IMGZ.js} +2 -2
- package/dist/cli/chunks/{chunk-RCHDSUVU.js → chunk-A7N3YUDJ.js} +2 -2
- package/dist/cli/chunks/{chunk-MZ2PJUN6.js → chunk-ADK7DF3G.js} +2 -2
- package/dist/cli/chunks/{chunk-VEWYUEVY.js → chunk-ARMZYHYL.js} +2 -2
- package/dist/cli/chunks/{chunk-IGRTQ6VT.js → chunk-BWRHOIYC.js} +2 -2
- package/dist/cli/chunks/{chunk-MFAN5W27.js → chunk-C7AXRI7E.js} +1 -1
- package/dist/cli/chunks/{chunk-UN7EHLRV.js → chunk-CG2MUD7U.js} +1 -1
- package/dist/cli/chunks/{chunk-QM6EJHP5.js → chunk-CH2TQCV5.js} +1 -1
- package/dist/cli/chunks/{chunk-UWRMPRY5.js → chunk-CIESXO73.js} +1 -1
- package/dist/cli/chunks/{chunk-3WSH4HD2.js → chunk-CJCT452S.js} +2 -2
- package/dist/cli/chunks/{chunk-SEKOMKNG.js → chunk-CJHVOBJY.js} +1 -1
- package/dist/cli/chunks/{chunk-5TYGSQOL.js → chunk-CTCQOYBS.js} +1 -1
- package/dist/cli/chunks/{chunk-NAJCQJSK.js → chunk-D4RCV4LY.js} +2 -2
- package/dist/cli/chunks/{chunk-KHUO4NCW.js → chunk-DRO5NJZA.js} +2 -2
- package/dist/cli/chunks/{chunk-5F5V4QYU.js → chunk-DVHWLAEO.js} +3 -3
- package/dist/cli/chunks/{chunk-EPBWFTHH.js → chunk-DW6ZMNMR.js} +2 -2
- package/dist/cli/chunks/{chunk-PS6Y662P.js → chunk-E3Q7WNJD.js} +3 -3
- package/dist/cli/chunks/{chunk-ODNLKYOM.js → chunk-EAJK25IS.js} +1 -1
- package/dist/cli/chunks/{chunk-JZUWPDVS.js → chunk-EH5OCHAJ.js} +1 -1
- package/dist/cli/chunks/{chunk-MDLLEUFN.js → chunk-F2KRT2II.js} +3 -3
- package/dist/cli/chunks/{chunk-O7KF3GBV.js → chunk-FPHPP5TQ.js} +1 -1
- package/dist/cli/chunks/{chunk-FOAFRC2W.js → chunk-FREF6Y4L.js} +2 -2
- package/dist/cli/chunks/{chunk-6HMNN2Y2.js → chunk-FVGTINVR.js} +10 -10
- package/dist/cli/chunks/{chunk-GH3NJOTC.js → chunk-G2CLZVYI.js} +3 -3
- package/dist/cli/chunks/{chunk-SZRDEPUY.js → chunk-G6AV2HGY.js} +3 -3
- package/dist/cli/chunks/{chunk-DKXSJDII.js → chunk-GHQ5PUOV.js} +2 -2
- package/dist/cli/chunks/{chunk-6Z6Y3YBX.js → chunk-GHUPID5E.js} +1 -1
- package/dist/cli/chunks/{chunk-FH7SCX2I.js → chunk-GJAWEUIN.js} +2 -2
- package/dist/cli/chunks/{chunk-CGDW47WP.js → chunk-HBTC4L53.js} +2 -2
- package/dist/cli/chunks/{chunk-HBAQVJDP.js → chunk-HSJ5FQCF.js} +2 -2
- package/dist/cli/chunks/{chunk-5NSSJUWW.js → chunk-HZ6NEJMO.js} +2 -2
- package/dist/cli/chunks/{chunk-IYB3GRXF.js → chunk-HZMLNM2T.js} +10 -10
- package/dist/cli/chunks/{chunk-J7VAD4RG.js → chunk-ICKLBATY.js} +2 -2
- package/dist/cli/chunks/{chunk-CCZZZBAO.js → chunk-IUNMW454.js} +2 -2
- package/dist/cli/chunks/{chunk-RYHCYTFE.js → chunk-IVGVOGIZ.js} +1 -1
- package/dist/cli/chunks/{chunk-T7XYQX5G.js → chunk-IWFL6EFI.js} +2 -2
- package/dist/cli/chunks/{chunk-D6RCRTTR.js → chunk-JDXLCNKV.js} +2 -2
- package/dist/cli/chunks/{chunk-PYAH4K2U.js → chunk-JIUF6NV6.js} +2 -2
- package/dist/cli/chunks/{chunk-7GF6IRSU.js → chunk-JQ2ZD3WO.js} +2 -2
- package/dist/cli/chunks/{chunk-OBKMLOHU.js → chunk-K574FLVB.js} +2 -2
- package/dist/cli/chunks/{chunk-6DDMHZWH.js → chunk-KEEBUVGV.js} +2 -2
- package/dist/cli/chunks/{chunk-4MT62HKK.js → chunk-KFXZDQ5J.js} +1 -1
- package/dist/cli/chunks/{chunk-3XRXUVUI.js → chunk-KPFG4OIM.js} +1 -1
- package/dist/cli/chunks/{chunk-IIBXGHZT.js → chunk-KZOBLLXW.js} +2 -2
- package/dist/cli/chunks/{chunk-HCCILQGN.js → chunk-L2F7FVIU.js} +2 -2
- package/dist/cli/chunks/{chunk-ZC3HC6FO.js → chunk-LML5VTFK.js} +1 -1
- package/dist/cli/chunks/{chunk-FRRRDCXY.js → chunk-LWUJQGCS.js} +2 -2
- package/dist/cli/chunks/{chunk-TT7DF2GX.js → chunk-MH73D5TN.js} +2 -2
- package/dist/cli/chunks/{chunk-TF33GKWA.js → chunk-MWQTACNA.js} +2 -2
- package/dist/cli/chunks/{chunk-HJD52N32.js → chunk-N3RN4QTC.js} +2 -2
- package/dist/cli/chunks/{chunk-45S5553E.js → chunk-N5ZRUOMR.js} +2 -2
- package/dist/cli/chunks/{chunk-KXMW7XTJ.js → chunk-NAZVPZJS.js} +2 -2
- package/dist/cli/chunks/{chunk-LJ63HPPN.js → chunk-NG2UVPTW.js} +1 -1
- package/dist/cli/chunks/{chunk-J33LKXVH.js → chunk-NHHWLJQF.js} +1 -1
- package/dist/cli/chunks/{chunk-JNSTKE3K.js → chunk-NNOMDM4N.js} +2 -2
- package/dist/cli/chunks/{chunk-DKUKGBJE.js → chunk-NRR23SJV.js} +1 -1
- package/dist/cli/chunks/{chunk-7AYTM426.js → chunk-NWFIJNEB.js} +1 -1
- package/dist/cli/chunks/{chunk-75SC3GEX.js → chunk-OBCKP3G4.js} +2 -2
- package/dist/cli/chunks/{chunk-QAE4BOIV.js → chunk-OC2CKU7I.js} +2 -2
- package/dist/cli/chunks/{chunk-QMTBWHGR.js → chunk-OX6T26CD.js} +3 -3
- package/dist/cli/chunks/chunk-P64DMQ2C.js +2 -0
- package/dist/cli/chunks/{chunk-6B77GPWL.js → chunk-PFXX5Q32.js} +2 -2
- package/dist/cli/chunks/chunk-PHHXHG2W.js +2 -0
- package/dist/cli/chunks/{chunk-FHBGALBG.js → chunk-PMUBG2RU.js} +2 -2
- package/dist/cli/chunks/{chunk-S4WIAKPL.js → chunk-PVHO6KLB.js} +1 -1
- package/dist/cli/chunks/{chunk-Z5YU2TDS.js → chunk-PWEIDHT7.js} +2 -2
- package/dist/cli/chunks/{chunk-PS5NIMWJ.js → chunk-PZKZY6PB.js} +2 -2
- package/dist/cli/chunks/{chunk-5KP62DC3.js → chunk-Q335R4MR.js} +2 -2
- package/dist/cli/chunks/{chunk-C3XNFIOM.js → chunk-Q3JHS3UD.js} +2 -2
- package/dist/cli/chunks/{chunk-FFRKTZYP.js → chunk-QFUX7ELG.js} +2 -2
- package/dist/cli/chunks/{chunk-5Y2QFSVZ.js → chunk-QW4LN5NK.js} +2 -2
- package/dist/cli/chunks/{chunk-VVP2ROXD.js → chunk-QXTW7XCS.js} +2 -2
- package/dist/cli/chunks/{chunk-L66BWYQH.js → chunk-R5RNOLHI.js} +1 -1
- package/dist/cli/chunks/{chunk-NEEZ6M4W.js → chunk-RCI64RIJ.js} +2 -2
- package/dist/cli/chunks/{chunk-5T6PAUZD.js → chunk-RFNEHNJV.js} +1 -1
- package/dist/cli/chunks/{chunk-HRUQWABO.js → chunk-RGH3WGWD.js} +3 -3
- package/dist/cli/chunks/{chunk-3JMSXOU4.js → chunk-RHJVDCLV.js} +2 -2
- package/dist/cli/chunks/{chunk-FPBQ7BXU.js → chunk-RVCWSAXI.js} +2 -2
- package/dist/cli/chunks/{chunk-ZAHCVRR7.js → chunk-RYJHREYS.js} +2 -2
- package/dist/cli/chunks/{chunk-NNJ63W77.js → chunk-S4MR6RTE.js} +1 -1
- package/dist/cli/chunks/{chunk-TGFJUL6M.js → chunk-S7N4BKI3.js} +2 -2
- package/dist/cli/chunks/{chunk-A6RB34Y6.js → chunk-SEHCX4NH.js} +1 -1
- package/dist/cli/chunks/{chunk-AZUC7E5S.js → chunk-T46LOLW3.js} +2 -2
- package/dist/cli/chunks/{chunk-L4WATX6B.js → chunk-T4C56HBW.js} +2 -2
- package/dist/cli/chunks/{chunk-3FFMUB3B.js → chunk-TENYL5TI.js} +2 -2
- package/dist/cli/chunks/{chunk-J2VF7ZO7.js → chunk-TLPL3EQY.js} +2 -2
- package/dist/cli/chunks/{chunk-7XL2D56F.js → chunk-TYVQNYXX.js} +4 -4
- package/dist/cli/chunks/{chunk-H5LSXVWY.js → chunk-U2AY57XZ.js} +2 -2
- package/dist/cli/chunks/{chunk-3TMUCJNJ.js → chunk-U54OOA24.js} +1 -1
- package/dist/cli/chunks/{chunk-3AYNHOWS.js → chunk-UHTAI4ZB.js} +1 -1
- package/dist/cli/chunks/{chunk-RXPHQ4ZE.js → chunk-UIGEUEBT.js} +2 -2
- package/dist/cli/chunks/{chunk-GO66DCIZ.js → chunk-UYTWDS2R.js} +2 -2
- package/dist/cli/chunks/{chunk-RVCMZUSJ.js → chunk-VNAKBHJI.js} +2 -2
- package/dist/cli/chunks/{chunk-4ZLFUO4I.js → chunk-VOYJJ3KA.js} +2 -2
- package/dist/cli/chunks/{chunk-DKSLJZVA.js → chunk-VSYBMNIR.js} +1 -1
- package/dist/cli/chunks/{chunk-6YIMLUH6.js → chunk-W2FLULF4.js} +2 -2
- package/dist/cli/chunks/{chunk-OBLHI4HA.js → chunk-W4OQYLYO.js} +1 -1
- package/dist/cli/chunks/{chunk-DFXQLHQM.js → chunk-WBH4C4BG.js} +2 -2
- package/dist/cli/chunks/{chunk-RXHI6CKK.js → chunk-WBMRADQP.js} +1 -1
- package/dist/cli/chunks/{chunk-B6Y6AF4M.js → chunk-WMW47QMR.js} +2 -2
- package/dist/cli/chunks/{chunk-N22LMACN.js → chunk-WVY22NHZ.js} +2 -2
- package/dist/cli/chunks/{chunk-PMREFRPP.js → chunk-WXMSRBQF.js} +2 -2
- package/dist/cli/chunks/{chunk-IYIMLLUV.js → chunk-XPLSLHRB.js} +1 -1
- package/dist/cli/chunks/{chunk-PZZX57ZA.js → chunk-YF5OP6CR.js} +2 -2
- package/dist/cli/chunks/{chunk-WFJKLM6Z.js → chunk-YN6W2XIT.js} +3 -3
- package/dist/cli/chunks/{chunk-QIY43XQJ.js → chunk-ZCDXJ27H.js} +1 -1
- package/dist/cli/chunks/{chunk-F7TRO2OM.js → chunk-ZFGND4QK.js} +1 -1
- package/dist/cli/chunks/{chunk-H2DX36SC.js → chunk-ZWRQ5VAU.js} +2 -2
- package/dist/cli/chunks/{chunk-GRVR3Y6I.js → chunk-ZYLSOBOR.js} +1 -1
- package/dist/cli/chunks/{ci-Q2VX75PS.js → ci-NTRH7PAW.js} +2 -2
- package/dist/cli/chunks/{ci-output-MD5GTVR2.js → ci-output-F57RSD35.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-JMRLG2XI.js → circuit-breaker-4WST3QSA.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-IMXYALBU.js → claude-flow-setup-KB4TKMYI.js} +2 -2
- package/dist/cli/chunks/client-GPZEC54E.js +2 -0
- package/dist/cli/chunks/{cline-installer-HWFASEGE.js → cline-installer-W2ZHQ6WM.js} +2 -2
- package/dist/cli/chunks/{code-3V37TCAD.js → code-TF2AVR5D.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-5V54WGFL.js → code-index-extractor-RMDRUVQJ.js} +2 -2
- package/dist/cli/chunks/{codex-installer-UCA5AVE6.js → codex-installer-VSTRHJHV.js} +2 -2
- package/dist/cli/chunks/{completions-2DMRCQU6.js → completions-3Q37QVFR.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-MMQRXBTD.js → complexity-analyzer-3FNFLACD.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-FAARXP3S.js → continuedev-installer-VTEXM455.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-AKQALMB5.js → copilot-installer-AGY7DQUS.js} +2 -2
- package/dist/cli/chunks/core-handlers-YMGHYIBR.js +2 -0
- package/dist/cli/chunks/{cost-tracker-AXWHDND5.js → cost-tracker-LTZAQBX7.js} +2 -2
- package/dist/cli/chunks/{coverage-ZLSKKCG5.js → coverage-TT64IOS4.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-ECBNTGYJ.js +2 -0
- package/dist/cli/chunks/{cursor-installer-UALCQKVD.js → cursor-installer-OVOJIOHN.js} +2 -2
- package/dist/cli/chunks/{daemon-4LNOPJGN.js → daemon-DMFZMXKA.js} +8 -8
- package/dist/cli/chunks/{daemon-K3DFGCXC.js → daemon-XCULEHWY.js} +4 -4
- package/dist/cli/chunks/{dag-attention-scheduler-LCQ7MYKC.js → dag-attention-scheduler-WW2RX4B5.js} +2 -2
- package/dist/cli/chunks/{detect-P7PEN3MZ.js → detect-QNWIM232.js} +2 -2
- package/dist/cli/chunks/{dist-node-I72BJC2D.js → dist-node-6GQIY3CG.js} +2 -2
- package/dist/cli/chunks/{domain-handler-LROF6KWN.js → domain-handler-6RJPDELX.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-M2ZSSTPV.js → domain-transfer-WK524LBS.js} +2 -2
- package/dist/cli/chunks/dream-EHGKCFWH.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-MTBPUGO4.js → embed-and-insert-pattern-SO6GWJW7.js} +2 -2
- package/dist/cli/chunks/{eval-O24ALB3W.js → eval-GL544IPO.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-7JXEOGRE.js → experience-capture-middleware-BCCJ35OX.js} +3 -3
- package/dist/cli/chunks/{fast-paths-4CFYJV4U.js → fast-paths-CATDDBEU.js} +2 -2
- package/dist/cli/chunks/{feature-flags-CHPUA7IM.js → feature-flags-BUXNAORY.js} +2 -2
- package/dist/cli/chunks/{feature-flags-E6PIM6ZB.js → feature-flags-KNNWWP5G.js} +2 -2
- package/dist/cli/chunks/{file-discovery-2ANIAUCP.js → file-discovery-S4HF3O7D.js} +2 -2
- package/dist/cli/chunks/{fleet-2MQ3OGCP.js → fleet-DQVQQONW.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-P7JW3622.js → gnn-wrapper-G7ABZUG7.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-WWWZSA7V.js → heartbeat-handler-UFMELIWT.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-UFEL2CBW.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-BLSD45CX.js +2 -0
- package/dist/cli/chunks/hnsw-index-A3RZODEN.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-W634ZOTV.js → hnsw-legacy-bridge-YIILSRXI.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-SLZDLMKM.js → hnswlib-node-TSVRMXDH.js} +2 -2
- package/dist/cli/chunks/{hooks-3BFAZGG7.js → hooks-OHQPNK74.js} +10 -10
- package/dist/cli/chunks/{hypergraph-engine-XJSGXP2J.js → hypergraph-engine-LY7PJDSL.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-RVUWZMOX.js → hypergraph-handler-YGDYZO6H.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-OXHD3FOH.js +2 -0
- package/dist/cli/chunks/{init-handler-FYOZNNNO.js → init-handler-MTK65LI3.js} +6 -6
- package/dist/cli/chunks/init-wizard-PKZL7QBU.js +2 -0
- package/dist/cli/chunks/kernel-XWPM72UJ.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-MAAKFVSB.js → kilocode-installer-3IICU4RS.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-GX3TLZC5.js → kiro-installer-MXOVQYQA.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-FRKR5XWI.js +2 -0
- package/dist/cli/chunks/{learning-T4QZ6C26.js → learning-EV5LSOOM.js} +3 -3
- package/dist/cli/chunks/{llm-router-N2M4WXOC.js → llm-router-7LYDJUOT.js} +4 -4
- package/dist/cli/chunks/llm-router-service-R7A5HHDM.js +2 -0
- package/dist/cli/chunks/{load-6RU3G4P2.js → load-F4PVAMXQ.js} +2 -2
- package/dist/cli/chunks/load-test-5IKDWSYL.js +2 -0
- package/dist/cli/chunks/{mcp-EFBO7BAU.js → mcp-DUYJUEME.js} +2 -2
- package/dist/cli/chunks/{memory-AXU2M3DN.js → memory-XTTYORAS.js} +5 -5
- package/dist/cli/chunks/memory-backend-7VW5QCMO.js +2 -0
- package/dist/cli/chunks/{memory-handlers-65CXN76C.js → memory-handlers-VZH3R2TQ.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-W7AFGVNH.js → multi-model-executor-R6XCTMCF.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-KJE2RLCH.js → opencode-installer-33ULBU2F.js} +2 -2
- package/dist/cli/chunks/{orchestrator-CL6MLGVU.js → orchestrator-34ZJEKTJ.js} +5 -5
- package/dist/cli/chunks/pattern-null-store-BU6LCB2W.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-7SNSJ7K2.js → pattern-usage-recorder-GZ2M3F2E.js} +2 -2
- package/dist/cli/chunks/{pipeline-3UU6ON3F.js → pipeline-SR5OTY45.js} +2 -2
- package/dist/cli/chunks/{platform-SNMPIDIT.js → platform-VKJFJIAW.js} +2 -2
- package/dist/cli/chunks/{plugin-65IIUUCU.js → plugin-5C5UBQUQ.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-WWWJRLRP.js → prime-radiant-advanced-wasm-KO2PQI3D.js} +2 -2
- package/dist/cli/chunks/protocol-executor-BSP5LWJN.js +2 -0
- package/dist/cli/chunks/{protocol-handler-SEBHCLLJ.js → protocol-handler-ZF74NIKA.js} +2 -2
- package/dist/cli/chunks/{prove-N4X7CCJ4.js → prove-MO5TQQU4.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-J2RC7P25.js +2 -0
- package/dist/cli/chunks/{quality-LBCJWXMU.js → quality-EYIN6AER.js} +2 -2
- package/dist/cli/chunks/{quality-gate-KZIQI7QT.js → quality-gate-V6OQM57O.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-XI5AJV2V.js +2 -0
- package/dist/cli/chunks/{real-embeddings-XCZFHFME.js → real-embeddings-AR7TZX7U.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-P3O6B7PT.js → roocode-installer-46E626VZ.js} +2 -2
- package/dist/cli/chunks/router-VXQYYA3D.js +2 -0
- package/dist/cli/chunks/routing-feedback-HZQTASFF.js +2 -0
- package/dist/cli/chunks/{routing-handler-OXZ4DOV4.js → routing-handler-ZNRVW6QW.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-PSY5IDSL.js → ruvector-commands-4L2CQMWS.js} +2 -2
- package/dist/cli/chunks/rvf-dual-writer-BDTLLJER.js +2 -0
- package/dist/cli/chunks/rvf-migration-adapter-IB343MDN.js +2 -0
- package/dist/cli/chunks/{rvf-migration-coordinator-4SUT7GTJ.js → rvf-migration-coordinator-H4RVGBIA.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-Y7SN7LHU.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-TCKC22FH.js → rvf-store-integrity-OJGWWPLL.js} +2 -2
- package/dist/cli/chunks/safe-db-2VTKKBJU.js +2 -0
- package/dist/cli/chunks/schedule-QJ4CFGJY.js +2 -0
- package/dist/cli/chunks/scheduler-2NHDQPC3.js +2 -0
- package/dist/cli/chunks/{security-RQGUQGSI.js → security-JF3BVNRO.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-ZJFN52C2.js → shared-rvf-adapter-M6NNIZ5W.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-V2R37HWV.js → shared-rvf-dual-writer-LHMFCYVE.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-NVVAPZN3.js +2 -0
- package/dist/cli/chunks/{status-handler-XEKWNVDR.js → status-handler-GMIOXQIE.js} +2 -2
- package/dist/cli/chunks/{structural-health-QMIW6WUN.js → structural-health-YZXHVHM6.js} +2 -2
- package/dist/cli/chunks/{sync-H5SXWXPP.js → sync-GMPCPV5L.js} +2 -2
- package/dist/cli/chunks/{sync-GDYJ2ULT.js → sync-N56UQGCS.js} +2 -2
- package/dist/cli/chunks/{task-handler-EPLKCQHY.js → task-handler-VTNRGAXP.js} +2 -2
- package/dist/cli/chunks/{task-handlers-22NTLWTC.js → task-handlers-FYSDH55N.js} +3 -3
- package/dist/cli/chunks/{test-WHJFRZ3F.js → test-GQNCKRSP.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-KZVFZOQN.js → test-scheduling-GPRXSIRP.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-BW5WA6PY.js → token-bootstrap-76SRNXGG.js} +2 -2
- package/dist/cli/chunks/{token-usage-4A4O57R6.js → token-usage-O7CZDP5Q.js} +2 -2
- package/dist/cli/chunks/{transformers-FYTBRV46.js → transformers-LTU4LSSC.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-TZIJPLF3.js → tree-sitter-wasm-parser-NQSQCMBM.js} +2 -2
- package/dist/cli/chunks/{types-B2L6LKFA.js → types-OP6IWE6N.js} +2 -2
- package/dist/cli/chunks/unified-memory-DSTIEDSH.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-KBV3P4OS.js +2 -0
- package/dist/cli/chunks/unified-persistence-XKCOUBKY.js +2 -0
- package/dist/cli/chunks/{upgrade-O6U7EA7V.js → upgrade-OQWRBZ3R.js} +2 -2
- package/dist/cli/chunks/{validate-FHNZ5XL3.js → validate-TH5SRP3E.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-YOLLUEHE.js → validate-swarm-UITL2JUS.js} +2 -2
- package/dist/cli/chunks/{vibium-UXRPEIXB.js → vibium-O6PRAG4J.js} +2 -2
- package/dist/cli/chunks/visual-security-TTWSPZTZ.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-JJ5UIYFD.js → web-tree-sitter-XBFBY4OF.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-I4QMQPIL.js → windsurf-installer-DVT5NRNY.js} +2 -2
- package/dist/cli/chunks/witness-chain-2KY73HPN.js +2 -0
- package/dist/cli/chunks/{witness-chain-BIJ7WDGS.js → witness-chain-VRSH2F36.js} +2 -2
- package/dist/cli/chunks/{witness-key-manager-3SMMLJLP.js → witness-key-manager-GFHRDKQ4.js} +2 -2
- package/dist/cli/chunks/{workflow-33PUXXJV.js → workflow-HAZ6YKOG.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-UK56AVOT.js +2 -0
- package/dist/cli/chunks/{wrappers-ASAU36VK.js → wrappers-5LLLT7GM.js} +2 -2
- package/dist/cli/commands/daemon.js +3 -0
- package/dist/cli/foreground-command.d.ts +3 -0
- package/dist/cli/foreground-command.js +22 -0
- package/dist/cli/index.js +4 -0
- package/dist/mcp/bundle.js +368 -368
- package/dist/mcp/index.d.ts +1 -0
- package/dist/mcp/index.js +1 -0
- package/dist/mcp/protocol-server.js +11 -2
- package/dist/mcp/qe-tool-bridge.js +1 -0
- package/dist/mcp/tool-annotations.d.ts +25 -0
- package/dist/mcp/tool-annotations.js +75 -0
- package/dist/mcp/tool-registry.js +17 -12
- package/dist/mcp/tools/base.d.ts +7 -1
- package/dist/mcp/tools/base.js +8 -0
- package/dist/mcp/tools/registry.d.ts +3 -0
- package/dist/mcp/tools/registry.js +1 -0
- package/dist/mcp/types.d.ts +15 -0
- package/package.json +3 -2
- package/dist/cli/chunks/adapter-I2N7PEKG.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-U4ALUH6A.js +0 -2
- package/dist/cli/chunks/base-RCYIBNHM.js +0 -2
- package/dist/cli/chunks/browser-workflow-L6TDB5O5.js +0 -2
- package/dist/cli/chunks/chunk-CGZ7LTUK.js +0 -2
- package/dist/cli/chunks/chunk-YXN47QOI.js +0 -2
- package/dist/cli/chunks/client-L4PIXCGV.js +0 -2
- package/dist/cli/chunks/core-handlers-KROSXP4V.js +0 -2
- package/dist/cli/chunks/cross-domain-router-WMTYBOON.js +0 -2
- package/dist/cli/chunks/dream-AV63YQ2Y.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-5IZUGMC2.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-NV2NNBJL.js +0 -2
- package/dist/cli/chunks/hnsw-index-GRJ3KA2O.js +0 -2
- package/dist/cli/chunks/impact-analyzer-YM4QUWVH.js +0 -2
- package/dist/cli/chunks/init-wizard-YESXGIK6.js +0 -2
- package/dist/cli/chunks/kernel-VH5SKESU.js +0 -2
- package/dist/cli/chunks/knowledge-graph-F3NL4WJV.js +0 -2
- package/dist/cli/chunks/llm-router-service-HQYCJMPK.js +0 -2
- package/dist/cli/chunks/load-test-GWRGKWMN.js +0 -2
- package/dist/cli/chunks/memory-backend-7A2PFKPV.js +0 -2
- package/dist/cli/chunks/pattern-null-store-K2WPRYCP.js +0 -2
- package/dist/cli/chunks/protocol-executor-TJDLEHND.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-CGRMFPDM.js +0 -2
- package/dist/cli/chunks/queen-coordinator-FKP6QZAQ.js +0 -2
- package/dist/cli/chunks/router-KZ5BISAM.js +0 -2
- package/dist/cli/chunks/routing-feedback-O4Y5TTR6.js +0 -2
- package/dist/cli/chunks/rvf-dual-writer-NG3UF3D5.js +0 -2
- package/dist/cli/chunks/rvf-migration-adapter-PUHVTKQY.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-ODXFKZ6G.js +0 -2
- package/dist/cli/chunks/safe-db-BUQDNH2R.js +0 -2
- package/dist/cli/chunks/schedule-ZXNDZNNB.js +0 -2
- package/dist/cli/chunks/scheduler-YUQQWWW3.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-HVSX46C7.js +0 -2
- package/dist/cli/chunks/unified-memory-AHN4RVBP.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-XB7JPF74.js +0 -2
- package/dist/cli/chunks/unified-persistence-53KWNFQJ.js +0 -2
- package/dist/cli/chunks/visual-security-CRPYS7L7.js +0 -2
- package/dist/cli/chunks/witness-chain-5WCR2CAS.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-RZWCLTT5.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.14.
|
|
2
|
-
import{d as j,e as W,f as ne,g as V}from"./chunk-
|
|
3
|
-
`)}var bt=(function(n){gt(e,n);function e(t,r,i,s,a){var c=this.constructor,d=n.call(this,ze(t,{name:r,index:i,operation:s,tree:a}))||this;return d.name=r,d.index=i,d.operation=s,d.tree=a,Object.setPrototypeOf(d,c.prototype),d.message=ze(t,{name:r,index:i,operation:s,tree:a}),d}return e})(Error);E.PatchError=bt});var me=B(g=>{Object.defineProperty(g,"__esModule",{value:!0});var R=Y();g.JsonPatchError=R.PatchError;g.deepClone=R._deepClone;var U={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=K(t,this.path);r&&(r=R._deepClone(r));var i=_(t,{op:"remove",path:this.from}).removed;return _(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=K(t,this.from);return _(t,{op:"add",path:this.path,value:R._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:J(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},Et={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:U.move,copy:U.copy,test:U.test,_get:U._get};function K(n,e){if(e=="")return n;var t={op:"_get",path:e};return _(n,t),t.value}g.getValueByPointer=K;function _(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):Z(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=K(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=J(n,e.value),a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,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",s,e,n);return a}}else{r||(n=R._deepClone(n));var c=e.path||"",d=c.split("/"),o=n,l=1,f=d.length,h=void 0,u=void 0,m=void 0;for(typeof t=="function"?m=t:m=Z;;){if(u=d[l],u&&u.indexOf("~")!=-1&&(u=R.unescapePathComponent(u)),i&&(u=="__proto__"||u=="prototype"&&l>0&&d[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&&h===void 0&&(o[u]===void 0?h=d.slice(0,l).join("/"):l==f-1&&(h=e.path),h!==void 0&&m(e,0,n,h)),l++,Array.isArray(o)){if(u==="-")u=o.length;else{if(t&&!R.isInteger(u))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",s,e,n);R.isInteger(u)&&(u=~~u)}if(l>=f){if(t&&e.op==="add"&&u>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",s,e,n);var a=Et[e.op].call(e,o,u,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=f){var a=U[e.op].call(e,o,u,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[u],t&&l<f&&(!o||typeof o!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}g.applyOperation=_;function Be(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!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 s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=_(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}g.applyPatch=Be;function At(n,e,t){var r=_(n,e);if(r.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}g.applyReducer=At;function Z(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(U[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 i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)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=Z;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)Be(R._deepClone(e),R._deepClone(n),t||!0);else{t=t||Z;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof g.JsonPatchError)return i;throw i}}g.validate=je;function J(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),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!J(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(s=c.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=s;i--!==0;)if(a=c[i],!J(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}g._areEquals=J});var We=B(q=>{Object.defineProperty(q,"__esModule",{value:!0});var b=Y(),Rt=me(),ge=new WeakMap,Tt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Ct=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function xt(n){return ge.get(n)}function It(n,e){return n.observers.get(e)}function Dt(n,e){n.observers.delete(e.callback)}function Ft(n,e){e.unobserve()}q.unobserve=Ft;function Ot(n,e){var t=[],r,i=xt(n);if(!i)i=new Tt(n),ge.set(n,i);else{var s=It(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=b._deepClone(n),e){r.callback=e,r.next=null;var a=function(){pe(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(){pe(r),clearTimeout(r.next),Dt(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},i.observers.set(e,new Ct(e,r)),r}q.observe=Ot;function pe(n,e){e===void 0&&(e=!1);var t=ge.get(n.object);ye(t.value,n.object,n.patches,"",e),n.patches.length&&Rt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}q.generate=pe;function ye(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=b._objectKeys(e),a=b._objectKeys(n),c=!1,d=!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 h=e[l];typeof f=="object"&&f!=null&&typeof h=="object"&&h!=null&&Array.isArray(f)===Array.isArray(h)?ye(f,h,t,r+"/"+b.escapePathComponent(l),i):f!==h&&(c=!0,i&&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(h)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"remove",path:r+"/"+b.escapePathComponent(l)}),d=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!d&&s.length==a.length))for(var o=0;o<s.length;o++){var l=s[o];!b.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(e[l])})}}}function _t(n,e,t){t===void 0&&(t=!1);var r=[];return ye(n,e,r,"",t),r}q.compare=_t});var Ve=B(N=>{var Nt=me();Object.assign(N,Nt);var Mt=We();Object.assign(N,Mt);var ee=Y();N.JsonPatchError=ee.PatchError;N.deepClone=ee._deepClone;N.escapePathComponent=ee.escapePathComponent;N.unescapePathComponent=ee.unescapePathComponent});var A=class extends Error{patternId;disposition;cause;constructor(e,t,r){super(`${t}: pattern ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="PatternMutationError",this.patternId=e,this.disposition=t,this.cause=r}};at();import{existsSync as jt}from"node:fs";import{join as rt}from"node:path";Ie();var z=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??X,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1,this.embeddingSpaceId=t?.embeddingSpaceId}createAdapter;config;rvfPath;skipCloseOnDispose;embeddingSpaceId;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(this.rvfInitError=null,process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension);let e=T()?.spaceId??this.embeddingSpaceId??null;Fe(this.rvfPath,e,this.adapter.status()?.totalVectors??0),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=S(e);try{this.adapter?.close()}catch{}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-HVSX46C7.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:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),d=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!d.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: ${S(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=V(e);if(!t.valid)return v(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return v(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(!this.sqliteStore)return v(new A(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let r=T()?.spaceId??this.embeddingSpaceId;if(e.embedding&&!r)return v(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));let i=!1;if(this.sqliteStore)try{let s=this.sqliteStore.storePattern(e,e.embedding,r);s&&s!==e.id&&(e.id=s),i=!0}catch(s){return v(new A(e.id,"FAILED",s))}if(e.embedding&&!this.adapter&&this.rvfInitError)return v(new A(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",new Error(`RVF unavailable ${i?"after":"before"} authoritative pattern commit: ${this.rvfInitError}`)));if(e.embedding&&this.adapter)try{let s=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding),a=this.adapter.ingest([{id:e.id,vector:s}]);if(a.accepted!==1||a.rejected!==0)throw new Error(`RVF rejected pattern vector (accepted=${a.accepted}, rejected=${a.rejected})`)}catch(s){return v(new A(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",s))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:D(),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},s=await this.store(i);return s.success?P(i):v(s.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(),i=t.limit??10,s=[];if(Array.isArray(e)){let c=T()?.spaceId??this.embeddingSpaceId;if(!c||t.embeddingSpaceId!==c)return v(new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId"))}if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),d=this.adapter.search(c,i*2);for(let o of d){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.score);s.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:",S(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),d=e,o=Math.sqrt(d.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),h=f?.embedding;if(!h||h.length!==d.length)continue;let u=0,m=0;for(let w=0;w<d.length;w++)u+=d[w]*h[w],m+=h[w]*h[w];if(m=Math.sqrt(m),m===0)continue;let p=u/(o*m),y=this.calculateReuseInfo(f,p);s.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:i*2}),d=new Set(s.map(o=>o.pattern.id));for(let o of c){if(d.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);s.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,i*2),d=new Set(s.map(o=>o.pattern.id));for(let o of c){if(d.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch{}s.sort((c,d)=>d.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,P(s.slice(0,i))}async recordUsage(e,t,r,i){if(!this.sqliteStore)return v(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,i),P(void 0)}catch(s){return v(new Error(`recordUsage failed: ${S(s)}`))}}async promote(e){if(!this.sqliteStore)return v(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return v(new Error(`promote failed: ${S(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,S(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return v(new Error(`SQLite delete failed: ${S(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},i={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let s=this.sqliteStore.getStats();t=s.totalPatterns,r=s.byDomain,i={shortTerm:s.byTier["short-term"]??0,longTerm:s.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:i,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 i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=W&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",S(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,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};ot();Ie();O();function lt(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let c of s){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function dt(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 s=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 s>=a&&s<=c}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function G(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>G(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>G(n,r))}case"NOT":return e.child?!G(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=lt(n,e.field);return dt(t,e.operator,e.value)}default:return!0}}function He(n,e){return e?n.filter(t=>G(t,e)):n}O();O();var ke=1e4,Ue=2166136261;function qe(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 le=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;le[n]=e}var Le="0123456789abcdef";function ut(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Le[i>>4]+Le[i&15]}return t}function ht(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 ft(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let c=0,d=1<<a;for(let o=0;o<n.length;o++)n[o][i]&d&&c++;c>=r&&(s|=d)}t[i]=s}return t}function mt(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 s=0;s<n.length;s++)r+=le[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function pt(n,e,t){return 1-mt(n,e,t)}var oe=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??ke,this.baseSeed=e?.seed??Ue,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=qe(e)^this.baseSeed,i=this.generateSeededVector(r);return this.tokenCache.set(e,i),new Uint8Array(i)}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=ht(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let i=this.fingerprintPattern(t);return ft([r,i])}similarity(e,t){return pt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new se(e),i=0;for(;i<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-i);for(let d=0;d<c;d++)t[i++]=a>>>d*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},ce=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??ke,this.baseSeed=e?.seed??Ue,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=qe(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:ut(i)}}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 i=0;i<e.length;i++)r[i]=e[i]^t[i];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 i=0;i<e.length;i++)r+=le[e[i]^t[i]];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),i=new se(e),s=0;for(;s<t;){let c=i.next(),d=t-s,o=d<4?d:4;for(let l=0;l<o;l++)r[s++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function Qe(n){return new ce(n)}function $e(n){return $()?new oe(n):null}var Se=st(Ve(),1),ve=Se.default??Se,Ht=`
|
|
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.14.2");process.exit(0)}
|
|
2
|
+
import{d as j,e as W,f as ne,g as V}from"./chunk-C7AXRI7E.js";import{a as se}from"./chunk-R5RNOLHI.js";import{b as Me}from"./chunk-IUNMW454.js";import{a as ae}from"./chunk-Q335R4MR.js";import{c as Fe,n as T}from"./chunk-E3Q7WNJD.js";import{b as De,c as at}from"./chunk-JDXLCNKV.js";import{a as ie,b as Oe,d as _e,f as ot}from"./chunk-HSJ5FQCF.js";import{c as Ne}from"./chunk-VSYBMNIR.js";import{b as P,c as v}from"./chunk-CIESXO73.js";import{a as S,b as xe,c as Ie}from"./chunk-D4RCV4LY.js";import{i as D}from"./chunk-NG2UVPTW.js";import{B as $,D as L,G as re,P as k,S as O,b as F}from"./chunk-GHQ5PUOV.js";import{d as B,f as st}from"./chunk-6VKJAMZY.js";var Y=B(E=>{var gt=E&&E.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},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 yt=Object.prototype.hasOwnProperty;function he(n,e){return yt.call(n,e)}E.hasOwnProperty=he;function Je(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 i in n)he(n,i)&&r.push(i);return r}E._objectKeys=Je;function vt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}E._deepClone=vt;function St(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=St;function de(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapePathComponent=de;function wt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapePathComponent=wt;function fe(n,e){var t;for(var r in n)if(he(n,r)){if(n[r]===e)return de(r)+"/";if(typeof n[r]=="object"&&(t=fe(n[r],e),t!=""))return de(r)+"/"+t}return""}E._getPathRecursive=fe;function Pt(n,e){if(n===e)return"/";var t=fe(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}E.getPath=Pt;function ue(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(ue(n[e]))return!0}else if(typeof n=="object"){for(var r=Je(n),i=r.length,s=0;s<i;s++)if(ue(n[r[s]]))return!0}}return!1}E.hasUndefined=ue;function ze(n,e){var t=[n];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&t.push(r+": "+i)}return t.join(`
|
|
3
|
+
`)}var bt=(function(n){gt(e,n);function e(t,r,i,s,a){var c=this.constructor,d=n.call(this,ze(t,{name:r,index:i,operation:s,tree:a}))||this;return d.name=r,d.index=i,d.operation=s,d.tree=a,Object.setPrototypeOf(d,c.prototype),d.message=ze(t,{name:r,index:i,operation:s,tree:a}),d}return e})(Error);E.PatchError=bt});var me=B(g=>{Object.defineProperty(g,"__esModule",{value:!0});var R=Y();g.JsonPatchError=R.PatchError;g.deepClone=R._deepClone;var U={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=K(t,this.path);r&&(r=R._deepClone(r));var i=_(t,{op:"remove",path:this.from}).removed;return _(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=K(t,this.from);return _(t,{op:"add",path:this.path,value:R._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:J(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},Et={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:U.move,copy:U.copy,test:U.test,_get:U._get};function K(n,e){if(e=="")return n;var t={op:"_get",path:e};return _(n,t),t.value}g.getValueByPointer=K;function _(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):Z(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=K(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=J(n,e.value),a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,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",s,e,n);return a}}else{r||(n=R._deepClone(n));var c=e.path||"",d=c.split("/"),o=n,l=1,f=d.length,h=void 0,u=void 0,m=void 0;for(typeof t=="function"?m=t:m=Z;;){if(u=d[l],u&&u.indexOf("~")!=-1&&(u=R.unescapePathComponent(u)),i&&(u=="__proto__"||u=="prototype"&&l>0&&d[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&&h===void 0&&(o[u]===void 0?h=d.slice(0,l).join("/"):l==f-1&&(h=e.path),h!==void 0&&m(e,0,n,h)),l++,Array.isArray(o)){if(u==="-")u=o.length;else{if(t&&!R.isInteger(u))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",s,e,n);R.isInteger(u)&&(u=~~u)}if(l>=f){if(t&&e.op==="add"&&u>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",s,e,n);var a=Et[e.op].call(e,o,u,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=f){var a=U[e.op].call(e,o,u,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[u],t&&l<f&&(!o||typeof o!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}g.applyOperation=_;function Be(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!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 s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=_(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}g.applyPatch=Be;function At(n,e,t){var r=_(n,e);if(r.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}g.applyReducer=At;function Z(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(U[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 i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)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=Z;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)Be(R._deepClone(e),R._deepClone(n),t||!0);else{t=t||Z;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof g.JsonPatchError)return i;throw i}}g.validate=je;function J(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),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!J(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(s=c.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=s;i--!==0;)if(a=c[i],!J(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}g._areEquals=J});var We=B(q=>{Object.defineProperty(q,"__esModule",{value:!0});var b=Y(),Rt=me(),ge=new WeakMap,Tt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Ct=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function xt(n){return ge.get(n)}function It(n,e){return n.observers.get(e)}function Dt(n,e){n.observers.delete(e.callback)}function Ft(n,e){e.unobserve()}q.unobserve=Ft;function Ot(n,e){var t=[],r,i=xt(n);if(!i)i=new Tt(n),ge.set(n,i);else{var s=It(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=b._deepClone(n),e){r.callback=e,r.next=null;var a=function(){pe(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(){pe(r),clearTimeout(r.next),Dt(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},i.observers.set(e,new Ct(e,r)),r}q.observe=Ot;function pe(n,e){e===void 0&&(e=!1);var t=ge.get(n.object);ye(t.value,n.object,n.patches,"",e),n.patches.length&&Rt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}q.generate=pe;function ye(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=b._objectKeys(e),a=b._objectKeys(n),c=!1,d=!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 h=e[l];typeof f=="object"&&f!=null&&typeof h=="object"&&h!=null&&Array.isArray(f)===Array.isArray(h)?ye(f,h,t,r+"/"+b.escapePathComponent(l),i):f!==h&&(c=!0,i&&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(h)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"remove",path:r+"/"+b.escapePathComponent(l)}),d=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!d&&s.length==a.length))for(var o=0;o<s.length;o++){var l=s[o];!b.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(e[l])})}}}function _t(n,e,t){t===void 0&&(t=!1);var r=[];return ye(n,e,r,"",t),r}q.compare=_t});var Ve=B(N=>{var Nt=me();Object.assign(N,Nt);var Mt=We();Object.assign(N,Mt);var ee=Y();N.JsonPatchError=ee.PatchError;N.deepClone=ee._deepClone;N.escapePathComponent=ee.escapePathComponent;N.unescapePathComponent=ee.unescapePathComponent});var A=class extends Error{patternId;disposition;cause;constructor(e,t,r){super(`${t}: pattern ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="PatternMutationError",this.patternId=e,this.disposition=t,this.cause=r}};at();import{existsSync as jt}from"node:fs";import{join as rt}from"node:path";Ie();var z=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??X,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1,this.embeddingSpaceId=t?.embeddingSpaceId}createAdapter;config;rvfPath;skipCloseOnDispose;embeddingSpaceId;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(this.rvfInitError=null,process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension);let e=T()?.spaceId??this.embeddingSpaceId??null;Fe(this.rvfPath,e,this.adapter.status()?.totalVectors??0),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=S(e);try{this.adapter?.close()}catch{}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-NVVAPZN3.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:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),d=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!d.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: ${S(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=V(e);if(!t.valid)return v(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return v(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(!this.sqliteStore)return v(new A(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let r=T()?.spaceId??this.embeddingSpaceId;if(e.embedding&&!r)return v(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));let i=!1;if(this.sqliteStore)try{let s=this.sqliteStore.storePattern(e,e.embedding,r);s&&s!==e.id&&(e.id=s),i=!0}catch(s){return v(new A(e.id,"FAILED",s))}if(e.embedding&&!this.adapter&&this.rvfInitError)return v(new A(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",new Error(`RVF unavailable ${i?"after":"before"} authoritative pattern commit: ${this.rvfInitError}`)));if(e.embedding&&this.adapter)try{let s=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding),a=this.adapter.ingest([{id:e.id,vector:s}]);if(a.accepted!==1||a.rejected!==0)throw new Error(`RVF rejected pattern vector (accepted=${a.accepted}, rejected=${a.rejected})`)}catch(s){return v(new A(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",s))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:D(),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},s=await this.store(i);return s.success?P(i):v(s.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(),i=t.limit??10,s=[];if(Array.isArray(e)){let c=T()?.spaceId??this.embeddingSpaceId;if(!c||t.embeddingSpaceId!==c)return v(new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId"))}if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),d=this.adapter.search(c,i*2);for(let o of d){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.score);s.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:",S(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),d=e,o=Math.sqrt(d.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),h=f?.embedding;if(!h||h.length!==d.length)continue;let u=0,m=0;for(let w=0;w<d.length;w++)u+=d[w]*h[w],m+=h[w]*h[w];if(m=Math.sqrt(m),m===0)continue;let p=u/(o*m),y=this.calculateReuseInfo(f,p);s.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:i*2}),d=new Set(s.map(o=>o.pattern.id));for(let o of c){if(d.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);s.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,i*2),d=new Set(s.map(o=>o.pattern.id));for(let o of c){if(d.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch{}s.sort((c,d)=>d.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,P(s.slice(0,i))}async recordUsage(e,t,r,i){if(!this.sqliteStore)return v(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,i),P(void 0)}catch(s){return v(new Error(`recordUsage failed: ${S(s)}`))}}async promote(e){if(!this.sqliteStore)return v(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return v(new Error(`promote failed: ${S(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,S(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return v(new Error(`SQLite delete failed: ${S(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},i={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let s=this.sqliteStore.getStats();t=s.totalPatterns,r=s.byDomain,i={shortTerm:s.byTier["short-term"]??0,longTerm:s.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:i,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 i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=W&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",S(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,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};ot();Ie();O();function lt(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let c of s){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function dt(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 s=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 s>=a&&s<=c}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function G(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>G(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>G(n,r))}case"NOT":return e.child?!G(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=lt(n,e.field);return dt(t,e.operator,e.value)}default:return!0}}function He(n,e){return e?n.filter(t=>G(t,e)):n}O();O();var ke=1e4,Ue=2166136261;function qe(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 le=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;le[n]=e}var Le="0123456789abcdef";function ut(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Le[i>>4]+Le[i&15]}return t}function ht(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 ft(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let c=0,d=1<<a;for(let o=0;o<n.length;o++)n[o][i]&d&&c++;c>=r&&(s|=d)}t[i]=s}return t}function mt(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 s=0;s<n.length;s++)r+=le[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function pt(n,e,t){return 1-mt(n,e,t)}var oe=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??ke,this.baseSeed=e?.seed??Ue,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=qe(e)^this.baseSeed,i=this.generateSeededVector(r);return this.tokenCache.set(e,i),new Uint8Array(i)}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=ht(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let i=this.fingerprintPattern(t);return ft([r,i])}similarity(e,t){return pt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new se(e),i=0;for(;i<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-i);for(let d=0;d<c;d++)t[i++]=a>>>d*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},ce=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??ke,this.baseSeed=e?.seed??Ue,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=qe(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:ut(i)}}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 i=0;i<e.length;i++)r[i]=e[i]^t[i];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 i=0;i<e.length;i++)r+=le[e[i]^t[i]];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),i=new se(e),s=0;for(;s<t;){let c=i.next(),d=t-s,o=d<4?d:4;for(let l=0;l<o;l++)r[s++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function Qe(n){return new ce(n)}function $e(n){return $()?new oe(n):null}var Se=st(Ve(),1),ve=Se.default??Se,Ht=`
|
|
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 W,f as ne,g as V}from"./chunk-MFAN5W27.js";import{a as se}fro
|
|
|
46
46
|
WHERE pattern_id = ? AND version != 0
|
|
47
47
|
ORDER BY version ASC
|
|
48
48
|
LIMIT ?
|
|
49
|
-
)`).run(e,e,s)}}};O();var kt={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},we=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...kt,...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 i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,c=this.computeSparseChanges(t,r),d={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:i,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(d),this.buffer.push(d),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:d.timestamp}),this.enforceRetention(e),d}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}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 i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let c=[...a.fullVector],d=a.version+1;for(let o of r)if(!(o.version<d)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),c=i.slice(s),d=a.findIndex(f=>f.deltaType==="genesis");d>=0&&(c.unshift(a[d]),a.splice(d,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=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,c=s<t.length?t[s]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:s,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 Ye(n){return L()?new we(n):null}O();var Ut=128,qt=8,Qt=1e4,Pe=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Ut,this.beta=e?.beta??qt,this.maxPatterns=e?.maxPatterns??Qt,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 i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,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 i=this.softmax(r),s=0,a=i[0];for(let l=1;l<i.length;l++)i[l]>a&&(a=i[l],s=l);let c=this.patterns[s],d=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:d,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 i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let c=1/this.beta*(s+Math.log(a)),d=this.dotProduct(t,t);return-c+.5*d}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!F().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function Ke(n){return new Pe(n)}O();var $t={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},M=1e-5,Ze=1-M;function zt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function C(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function Jt(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 x=class n{static poincareDistance(e,t){let r=C(Jt(e,t)),i=Math.max(M,1-C(e)),s=Math.max(M,1-C(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=zt(e,t),i=C(e),s=C(t),a=Math.max(M,1+2*r+i*s),c=1+2*r+s,d=1-i,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+d*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(M,1-C(e)),i=Math.sqrt(C(t));if(i<M)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=s/i*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(C(e));if(t<=Ze)return new Float32Array(e);let r=Ze/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(C(e));if(t<M)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},be=class{config;points=new Map;constructor(e){if(this.config={...$t,...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:x.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=x.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:x.poincareDistance(r,s.coordinates),point:s});return i.sort((s,a)=>s.distance-a.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,a=[];for(let d of e)if(s.set(d.id,d),!d.parentId)a.push(d.id);else{let o=i.get(d.parentId);o||(o=[],i.set(d.parentId,o)),o.push(d.id)}let c=a.map((d,o)=>({id:d,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:d,depth:o,angOff:l,angSpan:f}=c.shift(),h=Math.tanh(.3*(o+.1)),u=l+f/2,m=new Float32Array(r);m[0]=h*Math.cos(u),m[1]=h*Math.sin(u);let p=s.get(d);if(p&&p.features.length>0){let H=h*.1;for(let I=2;I<r&&I-2<p.features.length;I++)m[I]=p.features[I-2]*H}let y=x.project(m);t.set(d,y),this.points.set(d,{id:d,coordinates:y,metadata:{depth:o,parentId:p?.parentId}});let w=i.get(d)??[];for(let H=0;H<w.length;H++){let I=f/Math.max(1,w.length);c.push({id:w[H],depth:o+1,angOff:l+H*I,angSpan:I})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function et(n){return Bt()?new be(n):null}function Bt(){return F().useHyperbolicHnsw}O();var Ee=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!k())return!1;try{return this.index=et(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 i=t instanceof Float32Array?t:new Float32Array(t),s=x.euclideanToHyperbolic(i);this.index.insert(e,s,r)}catch(i){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,i instanceof Error?i.message:i)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),i=x.euclideanToHyperbolic(r);return this.index.search(i,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 tt(n){return new Ee(n)}var Ae=null;function nt(){return Ae||(Ae=Qe({dimensions:1e4})),Ae}var Re;function Wt(){return Re===void 0&&(Re=$e()),Re}var Q=null,Te=0;function it(n){return(!Q||Te!==n)&&(Q=Ke({dimension:n,maxPatterns:1e4}),Te=n),Q}var X={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:W,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}},Ce=class{constructor(e,t={}){this.memory=e;this.config={...X,...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;hnswSpaceId=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,L()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new te(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(){if(this.hnswIndex!==null){let e=T()?.spaceId??this.config.embeddingSpaceId??null;return this.hnswSpaceId!==e?(console.warn("[PatternStore] VECTOR_SPACE_MISMATCH: active embedder changed; semantic index disabled"),null):this.hnswIndex}return 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(this.hnswSpaceId=T()?.spaceId??this.config.embeddingSpaceId??null,!this.hnswSpaceId)throw new Error("VECTOR_SPACE_UNVERIFIED: cannot initialize HNSW without runtime provenance");if(F().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-W634ZOTV.js"),{HnswAdapter:c}=await import("./hnsw-adapter-NV2NNBJL.js"),d=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(d),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-GRJ3KA2O.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,i=this.hnswIndex.initialize(),s=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([i,s]),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:",S(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,i=0,s=T()?.spaceId??this.config.embeddingSpaceId;for(let{patternId:a,embedding:c,spaceId:d}of e){if(r>=t)break;if(!s||d!==s||!c||c.length!==this.config.embeddingDimension){i++;continue}let o=this.patternCache.get(a);if(!o){i++;continue}try{await this.hnswIndex.insert(a,c,{filePath:o.patternType,lineCoverage:o.confidence*100,branchCoverage:o.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-o.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",S(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Ye()),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:",S(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=V(e);if(!t.valid)return v(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return v(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));let r=(process.env.AQE_MEMORY_BACKEND??"memory")!=="memory";if(r&&!this.sqliteStore)return v(new A(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let i=T()?.spaceId??this.config.embeddingSpaceId;if(e.embedding&&!i)return v(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let a=this.patternCache.get(e.id)??null,c=!1,d=()=>{this.unindexPattern(e),a&&this.indexPattern(a)};if(this.indexPattern(e),this.sqliteStore)try{let o=this.sqliteStore.storePattern(e,e.embedding,i);o&&o!==e.id&&(this.unindexPattern(e),e.id=o,this.indexPattern(e)),c=!0}catch(o){return d(),v(new A(e.id,"FAILED",o))}if(e.embedding){let o=await this.ensureHNSW();if(!o&&c)return v(new A(e.id,"COMMITTED_PENDING_INDEX",new Error("HNSW unavailable after authoritative pattern commit")));if(!o&&r)return d(),v(new A(e.id,"FAILED",new Error("HNSW unavailable before an authoritative pattern commit")));if(o)try{await o.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(l){return c||d(),v(new A(e.id,c?"COMMITTED_PENDING_INDEX":"FAILED",l))}}if($())try{let l=nt().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,l.vector)}catch(o){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,S(o))}try{let o=Wt();if(o){let l=[e.patternType,e.qeDomain];e.context?.tags&&l.push(...e.context.tags),e.name&&l.push(e.name);let f=o.fingerprintPattern(l);this.hdcTokenCache.set(e.id,f)}}catch(o){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,S(o))}if(re()&&e.embedding)try{it(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(o){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,S(o))}if(L()&&this.deltaTracker)try{let o={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,o)}catch(o){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,S(o))}if(e.embedding)try{let o=this.getVectorDeltaTracker();o&&(a?.embedding?o.recordDelta(e.id,a.embedding,e.embedding):o.getVersion(e.id)<0&&o.recordGenesis(e.id,e.embedding))}catch(o){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,S(o))}try{k()&&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),i={id:D(),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},s=await this.store(i);return s.success?P(i):v(s.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(),i=t.limit||10,s=[];try{if(Array.isArray(e)&&re())try{let h=it(e.length);if(h.getPatternCount()>0){let u=h.recall(new Float32Array(e));if(u&&u.similarity>.98){let m=u.metadata.id,p=await this.get(m);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,u.similarity);s.push({pattern:p,score:u.similarity,matchType:"vector",similarity:u.similarity,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",S(h))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let h=T()?.spaceId??this.config.embeddingSpaceId;if(!h||t.embeddingSpaceId!==h)throw new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId");let u=await this.ensureHNSW();if(u){let m=await u.search(e,i*2);for(let p of m){let y=await this.get(p.key);if(y&&this.matchesFilters(y,t)){let w=this.calculateReuseInfo(y,p.score);s.push({pattern:y,score:p.score,matchType:"vector",similarity:p.score,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let u=new Map(h.map(p=>[p.id,p.ftsScore])),m=new Set(s.map(p=>p.pattern.id));for(let p of s){let y=u.get(p.pattern.id);y!==void 0&&(p.score=.75*p.score+.25*y)}for(let p of h){if(m.has(p.id))continue;let y=await this.get(p.id);if(y&&this.matchesFilters(y,t)){let w=this.calculateReuseInfo(y,p.ftsScore);s.push({pattern:y,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let h=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),u=new Set(s.map(m=>m.pattern.id));for(let m of h)u.has(m.pattern.id)||s.push(m)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let u=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),m=c-u,p=Math.pow(.5,m/a),y=h.pattern.usageCount>0?p:.5;h.score=h.score*(.7+.3*y)}let d=this.sqliteStore?.getDatabase();if(d&&s.length>0)try{this.nullStore||(this.nullStore=new ae(d));let h=this.nullStore.getNullSummaries(s.map(u=>u.pattern.id));for(let u of s){let m=h.get(u.pattern.id);m&&(u.nullSummary=m,u.score=ae.applyNullDiscount(u.score,m,t.contextFingerprint))}}catch(h){console.debug("[PatternStore] null discount skipped:",S(h))}s.sort((h,u)=>u.score-h.score);let o=s;t.filter&&(o=He(s,t.filter));let l=o.slice(0,i),f=performance.now()-r;return this.recordSearchLatency(f),P(l)}catch(a){return v(xe(a))}}async searchByText(e,t,r){let i=[],s=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($()&&s&&this.hdcCache.size>0)try{let d=nt(),o=d.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(u=>this.hdcCache.has(u)).map(u=>({id:u,similarity:d.similarity(o.vector,this.hdcCache.get(u))}));l.sort((u,m)=>m.similarity-u.similarity);let f=l.map(u=>u.id),h=c.filter(u=>!this.hdcCache.has(u));c=[...f,...h]}catch{}for(let d of c){if(i.length>=r)break;let o=this.patternCache.get(d);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(s){let f=o.name.toLowerCase(),h=o.description.toLowerCase();f.includes(s)&&(l+=.5),h.includes(s)&&(s.length/h.length>.3?l+=.5:l+=.3);for(let u of o.context.tags)if(u.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let f=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),d=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&d,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,f=t,h=e.successRate,u=Math.min(e.reuseCount/10,1),m=o?f*.4+h*.4+u*.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,i){let s=await this.get(e);if(!s)return v(new Error(`Pattern not found: ${e}`));let a=new Date,c=s.usageCount+1,d=s.successfulUses+(t?1:0),o=d/c,l=t?.02:-.01,f=Math.max(.1,Math.min(1,s.confidence+l)),h=j({confidence:f,usageCount:c,successRate:o}),u={...s,usageCount:c,successfulUses:d,successRate:o,confidence:f,qualityScore:h,lastUsedAt:a};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,i)}catch(y){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,S(y))}if(L()&&this.deltaTracker)try{let y={id:s.id,name:s.name,confidence:s.confidence,qualityScore:s.qualityScore,usageCount:s.usageCount,successRate:s.successRate,tier:s.tier},w={id:u.id,name:u.name,confidence:u.confidence,qualityScore:u.qualityScore,usageCount:u.usageCount,successRate:u.successRate,tier:u.tier};this.deltaTracker.recordDelta(e,y,w,{success:t})}catch(y){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,S(y))}let m=ne(u);return m.meetsUsageCriteria&&m.meetsQualityCriteria&&m.meetsCoherenceCriteria&&u.tier==="short-term"?await this.promote(e):this.patternCache.set(e,u),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return v(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(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}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 v(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,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let c=await this.ensureHNSW(),d=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?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:d.nativeHNSW,vectorCount:d.vectorCount,indexSizeBytes:d.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=ne(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let d=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-d,l=o>10080*60*1e3,f=s.qualityScore<.2,h=s.usageCount===0&&o>1440*60*1e3;(l&&f||h)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).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 i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}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),Q&&(Q.clear(),Q=null,Te=0),this.initialized=!1}indexHyperbolic(e,t,r){if(k())try{this.hyperbolicIndex||(this.hyperbolicIndex=tt({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!k()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let c=Math.exp(-s.distance),d=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}return P(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function rn(n,e){try{if(F().useRVFPatternStore&&_e()){let r=process.env.AQE_PROJECT_ROOT??De(),i=rt(r,".agentic-qe"),s=rt(i,"patterns.rvf");if(jt(i)){let a={...X,...e},c=!1;try{let d=Me(i,a.embeddingDimension);if(d){c=!0;let o=new z(()=>d,{rvfPath:s,base:a,skipCloseOnDispose:!0,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),o}}catch{}if(!c){let d=new z((o,l)=>{let f=()=>{try{return Oe(o)}catch{return null}},h=f();if(h){if(h.dimension()!==l){try{h.close()}catch{}throw new Error(`RVF dimension mismatch (file=${h.dimension()}, requested=${l})`)}return h}try{return ie(o,l)}catch(u){if(h=f(),h&&h.dimension()===l)return h;if(Ne(o,u instanceof Error?u.message:String(u)))return ie(o,l);throw u}},{rvfPath:s,base:a,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),d}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new Ce(n,e)}export{A as a,rn as b};
|
|
49
|
+
)`).run(e,e,s)}}};O();var kt={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},we=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...kt,...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 i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,c=this.computeSparseChanges(t,r),d={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:i,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(d),this.buffer.push(d),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:d.timestamp}),this.enforceRetention(e),d}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}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 i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let c=[...a.fullVector],d=a.version+1;for(let o of r)if(!(o.version<d)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),c=i.slice(s),d=a.findIndex(f=>f.deltaType==="genesis");d>=0&&(c.unshift(a[d]),a.splice(d,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=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,c=s<t.length?t[s]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:s,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 Ye(n){return L()?new we(n):null}O();var Ut=128,qt=8,Qt=1e4,Pe=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Ut,this.beta=e?.beta??qt,this.maxPatterns=e?.maxPatterns??Qt,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 i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,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 i=this.softmax(r),s=0,a=i[0];for(let l=1;l<i.length;l++)i[l]>a&&(a=i[l],s=l);let c=this.patterns[s],d=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:d,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 i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let c=1/this.beta*(s+Math.log(a)),d=this.dotProduct(t,t);return-c+.5*d}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!F().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function Ke(n){return new Pe(n)}O();var $t={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},M=1e-5,Ze=1-M;function zt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function C(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function Jt(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 x=class n{static poincareDistance(e,t){let r=C(Jt(e,t)),i=Math.max(M,1-C(e)),s=Math.max(M,1-C(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=zt(e,t),i=C(e),s=C(t),a=Math.max(M,1+2*r+i*s),c=1+2*r+s,d=1-i,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+d*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(M,1-C(e)),i=Math.sqrt(C(t));if(i<M)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=s/i*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(C(e));if(t<=Ze)return new Float32Array(e);let r=Ze/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(C(e));if(t<M)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},be=class{config;points=new Map;constructor(e){if(this.config={...$t,...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:x.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=x.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:x.poincareDistance(r,s.coordinates),point:s});return i.sort((s,a)=>s.distance-a.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,a=[];for(let d of e)if(s.set(d.id,d),!d.parentId)a.push(d.id);else{let o=i.get(d.parentId);o||(o=[],i.set(d.parentId,o)),o.push(d.id)}let c=a.map((d,o)=>({id:d,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:d,depth:o,angOff:l,angSpan:f}=c.shift(),h=Math.tanh(.3*(o+.1)),u=l+f/2,m=new Float32Array(r);m[0]=h*Math.cos(u),m[1]=h*Math.sin(u);let p=s.get(d);if(p&&p.features.length>0){let H=h*.1;for(let I=2;I<r&&I-2<p.features.length;I++)m[I]=p.features[I-2]*H}let y=x.project(m);t.set(d,y),this.points.set(d,{id:d,coordinates:y,metadata:{depth:o,parentId:p?.parentId}});let w=i.get(d)??[];for(let H=0;H<w.length;H++){let I=f/Math.max(1,w.length);c.push({id:w[H],depth:o+1,angOff:l+H*I,angSpan:I})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function et(n){return Bt()?new be(n):null}function Bt(){return F().useHyperbolicHnsw}O();var Ee=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!k())return!1;try{return this.index=et(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 i=t instanceof Float32Array?t:new Float32Array(t),s=x.euclideanToHyperbolic(i);this.index.insert(e,s,r)}catch(i){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,i instanceof Error?i.message:i)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),i=x.euclideanToHyperbolic(r);return this.index.search(i,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 tt(n){return new Ee(n)}var Ae=null;function nt(){return Ae||(Ae=Qe({dimensions:1e4})),Ae}var Re;function Wt(){return Re===void 0&&(Re=$e()),Re}var Q=null,Te=0;function it(n){return(!Q||Te!==n)&&(Q=Ke({dimension:n,maxPatterns:1e4}),Te=n),Q}var X={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:W,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}},Ce=class{constructor(e,t={}){this.memory=e;this.config={...X,...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;hnswSpaceId=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,L()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new te(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(){if(this.hnswIndex!==null){let e=T()?.spaceId??this.config.embeddingSpaceId??null;return this.hnswSpaceId!==e?(console.warn("[PatternStore] VECTOR_SPACE_MISMATCH: active embedder changed; semantic index disabled"),null):this.hnswIndex}return 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(this.hnswSpaceId=T()?.spaceId??this.config.embeddingSpaceId??null,!this.hnswSpaceId)throw new Error("VECTOR_SPACE_UNVERIFIED: cannot initialize HNSW without runtime provenance");if(F().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-YIILSRXI.js"),{HnswAdapter:c}=await import("./hnsw-adapter-BLSD45CX.js"),d=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(d),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-A3RZODEN.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,i=this.hnswIndex.initialize(),s=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([i,s]),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:",S(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,i=0,s=T()?.spaceId??this.config.embeddingSpaceId;for(let{patternId:a,embedding:c,spaceId:d}of e){if(r>=t)break;if(!s||d!==s||!c||c.length!==this.config.embeddingDimension){i++;continue}let o=this.patternCache.get(a);if(!o){i++;continue}try{await this.hnswIndex.insert(a,c,{filePath:o.patternType,lineCoverage:o.confidence*100,branchCoverage:o.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-o.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",S(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Ye()),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:",S(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=V(e);if(!t.valid)return v(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return v(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));let r=(process.env.AQE_MEMORY_BACKEND??"memory")!=="memory";if(r&&!this.sqliteStore)return v(new A(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let i=T()?.spaceId??this.config.embeddingSpaceId;if(e.embedding&&!i)return v(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let a=this.patternCache.get(e.id)??null,c=!1,d=()=>{this.unindexPattern(e),a&&this.indexPattern(a)};if(this.indexPattern(e),this.sqliteStore)try{let o=this.sqliteStore.storePattern(e,e.embedding,i);o&&o!==e.id&&(this.unindexPattern(e),e.id=o,this.indexPattern(e)),c=!0}catch(o){return d(),v(new A(e.id,"FAILED",o))}if(e.embedding){let o=await this.ensureHNSW();if(!o&&c)return v(new A(e.id,"COMMITTED_PENDING_INDEX",new Error("HNSW unavailable after authoritative pattern commit")));if(!o&&r)return d(),v(new A(e.id,"FAILED",new Error("HNSW unavailable before an authoritative pattern commit")));if(o)try{await o.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(l){return c||d(),v(new A(e.id,c?"COMMITTED_PENDING_INDEX":"FAILED",l))}}if($())try{let l=nt().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,l.vector)}catch(o){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,S(o))}try{let o=Wt();if(o){let l=[e.patternType,e.qeDomain];e.context?.tags&&l.push(...e.context.tags),e.name&&l.push(e.name);let f=o.fingerprintPattern(l);this.hdcTokenCache.set(e.id,f)}}catch(o){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,S(o))}if(re()&&e.embedding)try{it(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(o){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,S(o))}if(L()&&this.deltaTracker)try{let o={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,o)}catch(o){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,S(o))}if(e.embedding)try{let o=this.getVectorDeltaTracker();o&&(a?.embedding?o.recordDelta(e.id,a.embedding,e.embedding):o.getVersion(e.id)<0&&o.recordGenesis(e.id,e.embedding))}catch(o){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,S(o))}try{k()&&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),i={id:D(),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},s=await this.store(i);return s.success?P(i):v(s.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(),i=t.limit||10,s=[];try{if(Array.isArray(e)&&re())try{let h=it(e.length);if(h.getPatternCount()>0){let u=h.recall(new Float32Array(e));if(u&&u.similarity>.98){let m=u.metadata.id,p=await this.get(m);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,u.similarity);s.push({pattern:p,score:u.similarity,matchType:"vector",similarity:u.similarity,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",S(h))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let h=T()?.spaceId??this.config.embeddingSpaceId;if(!h||t.embeddingSpaceId!==h)throw new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId");let u=await this.ensureHNSW();if(u){let m=await u.search(e,i*2);for(let p of m){let y=await this.get(p.key);if(y&&this.matchesFilters(y,t)){let w=this.calculateReuseInfo(y,p.score);s.push({pattern:y,score:p.score,matchType:"vector",similarity:p.score,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let u=new Map(h.map(p=>[p.id,p.ftsScore])),m=new Set(s.map(p=>p.pattern.id));for(let p of s){let y=u.get(p.pattern.id);y!==void 0&&(p.score=.75*p.score+.25*y)}for(let p of h){if(m.has(p.id))continue;let y=await this.get(p.id);if(y&&this.matchesFilters(y,t)){let w=this.calculateReuseInfo(y,p.ftsScore);s.push({pattern:y,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let h=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),u=new Set(s.map(m=>m.pattern.id));for(let m of h)u.has(m.pattern.id)||s.push(m)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let u=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),m=c-u,p=Math.pow(.5,m/a),y=h.pattern.usageCount>0?p:.5;h.score=h.score*(.7+.3*y)}let d=this.sqliteStore?.getDatabase();if(d&&s.length>0)try{this.nullStore||(this.nullStore=new ae(d));let h=this.nullStore.getNullSummaries(s.map(u=>u.pattern.id));for(let u of s){let m=h.get(u.pattern.id);m&&(u.nullSummary=m,u.score=ae.applyNullDiscount(u.score,m,t.contextFingerprint))}}catch(h){console.debug("[PatternStore] null discount skipped:",S(h))}s.sort((h,u)=>u.score-h.score);let o=s;t.filter&&(o=He(s,t.filter));let l=o.slice(0,i),f=performance.now()-r;return this.recordSearchLatency(f),P(l)}catch(a){return v(xe(a))}}async searchByText(e,t,r){let i=[],s=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($()&&s&&this.hdcCache.size>0)try{let d=nt(),o=d.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(u=>this.hdcCache.has(u)).map(u=>({id:u,similarity:d.similarity(o.vector,this.hdcCache.get(u))}));l.sort((u,m)=>m.similarity-u.similarity);let f=l.map(u=>u.id),h=c.filter(u=>!this.hdcCache.has(u));c=[...f,...h]}catch{}for(let d of c){if(i.length>=r)break;let o=this.patternCache.get(d);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(s){let f=o.name.toLowerCase(),h=o.description.toLowerCase();f.includes(s)&&(l+=.5),h.includes(s)&&(s.length/h.length>.3?l+=.5:l+=.3);for(let u of o.context.tags)if(u.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let f=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),d=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&d,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,f=t,h=e.successRate,u=Math.min(e.reuseCount/10,1),m=o?f*.4+h*.4+u*.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,i){let s=await this.get(e);if(!s)return v(new Error(`Pattern not found: ${e}`));let a=new Date,c=s.usageCount+1,d=s.successfulUses+(t?1:0),o=d/c,l=t?.02:-.01,f=Math.max(.1,Math.min(1,s.confidence+l)),h=j({confidence:f,usageCount:c,successRate:o}),u={...s,usageCount:c,successfulUses:d,successRate:o,confidence:f,qualityScore:h,lastUsedAt:a};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,i)}catch(y){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,S(y))}if(L()&&this.deltaTracker)try{let y={id:s.id,name:s.name,confidence:s.confidence,qualityScore:s.qualityScore,usageCount:s.usageCount,successRate:s.successRate,tier:s.tier},w={id:u.id,name:u.name,confidence:u.confidence,qualityScore:u.qualityScore,usageCount:u.usageCount,successRate:u.successRate,tier:u.tier};this.deltaTracker.recordDelta(e,y,w,{success:t})}catch(y){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,S(y))}let m=ne(u);return m.meetsUsageCriteria&&m.meetsQualityCriteria&&m.meetsCoherenceCriteria&&u.tier==="short-term"?await this.promote(e):this.patternCache.set(e,u),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return v(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(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}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 v(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,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let c=await this.ensureHNSW(),d=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?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:d.nativeHNSW,vectorCount:d.vectorCount,indexSizeBytes:d.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=ne(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let d=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-d,l=o>10080*60*1e3,f=s.qualityScore<.2,h=s.usageCount===0&&o>1440*60*1e3;(l&&f||h)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).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 i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}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),Q&&(Q.clear(),Q=null,Te=0),this.initialized=!1}indexHyperbolic(e,t,r){if(k())try{this.hyperbolicIndex||(this.hyperbolicIndex=tt({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!k()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let c=Math.exp(-s.distance),d=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}return P(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function rn(n,e){try{if(F().useRVFPatternStore&&_e()){let r=process.env.AQE_PROJECT_ROOT??De(),i=rt(r,".agentic-qe"),s=rt(i,"patterns.rvf");if(jt(i)){let a={...X,...e},c=!1;try{let d=Me(i,a.embeddingDimension);if(d){c=!0;let o=new z(()=>d,{rvfPath:s,base:a,skipCloseOnDispose:!0,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),o}}catch{}if(!c){let d=new z((o,l)=>{let f=()=>{try{return Oe(o)}catch{return null}},h=f();if(h){if(h.dimension()!==l){try{h.close()}catch{}throw new Error(`RVF dimension mismatch (file=${h.dimension()}, requested=${l})`)}return h}try{return ie(o,l)}catch(u){if(h=f(),h&&h.dimension()===l)return h;if(Ne(o,u instanceof Error?u.message:String(u)))return ie(o,l);throw u}},{rvfPath:s,base:a,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),d}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new Ce(n,e)}export{A as a,rn as b};
|
|
50
50
|
/*! Bundled license information:
|
|
51
51
|
|
|
52
52
|
fast-json-patch/commonjs/helpers.js:
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.
|
|
2
|
-
import{b as E,d as p,e as u,f as L}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.2");process.exit(0)}
|
|
2
|
+
import{b as E,d as p,e as u,f as L}from"./chunk-W2FLULF4.js";import{createHash as R}from"crypto";import{existsSync as A,readFileSync as X,writeFileSync as U,openSync as f,writeSync as I,closeSync as b}from"fs";L();var g=[`CREATE TABLE IF NOT EXISTS qe_patterns (
|
|
3
3
|
id TEXT PRIMARY KEY, pattern_type TEXT NOT NULL, qe_domain TEXT NOT NULL,
|
|
4
4
|
domain TEXT NOT NULL, name TEXT NOT NULL, description TEXT,
|
|
5
5
|
confidence REAL DEFAULT 0.5, usage_count INTEGER DEFAULT 0,
|
|
@@ -1,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.14.
|
|
2
|
-
import{k as K,o as ot}from"./chunk-6YIMLUH6.js";import{a as rt}from"./chunk-CGZ7LTUK.js";import{c as U}from"./chunk-J7VAD4RG.js";import{a as j,c as et}from"./chunk-NAJCQJSK.js";import{a as G,d as at}from"./chunk-L4WATX6B.js";import{a as nt,b as it}from"./chunk-PYAH4K2U.js";import{c as H,e as V,g as w}from"./chunk-EHW62JL2.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>At,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>bt,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,bt,At,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:bt,HyperbolicAttention:At,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}restoreRequestCount(t){this.requestCount=t}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function b(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(b(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(b(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let A=0;for(let p=0;p<n;p++)A+=t[h*n+p]*e[d*n+p];s[h*a+d]=A*u}for(let h=0;h<a;h++){let d=h*a,A=d+a,p=s.subarray(d,A),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let A=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=A*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return b(),F}function te(){return b(),D}function ee(){return b(),W}function re(){return b(),B}function ae(){return b(),z}function ne(){return b(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-P7JW3622.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.2");process.exit(0)}
|
|
2
|
+
import{k as K,o as ot}from"./chunk-W2FLULF4.js";import{a as rt}from"./chunk-PHHXHG2W.js";import{c as U}from"./chunk-ICKLBATY.js";import{a as j,c as et}from"./chunk-D4RCV4LY.js";import{a as G,d as at}from"./chunk-T4C56HBW.js";import{a as nt,b as it}from"./chunk-JIUF6NV6.js";import{c as H,e as V,g as w}from"./chunk-6VKJAMZY.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>At,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>bt,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,bt,At,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:bt,HyperbolicAttention:At,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}restoreRequestCount(t){this.requestCount=t}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function b(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(b(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(b(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let A=0;for(let p=0;p<n;p++)A+=t[h*n+p]*e[d*n+p];s[h*a+d]=A*u}for(let h=0;h<a;h++){let d=h*a,A=d+a,p=s.subarray(d,A),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let A=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=A*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return b(),F}function te(){return b(),D}function ee(){return b(),W}function re(){return b(),B}function ae(){return b(),z}function ne(){return b(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-G7ABZUG7.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};
|