agentic-qe 3.10.3 → 3.10.4
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 +33 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-A62ETL5C.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-NGC6LSQP.js → agent-booster-wasm-EJPDSWON.js} +2 -2
- package/dist/cli/chunks/{agent-handler-P2IJE4GK.js → agent-handler-2DZB7LGI.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-JXRJ5GKQ.js → agent-memory-branch-SSFYAVIK.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-MTCRAV6N.js +2 -0
- package/dist/cli/chunks/audit-42XG5JFB.js +3 -0
- package/dist/cli/chunks/base-KKEBUHZC.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-64EGGWIC.js → better-sqlite3-PX5JM3DG.js} +2 -2
- package/dist/cli/chunks/{brain-handler-SACNDFSW.js → brain-handler-LFHX2TYP.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-LFOTVUDA.js → branch-enumerator-AX7DKGV7.js} +2 -2
- package/dist/cli/chunks/{browser-FK7PRF3W.js → browser-4NYLZ7FA.js} +2 -2
- package/dist/cli/chunks/browser-workflow-XHYAJUB6.js +2 -0
- package/dist/cli/chunks/{chunk-3LRK7PYN.js → chunk-2B6ETC7C.js} +2 -2
- package/dist/cli/chunks/{chunk-VRXY4T22.js → chunk-2G2PVVQG.js} +2 -2
- package/dist/cli/chunks/{chunk-EETVN2OJ.js → chunk-2L5VFVCG.js} +1 -1
- package/dist/cli/chunks/{chunk-CNEWYJKT.js → chunk-2TYO4VZH.js} +3 -3
- package/dist/cli/chunks/{chunk-GHNNJHH3.js → chunk-3ISX5B77.js} +2 -2
- package/dist/cli/chunks/{chunk-X2B7SANM.js → chunk-3UGUX34A.js} +1 -1
- package/dist/cli/chunks/{chunk-VIWIO27R.js → chunk-4BX72XG4.js} +2 -2
- package/dist/cli/chunks/{chunk-3HBWDG62.js → chunk-4FTLYIMW.js} +2 -2
- package/dist/cli/chunks/{chunk-KG5SM36Y.js → chunk-5FNNCVXR.js} +1 -1
- package/dist/cli/chunks/{chunk-72LE6PHL.js → chunk-5Q3L4QEE.js} +2 -2
- package/dist/cli/chunks/{chunk-NZHOKLII.js → chunk-5T2HDET6.js} +3 -3
- package/dist/cli/chunks/{chunk-OX4R55T3.js → chunk-5T4J3IPG.js} +2 -2
- package/dist/cli/chunks/{chunk-QWG76RHA.js → chunk-6OLHPWSN.js} +2 -2
- package/dist/cli/chunks/{chunk-M5CDW2ZH.js → chunk-6SCIX2W2.js} +2 -2
- package/dist/cli/chunks/{chunk-MQOFFRTA.js → chunk-6WF2MOQB.js} +2 -2
- package/dist/cli/chunks/{chunk-JP63XACW.js → chunk-7BQXEYRV.js} +2 -2
- package/dist/cli/chunks/{chunk-H56AROF2.js → chunk-7VO5IEJ2.js} +2 -2
- package/dist/cli/chunks/{chunk-YXH2CVAF.js → chunk-AIBE3J4A.js} +1 -1
- package/dist/cli/chunks/{chunk-BWP3UVPE.js → chunk-AMW27FSS.js} +3 -3
- package/dist/cli/chunks/{chunk-3JAOFKEU.js → chunk-AZJYDM2K.js} +1 -1
- package/dist/cli/chunks/{chunk-MBSJ5G4I.js → chunk-B6CT4ILU.js} +4 -4
- package/dist/cli/chunks/{chunk-FJGSEPFL.js → chunk-BEFRQOLH.js} +2 -2
- package/dist/cli/chunks/{chunk-UIJFU4KD.js → chunk-C2446H7G.js} +2 -2
- package/dist/cli/chunks/{chunk-YIYV2JB6.js → chunk-D7IWGQTW.js} +2 -2
- package/dist/cli/chunks/{chunk-JLL27IGU.js → chunk-D7PI4CYZ.js} +2 -2
- package/dist/cli/chunks/{chunk-I42R57ON.js → chunk-DAIM72HV.js} +2 -2
- package/dist/cli/chunks/{chunk-YYAPO3CU.js → chunk-DPKECIKN.js} +2 -2
- package/dist/cli/chunks/{chunk-E2BJT6A7.js → chunk-E6CGBOZY.js} +2 -2
- package/dist/cli/chunks/{chunk-MC7K44M4.js → chunk-EGTOSQZK.js} +2 -2
- package/dist/cli/chunks/{chunk-NRCL3WCP.js → chunk-EMZ3DXMG.js} +2 -2
- package/dist/cli/chunks/{chunk-NNZMEYLT.js → chunk-EWI37TJA.js} +1 -1
- package/dist/cli/chunks/{chunk-NNVXHC74.js → chunk-F34OO2Q7.js} +3 -3
- package/dist/cli/chunks/{chunk-U7NMPZE2.js → chunk-F6QPAVWS.js} +2 -2
- package/dist/cli/chunks/chunk-F77X5DAF.js +2 -0
- package/dist/cli/chunks/{chunk-6GCOIIHY.js → chunk-FDFJJFQT.js} +2 -2
- package/dist/cli/chunks/{chunk-OPDTDKN3.js → chunk-FQ7I4JBQ.js} +2 -2
- package/dist/cli/chunks/{chunk-RNF47IJ5.js → chunk-G5FPWH5O.js} +2 -2
- package/dist/cli/chunks/{chunk-IRR7YA3Q.js → chunk-GDMH7NPV.js} +2 -2
- package/dist/cli/chunks/{chunk-6FL3GN4T.js → chunk-GILL32E2.js} +2 -2
- package/dist/cli/chunks/{chunk-JE3C7JYN.js → chunk-GLMDRGJD.js} +1 -1
- package/dist/cli/chunks/{chunk-JTF6D2RJ.js → chunk-GS33ZRJH.js} +2 -2
- package/dist/cli/chunks/chunk-HPYGMKZF.js +2 -0
- package/dist/cli/chunks/{chunk-6Q2PPOOF.js → chunk-HTLAPMTK.js} +1 -1
- package/dist/cli/chunks/{chunk-RZCAA2PZ.js → chunk-IAK76TIZ.js} +1 -1
- package/dist/cli/chunks/{chunk-LZ6TNTGO.js → chunk-ICF5RPQU.js} +2 -2
- package/dist/cli/chunks/{chunk-BO2OV2RH.js → chunk-IPAQ4HVX.js} +2 -2
- package/dist/cli/chunks/{chunk-FND6V2RV.js → chunk-ISRTT4I7.js} +8 -8
- package/dist/cli/chunks/{chunk-KTRB3L53.js → chunk-IYFMDIYZ.js} +2 -2
- package/dist/cli/chunks/{chunk-T63EK6GH.js → chunk-JRBGHWAM.js} +2 -2
- package/dist/cli/chunks/{chunk-GL3HZN3O.js → chunk-JYR3X4OC.js} +1 -1
- package/dist/cli/chunks/{chunk-R5ONQAQL.js → chunk-K72J52JO.js} +2 -2
- package/dist/cli/chunks/{chunk-FU77CDEM.js → chunk-K7CW2X6U.js} +2 -2
- package/dist/cli/chunks/{chunk-3X2ZQ55B.js → chunk-K7K4TFJM.js} +3 -3
- package/dist/cli/chunks/{chunk-2ULVCLOW.js → chunk-KCXE2LZU.js} +2 -2
- package/dist/cli/chunks/{chunk-UDV4YB42.js → chunk-KGPAWNNR.js} +1 -1
- package/dist/cli/chunks/{chunk-CTDO2UB2.js → chunk-KJ56OXH4.js} +1 -1
- package/dist/cli/chunks/{chunk-DF3MJ2YL.js → chunk-KUFC4DBX.js} +1 -1
- package/dist/cli/chunks/{chunk-UHDBM7QS.js → chunk-KWZEBHAP.js} +2 -2
- package/dist/cli/chunks/{chunk-WWD5IWTV.js → chunk-L6VNEEN6.js} +1 -1
- package/dist/cli/chunks/{chunk-7SEHQTYD.js → chunk-LHPR7ROV.js} +1 -1
- package/dist/cli/chunks/{chunk-YDKYLNKZ.js → chunk-LKK3NIHC.js} +1 -1
- package/dist/cli/chunks/{chunk-YDDZJCKY.js → chunk-LOFA3U4X.js} +1 -1
- package/dist/cli/chunks/{chunk-HAO3SPOE.js → chunk-LYKSIOOT.js} +2 -2
- package/dist/cli/chunks/chunk-M2PSXKTG.js +2 -0
- package/dist/cli/chunks/{chunk-UZL366ZI.js → chunk-M3MKP5VN.js} +1 -1
- package/dist/cli/chunks/{chunk-7YYTTWGY.js → chunk-M4ARHDY4.js} +1 -1
- package/dist/cli/chunks/{chunk-IL2KOW5W.js → chunk-M5DBKHM4.js} +2 -2
- package/dist/cli/chunks/{chunk-SL6YZAT4.js → chunk-MDWJXSBA.js} +2 -2
- package/dist/cli/chunks/{chunk-HMFEPKAR.js → chunk-MFWWPRBV.js} +2 -2
- package/dist/cli/chunks/{chunk-N7IBYDW5.js → chunk-MHWYQHGN.js} +1 -1
- package/dist/cli/chunks/{chunk-Q7EBD24B.js → chunk-MIQBRVK2.js} +1 -1
- package/dist/cli/chunks/{chunk-ERYMAYJW.js → chunk-MKZQBBCU.js} +2 -2
- package/dist/cli/chunks/{chunk-NEYYLAYS.js → chunk-MQ5WMWUK.js} +2 -2
- package/dist/cli/chunks/chunk-MQIAN57O.js +2 -0
- package/dist/cli/chunks/{chunk-6B4S7PKP.js → chunk-MU4P4P4E.js} +1 -1
- package/dist/cli/chunks/{chunk-B5MMDMH6.js → chunk-MWV4KPOB.js} +2 -2
- package/dist/cli/chunks/{chunk-SWOG3PBD.js → chunk-N244P4MM.js} +2 -2
- package/dist/cli/chunks/{chunk-7ZSPCGTI.js → chunk-N3MM4Z33.js} +2 -2
- package/dist/cli/chunks/{chunk-VDTFRMES.js → chunk-N4CXUGXE.js} +2 -2
- package/dist/cli/chunks/{chunk-C6BBRM2J.js → chunk-ND6YSW5N.js} +1 -1
- package/dist/cli/chunks/{chunk-5IBJURYB.js → chunk-NJYI7HX7.js} +2 -2
- package/dist/cli/chunks/{chunk-4CYLSXA6.js → chunk-NSRDP7RD.js} +2 -2
- package/dist/cli/chunks/{chunk-USFZ4IJD.js → chunk-NZGLDOU4.js} +15 -15
- package/dist/cli/chunks/{chunk-HM523MTQ.js → chunk-O3SG32PS.js} +1 -1
- package/dist/cli/chunks/{chunk-NXPFGPHV.js → chunk-OIFJH7TF.js} +1 -1
- package/dist/cli/chunks/{chunk-5EWWA4QP.js → chunk-OKKTDHHF.js} +6 -6
- package/dist/cli/chunks/{chunk-5SGEOO2F.js → chunk-OO7KJ34Y.js} +2 -2
- package/dist/cli/chunks/{chunk-Z2K5IZM6.js → chunk-OV4BLIKJ.js} +2 -2
- package/dist/cli/chunks/{chunk-RTDHWOAG.js → chunk-PISW5HUX.js} +1 -1
- package/dist/cli/chunks/{chunk-5ER3COX3.js → chunk-PLD4IGDL.js} +2 -2
- package/dist/cli/chunks/{chunk-D2FBUOAR.js → chunk-PMWWWYUM.js} +1 -1
- package/dist/cli/chunks/{chunk-OG7CWWFR.js → chunk-PWJZZCHJ.js} +1 -1
- package/dist/cli/chunks/{chunk-GELF4ILR.js → chunk-PZ4PRZXN.js} +9 -9
- package/dist/cli/chunks/chunk-PZCSJZVJ.js +2 -0
- package/dist/cli/chunks/{chunk-ZXQNE4QV.js → chunk-Q53M4LI7.js} +1 -1
- package/dist/cli/chunks/{chunk-WPVCSFDA.js → chunk-QPMAXDJ2.js} +2 -2
- package/dist/cli/chunks/{chunk-L74CHKFR.js → chunk-RJKYPWFD.js} +2 -2
- package/dist/cli/chunks/{chunk-4OUAHZX2.js → chunk-RUC3FCRK.js} +2 -2
- package/dist/cli/chunks/{chunk-HRLXU4LH.js → chunk-SC6UFGJ6.js} +2 -2
- package/dist/cli/chunks/{chunk-AEJVOJPT.js → chunk-SJC7OKF3.js} +2 -2
- package/dist/cli/chunks/{chunk-X3RJ6SFC.js → chunk-STMMZXS6.js} +1 -1
- package/dist/cli/chunks/{chunk-CAMEFWRK.js → chunk-SVILIQQQ.js} +1 -1
- package/dist/cli/chunks/{chunk-ADV4DH3W.js → chunk-SXMGNMFL.js} +3 -3
- package/dist/cli/chunks/{chunk-ZG4P3DTL.js → chunk-SZKFT6CD.js} +2 -2
- package/dist/cli/chunks/{chunk-4QFAUSWQ.js → chunk-TBJ566KV.js} +2 -2
- package/dist/cli/chunks/{chunk-7RMZAVGO.js → chunk-TCV5DASI.js} +2 -2
- package/dist/cli/chunks/{chunk-U6UK3UMX.js → chunk-TWAWEP4X.js} +3 -3
- package/dist/cli/chunks/chunk-U27GVYXA.js +2 -0
- package/dist/cli/chunks/{chunk-JD2PG4KS.js → chunk-UFKVKNAA.js} +1 -1
- package/dist/cli/chunks/{chunk-FLTPHVZ3.js → chunk-USB7GCIC.js} +1 -1
- package/dist/cli/chunks/{chunk-HQJMCTWN.js → chunk-UW3ZSFFB.js} +2 -2
- package/dist/cli/chunks/{chunk-JTZ3Q2QS.js → chunk-UWAUYDW4.js} +2 -2
- package/dist/cli/chunks/{chunk-QEODION5.js → chunk-UXJVR323.js} +2 -2
- package/dist/cli/chunks/{chunk-QM65UGPV.js → chunk-V5G3SMAJ.js} +2 -2
- package/dist/cli/chunks/{chunk-PL5SLO2W.js → chunk-VDKMBOUK.js} +1 -1
- package/dist/cli/chunks/{chunk-HWM2XJ3P.js → chunk-VJ2D6FST.js} +2 -2
- package/dist/cli/chunks/{chunk-5LON3MLI.js → chunk-VJOPNK2L.js} +2 -2
- package/dist/cli/chunks/{chunk-2L73WXA4.js → chunk-VRE2EBFI.js} +2 -2
- package/dist/cli/chunks/{chunk-3RZL4QTT.js → chunk-WI5WXYIS.js} +2 -2
- package/dist/cli/chunks/{chunk-XTP2GHI7.js → chunk-WIYWDON4.js} +2 -2
- package/dist/cli/chunks/{chunk-SNTMAVPH.js → chunk-WYMQ6FZR.js} +3 -3
- package/dist/cli/chunks/{chunk-BT3QLWII.js → chunk-XBFEHVBO.js} +2 -2
- package/dist/cli/chunks/{chunk-DY5KEOHX.js → chunk-XDZXLEJK.js} +1 -1
- package/dist/cli/chunks/{chunk-PFCAMX6H.js → chunk-XJXCSCCP.js} +1 -1
- package/dist/cli/chunks/{chunk-JXIPRMAY.js → chunk-XVA56PXZ.js} +4 -4
- package/dist/cli/chunks/{chunk-6ZK24V2Y.js → chunk-Y2EDDV5U.js} +2 -2
- package/dist/cli/chunks/{chunk-5G5AAEFF.js → chunk-YSLE6NNG.js} +2 -2
- package/dist/cli/chunks/{chunk-PZHZPX3O.js → chunk-Z4BTPQLG.js} +2 -2
- package/dist/cli/chunks/{chunk-GJUGSH7T.js → chunk-ZM4QGYGK.js} +3 -3
- package/dist/cli/chunks/{ci-AWZ3S5OT.js → ci-2BLMQNX3.js} +2 -2
- package/dist/cli/chunks/{ci-output-JLCYTIMT.js → ci-output-XK4PPSN7.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-BJDKBDIL.js → circuit-breaker-W7X4NPFE.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-KKOP5ZMO.js → claude-flow-setup-GLBLSYNJ.js} +2 -2
- package/dist/cli/chunks/client-C6CJOCRN.js +2 -0
- package/dist/cli/chunks/{cline-installer-7M525SEA.js → cline-installer-7WX7DBGI.js} +2 -2
- package/dist/cli/chunks/{code-27SUVJDO.js → code-SP3HAQWG.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-TTQQZLAK.js → code-index-extractor-44HH36UG.js} +2 -2
- package/dist/cli/chunks/{codex-installer-GHNGNPKP.js → codex-installer-LMXRWLPU.js} +2 -2
- package/dist/cli/chunks/{completions-JPJD24DG.js → completions-GL5FTZAN.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-Q74EJV33.js → complexity-analyzer-CQMYGETL.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-ULTRDIML.js → continuedev-installer-CYVYS5B7.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-EK52X4CG.js → copilot-installer-M7XVII2A.js} +2 -2
- package/dist/cli/chunks/{cost-tracker-2GKBRYXL.js → cost-tracker-S4ET4FH3.js} +2 -2
- package/dist/cli/chunks/{coverage-YCLC3W2A.js → coverage-DFVSSQ4A.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-I3GEA5G6.js +2 -0
- package/dist/cli/chunks/{cursor-installer-B3ALFW5E.js → cursor-installer-KWDSQPQC.js} +2 -2
- package/dist/cli/chunks/{daemon-ZKEBVLJA.js → daemon-2HD54QVO.js} +3 -3
- package/dist/cli/chunks/daemon-CRX46BBO.js +10 -0
- package/dist/cli/chunks/{dag-attention-scheduler-OQPJ6ULA.js → dag-attention-scheduler-SCP6WPZB.js} +2 -2
- package/dist/cli/chunks/{detect-YMYIQH3Q.js → detect-XS2GDCEX.js} +2 -2
- package/dist/cli/chunks/{dist-node-R4FAYQRY.js → dist-node-U43MVQ3F.js} +2 -2
- package/dist/cli/chunks/{domain-handler-IGWXLF2S.js → domain-handler-HITMDULH.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-A7YNO76C.js → domain-transfer-TJF7DNI4.js} +2 -2
- package/dist/cli/chunks/dream-JCQMG2RL.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-KODZAS7Y.js → embed-and-insert-pattern-JKG33YZK.js} +2 -2
- package/dist/cli/chunks/{eval-ALQW7Q2S.js → eval-NF5Y4W37.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-3WK4RXWK.js → experience-capture-middleware-VMMFYJ4D.js} +3 -3
- package/dist/cli/chunks/{fast-paths-PQWDFIJZ.js → fast-paths-W2Q53IR2.js} +2 -2
- package/dist/cli/chunks/{feature-flags-JRUAZCND.js → feature-flags-B4PBMQJO.js} +2 -2
- package/dist/cli/chunks/{feature-flags-6X33B3WX.js → feature-flags-PVI7A4RE.js} +2 -2
- package/dist/cli/chunks/{file-discovery-SA3YU3IH.js → file-discovery-E4L3I33I.js} +2 -2
- package/dist/cli/chunks/{fleet-7TXCAOKQ.js → fleet-LE5SHVLK.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-ZKNYACEC.js → gnn-wrapper-MWWJBLOH.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-KRZRZ23F.js → heartbeat-handler-XOUVNPQK.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-FBHE4ZWH.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-EOOA4WXD.js +2 -0
- package/dist/cli/chunks/hnsw-index-TD3KRPND.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-LVHQ5SG7.js → hnsw-legacy-bridge-W3T5ZDDP.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-HP4JZS6K.js → hnswlib-node-3TZFES5I.js} +2 -2
- package/dist/cli/chunks/hooks-RUPQVIUM.js +250 -0
- package/dist/cli/chunks/hybrid-router-64O6PXZ2.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-2EZBZMFK.js → hypergraph-engine-VDFK3JYH.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-GLPWYII2.js → hypergraph-handler-EUDGEF25.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-ITQHXGTM.js +2 -0
- package/dist/cli/chunks/{init-handler-ZSDO5VMA.js → init-handler-MZEAJOZK.js} +6 -6
- package/dist/cli/chunks/init-wizard-DZ4IKGQI.js +2 -0
- package/dist/cli/chunks/kernel-HSVY4ZYK.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-ATYSDWIV.js → kilocode-installer-ECBYWT6M.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-K66YT6PC.js → kiro-installer-KYFCSYTG.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-H32TXXX4.js +2 -0
- package/dist/cli/chunks/{learning-BVYCC4RI.js → learning-4RAFMDSB.js} +3 -3
- package/dist/cli/chunks/{llm-router-VBCXE6DN.js → llm-router-JHBNLYP3.js} +4 -4
- package/dist/cli/chunks/llm-router-service-3FKESBUX.js +2 -0
- package/dist/cli/chunks/{load-AREDQE2U.js → load-4DVQML7P.js} +2 -2
- package/dist/cli/chunks/load-test-LKHURZGZ.js +2 -0
- package/dist/cli/chunks/{mcp-NG6H6UC5.js → mcp-LCWMU4GZ.js} +2 -2
- package/dist/cli/chunks/{memory-Y65EHG6N.js → memory-3DTJAURT.js} +5 -5
- package/dist/cli/chunks/memory-backend-XRJRZ6CK.js +2 -0
- package/dist/cli/chunks/memory-handlers-BL6E3XAK.js +2 -0
- package/dist/cli/chunks/{multi-model-executor-VRPRFUZT.js → multi-model-executor-AVR5SZOO.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-CKQXPM5R.js → opencode-installer-DW2426QM.js} +2 -2
- package/dist/cli/chunks/{orchestrator-I7JBKD6G.js → orchestrator-AHF4W5GS.js} +5 -5
- package/dist/cli/chunks/{pipeline-MV2RWCBI.js → pipeline-N6THEWYE.js} +2 -2
- package/dist/cli/chunks/{platform-VU5P3SOG.js → platform-MRCFQF7X.js} +2 -2
- package/dist/cli/chunks/{plugin-6TERLKCB.js → plugin-6YKUN5QM.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-WIUIN2DL.js → prime-radiant-advanced-wasm-2YPAHSVS.js} +2 -2
- package/dist/cli/chunks/protocol-executor-KABPB6PQ.js +2 -0
- package/dist/cli/chunks/{protocol-handler-HKWBGARO.js → protocol-handler-Y2NMUKWQ.js} +2 -2
- package/dist/cli/chunks/{prove-7CQPHBRJ.js → prove-DZUNWBFD.js} +2 -2
- package/dist/cli/chunks/provider-manager-U7EBM3FA.js +2 -0
- package/dist/cli/chunks/qe-reasoning-bank-64O2OQIW.js +2 -0
- package/dist/cli/chunks/{quality-VLUVXKVG.js → quality-AIFQMGUV.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-SV3COGIL.js +2 -0
- package/dist/cli/chunks/{real-embeddings-JPZ64KK2.js → real-embeddings-5XL4LOG2.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-NONVB3UE.js → roocode-installer-LV3WONT5.js} +2 -2
- package/dist/cli/chunks/router-QARRPMED.js +2 -0
- package/dist/cli/chunks/routing-feedback-KD2JFTPK.js +2 -0
- package/dist/cli/chunks/{routing-handler-YYXDT4J2.js → routing-handler-WSMUILGD.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-5PFMNDLR.js → ruvector-commands-BCEIDTW3.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-TF6H7AXH.js → rvf-dual-writer-LRSPC6H3.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-VNGIUZCO.js → rvf-migration-adapter-QHNX6353.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-VA52YAIY.js → rvf-migration-coordinator-SLNB3XPW.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-4LLGF5AY.js +2 -0
- package/dist/cli/chunks/safe-db-RAX3H2P7.js +2 -0
- package/dist/cli/chunks/schedule-RQZGLLUY.js +2 -0
- package/dist/cli/chunks/scheduler-ACWTN4LN.js +2 -0
- package/dist/cli/chunks/{security-62HEETBF.js → security-CYY6TECQ.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-U6JE4O6A.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-JTZK7LRD.js → shared-rvf-dual-writer-PJBSNBRV.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-SWNBO257.js +2 -0
- package/dist/cli/chunks/{status-handler-LSUPUKRF.js → status-handler-W723LXX5.js} +2 -2
- package/dist/cli/chunks/{structural-health-Z75A666N.js → structural-health-WZUPZBB5.js} +2 -2
- package/dist/cli/chunks/{sync-M3O4T3A3.js → sync-UA22CKUS.js} +2 -2
- package/dist/cli/chunks/sync-ZLMF53TB.js +2 -0
- package/dist/cli/chunks/{task-handler-AQBSZAQC.js → task-handler-SENTEEXZ.js} +2 -2
- package/dist/cli/chunks/{task-handlers-BOZP247V.js → task-handlers-FGVUZOCC.js} +3 -3
- package/dist/cli/chunks/{test-FTEGPNN2.js → test-Q37C3WI2.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-IGR4U2VQ.js → test-scheduling-E6SPIBTH.js} +3 -3
- package/dist/cli/chunks/token-bootstrap-HQFFMZUF.js +2 -0
- package/dist/cli/chunks/{token-usage-VCHV47EO.js → token-usage-JHNWTZ7L.js} +2 -2
- package/dist/cli/chunks/{transformers-M27QSNFH.js → transformers-TEXDUVNI.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-IIGEJYFU.js → tree-sitter-wasm-parser-MWSS52H6.js} +2 -2
- package/dist/cli/chunks/{types-RQFPUUKA.js → types-YQRKHYH3.js} +2 -2
- package/dist/cli/chunks/unified-memory-QG3FDRKR.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-KOR4EOIG.js +2 -0
- package/dist/cli/chunks/unified-persistence-J6NIRYKM.js +2 -0
- package/dist/cli/chunks/{upgrade-VJMYX3AL.js → upgrade-JKMEDURI.js} +2 -2
- package/dist/cli/chunks/{validate-ML7HUAU5.js → validate-URO7G6OE.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-RCR6EYRC.js → validate-swarm-VZVJ56Z5.js} +2 -2
- package/dist/cli/chunks/{vibium-ZOOS3W5L.js → vibium-G5WZILL6.js} +2 -2
- package/dist/cli/chunks/visual-security-RAWV6YLN.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-2YPGYLWK.js → web-tree-sitter-LECH5T6H.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-GOJWUWC5.js → windsurf-installer-2NPLC2YW.js} +2 -2
- package/dist/cli/chunks/{witness-chain-3MGSS3Q4.js → witness-chain-X347C36A.js} +2 -2
- package/dist/cli/chunks/witness-chain-ZO7FIM35.js +2 -0
- package/dist/cli/chunks/{workflow-B5Q77BI4.js → workflow-V4ALYZ73.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-7SKITNIJ.js +2 -0
- package/dist/cli/chunks/wrappers-QXOPRPR4.js +2 -0
- package/dist/cli/commands/hooks-handlers/task-hooks.js +50 -0
- package/dist/integrations/ruvector/shared-rvf-adapter.js +12 -1
- package/dist/integrations/ruvector/shared-rvf-dual-writer.js +6 -2
- package/dist/kernel/project-root.d.ts +33 -0
- package/dist/kernel/project-root.js +86 -0
- package/dist/kernel/unified-memory.d.ts +2 -19
- package/dist/kernel/unified-memory.js +8 -64
- package/dist/learning/local-judge-client.d.ts +55 -0
- package/dist/learning/local-judge-client.js +127 -0
- package/dist/learning/nagual-client.d.ts +73 -0
- package/dist/learning/nagual-client.js +150 -0
- package/dist/learning/pattern-store.js +10 -3
- package/dist/mcp/bundle.js +392 -390
- package/dist/mcp/entry.js +44 -33
- package/dist/mcp/transport/stdio.d.ts +7 -0
- package/dist/mcp/transport/stdio.js +39 -2
- package/dist/workers/daemon.js +2 -0
- package/dist/workers/quality-daemon/git-watcher.js +2 -0
- package/dist/workers/quality-daemon/index.js +2 -0
- package/dist/workers/worker-manager.js +4 -0
- package/package.json +1 -1
- package/dist/cli/chunks/adapter-BHPUKMJ5.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-JQ5WD2HM.js +0 -2
- package/dist/cli/chunks/audit-BMQ3VESB.js +0 -3
- package/dist/cli/chunks/base-E32WLGY2.js +0 -2
- package/dist/cli/chunks/browser-workflow-LNNXXAJG.js +0 -2
- package/dist/cli/chunks/chunk-2EQVYYBF.js +0 -2
- package/dist/cli/chunks/chunk-3VF3HCG4.js +0 -2
- package/dist/cli/chunks/chunk-JOLDCS6X.js +0 -2
- package/dist/cli/chunks/chunk-JSFYPLMQ.js +0 -2
- package/dist/cli/chunks/chunk-YX2HY4MX.js +0 -2
- package/dist/cli/chunks/client-2UKBYFX4.js +0 -2
- package/dist/cli/chunks/cross-domain-router-FPM3L27L.js +0 -2
- package/dist/cli/chunks/daemon-YWINEHG4.js +0 -10
- package/dist/cli/chunks/dream-XM33US3V.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-GM3M2MTG.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-K62GEHIL.js +0 -2
- package/dist/cli/chunks/hnsw-index-VCAK3TWN.js +0 -2
- package/dist/cli/chunks/hooks-6Y3UHYI2.js +0 -248
- package/dist/cli/chunks/hybrid-router-432QNCNG.js +0 -2
- package/dist/cli/chunks/impact-analyzer-VTSISNN4.js +0 -2
- package/dist/cli/chunks/init-wizard-COB5AH7Q.js +0 -2
- package/dist/cli/chunks/kernel-ROK7X5FM.js +0 -2
- package/dist/cli/chunks/knowledge-graph-YUWIDIWW.js +0 -2
- package/dist/cli/chunks/llm-router-service-7VLXJ7VE.js +0 -2
- package/dist/cli/chunks/load-test-32524DL3.js +0 -2
- package/dist/cli/chunks/memory-backend-BI2V5AAB.js +0 -2
- package/dist/cli/chunks/memory-handlers-NSOFWVFN.js +0 -2
- package/dist/cli/chunks/protocol-executor-2UPB7SPI.js +0 -2
- package/dist/cli/chunks/provider-manager-PDT37MIJ.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-AQQ2BI4V.js +0 -2
- package/dist/cli/chunks/queen-coordinator-6DVDVEU4.js +0 -2
- package/dist/cli/chunks/router-O2G4KQ6L.js +0 -2
- package/dist/cli/chunks/routing-feedback-TAGTD3KQ.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-46GRWQJR.js +0 -2
- package/dist/cli/chunks/safe-db-LNIPXXHH.js +0 -2
- package/dist/cli/chunks/schedule-AUH3ZALY.js +0 -2
- package/dist/cli/chunks/scheduler-KK3OYPWW.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-XWTQPGCT.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-CYESP7NG.js +0 -2
- package/dist/cli/chunks/sync-VI37UHHH.js +0 -2
- package/dist/cli/chunks/token-bootstrap-2DFRVMBM.js +0 -2
- package/dist/cli/chunks/unified-memory-RISHEANP.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-2IKXGMNZ.js +0 -2
- package/dist/cli/chunks/unified-persistence-ZTTUJNTU.js +0 -2
- package/dist/cli/chunks/visual-security-D66DTAO5.js +0 -2
- package/dist/cli/chunks/witness-chain-RHWHHDLV.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-OQMFW2TC.js +0 -2
- package/dist/cli/chunks/wrappers-MM5VLEPG.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{d as
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.4");process.exit(0)}
|
|
2
|
+
import{d as G,f as Xe}from"./chunk-K72J52JO.js";import{a as k,b,c as we}from"./chunk-U27GVYXA.js";import{b as L,d as Z}from"./chunk-IYFMDIYZ.js";import{a as De}from"./chunk-HPYGMKZF.js";import{c as Q}from"./chunk-VRE2EBFI.js";import{a as V,c as be}from"./chunk-2B6ETC7C.js";import{a as J,b as ye}from"./chunk-RJKYPWFD.js";import{a as ee,d as v,e as te,f as ne}from"./chunk-UWAUYDW4.js";import{a as O,e as ve}from"./chunk-6OLHPWSN.js";import{c as R,e as Oe}from"./chunk-SVILIQQQ.js";function I(i){if(!q.has(i))throw new Error(`Invalid table name: "${i}" is not in the allowlist`);return i}function ze(i){let e=i.split(".");if(e.length>2)throw new Error(`Invalid SQL identifier: "${i}" has too many parts (max: schema.table)`);for(let t of e)if(!re.test(t))throw new Error(`Invalid SQL identifier: "${i}" \u2014 part "${t}" does not match pattern ${re}`);return i}var q,re,z=R(()=>{"use strict";q=new Set(["schema_version","kv_store","vectors","rl_q_values","goap_goals","goap_actions","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","sona_patterns","sona_fisher_matrices","test_outcomes","routing_outcomes","coverage_sessions","patterns","hypergraph_nodes","hypergraph_edges","hypergraph_vertices","hypergraph_hyperedges","hypergraph_edge_vertices","hypergraph_vertex_properties","hypergraph_edge_properties","captured_experiences","experience_applications","witness_chain","witness_chain_receipts","witness_chain_archive","trajectories","trajectory_steps","pattern_evolution_events","pattern_relationships","pattern_versions","learning_daily_snapshots","metrics_outcomes","experience_consolidation_log","qe_pattern_reuse","qe_agent_co_execution"]);re=/^[a-z_][a-z0-9_]{0,62}$/});var D,se,oe,ie,ae,ce,Te,Ee,de,ue,le,pe,ge=R(()=>{"use strict";Xe();D=9,se=`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS schema_version (
|
|
4
4
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
5
5
|
version INTEGER NOT NULL,
|
|
@@ -551,16 +551,16 @@ import{d as k,f as we}from"./chunk-R5ONQAQL.js";import{b as C,d as Z}from"./chun
|
|
|
551
551
|
CREATE INDEX IF NOT EXISTS idx_coverage_sessions_technique ON coverage_sessions(technique);
|
|
552
552
|
CREATE INDEX IF NOT EXISTS idx_coverage_sessions_agent ON coverage_sessions(agent_id);
|
|
553
553
|
CREATE INDEX IF NOT EXISTS idx_coverage_sessions_created ON coverage_sessions(created_at);
|
|
554
|
-
`,pe=["kv_store","vectors","rl_q_values","goap_actions","goap_goals","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","hypergraph_nodes","hypergraph_edges","sona_patterns","witness_chain"]});function y(i,e,t){let n={value:e,timestamp:t??(e!==void 0?Date.now():0),nodeId:e!==void 0?i:"",version:e!==void 0?1:0,lastUpdated:Date.now()};function T(o,a,u,d){return o!==u?o-u:a.localeCompare(d)}return{get(){return n.value},set(o,a){let u=a??Date.now();(n.timestamp===0||T(u,i,n.timestamp,n.nodeId)>0)&&(n={value:o,timestamp:u,nodeId:i,version:n.version+1,lastUpdated:Date.now()})},merge(o){let a=o.getState();this.applyState(a)},getState(){return{value:n.value,timestamp:n.timestamp,nodeId:n.nodeId,version:n.version,lastUpdated:n.lastUpdated}},applyState(o){(n.timestamp===0||T(o.timestamp,o.nodeId,n.timestamp,n.nodeId)>0)&&(n={value:o.value,timestamp:o.timestamp,nodeId:o.nodeId,version:Math.max(n.version,o.version)+1,lastUpdated:Date.now()})},getNodeId(){return i},getTimestamp(){return n.timestamp}}}function X(i,e){let t=y(i);return t.applyState(e),t}var j=R(()=>{"use strict"});function I(i){let e={counts:{},version:0,lastUpdated:Date.now()};return e.counts[i]=0,{get(){return Object.values(e.counts).reduce((t,n)=>t+n,0)},increment(t=1){if(t<0)throw new Error("G-Counter can only increment by positive values");t!==0&&(e.counts[i]=(e.counts[i]||0)+t,e.version++,e.lastUpdated=Date.now())},merge(t){let n=t.getState();this.applyState(n)},getState(){return{counts:{...e.counts},version:e.version,lastUpdated:e.lastUpdated}},applyState(t){let n=!1;for(let[T,o]of Object.entries(t.counts)){let a=e.counts[T]||0;o>a&&(e.counts[T]=o,n=!0)}n&&(e.version=Math.max(e.version,t.version)+1,e.lastUpdated=Date.now())},getNodeId(){return i},getLocalCount(){return e.counts[i]||0}}}function w(i,e){let t=I(i);return t.applyState(e),t}var U=R(()=>{"use strict"});function F(i){let e=I(i),t=I(i),n=0,T=Date.now();return{get(){return e.get()-t.get()},increment(o=1){if(o<0)throw new Error("Use decrement() for negative values");o!==0&&(e.increment(o),n++,T=Date.now())},decrement(o=1){if(o<0)throw new Error("Use increment() for negative values");o!==0&&(t.increment(o),n++,T=Date.now())},merge(o){let a=o.getState();this.applyState(a)},getState(){return{positive:e.getState(),negative:t.getState(),version:n,lastUpdated:T}},applyState(o){let a=this.get();e.applyState(o.positive),t.applyState(o.negative);let u=this.get();a!==u&&(n=Math.max(n,o.version)+1,T=Date.now())},getNodeId(){return i}}}function x(i,e){let t=F(i);return t.applyState(e),t}var B=R(()=>{"use strict";U()});function Ue(i,e){return`${i}:${Date.now()}:${e}`}function W(i){return typeof i=="string"?`s:${i}`:typeof i=="number"?`n:${i}`:typeof i=="boolean"?`b:${i}`:`j:${JSON.stringify(i)}`}function Fe(i){let e=i.substring(0,2),t=i.substring(2);switch(e){case"s:":return t;case"n:":return Number(t);case"b:":return t==="true";case"j:":return C(t);default:throw new Error(`Unknown serialization type: ${e}`)}}function M(i){let e=new Map,t=new Map,n=0,T=Date.now(),o=0;function a(d){let E=e.get(d);if(!E||E.size===0)return!1;let l=t.get(d);if(!l||l.size===0)return!0;for(let m of E)if(!l.has(m))return!0;return!1}function u(d){let E=e.get(d);if(!E)return new Set;let l=t.get(d)||new Set,m=new Set;for(let p of E)l.has(p)||m.add(p);return m}return{has(d){let E=W(d);return a(E)},values(){let d=[];for(let[E]of e)a(E)&&d.push(Fe(E));return d},size(){let d=0;for(let[E]of e)a(E)&&d++;return d},add(d){let E=W(d),l=Ue(i,o++);e.has(E)||e.set(E,new Set),e.get(E).add(l),n++,T=Date.now()},remove(d){let E=W(d),l=e.get(E);if(!l||l.size===0)return;t.has(E)||t.set(E,new Set);let m=t.get(E);for(let p of l)m.add(p);n++,T=Date.now()},merge(d){let E=d.getState();this.applyState(E)},getState(){let d={};for(let[l,m]of e)d[l]=Array.from(m);let E={};for(let[l,m]of t)m.size>0&&(E[l]=Array.from(m));return{elements:d,tombstones:E,version:n,lastUpdated:T}},applyState(d){let E=!1;for(let[l,m]of Object.entries(d.elements)){e.has(l)||e.set(l,new Set);let p=e.get(l);for(let S of m)p.has(S)||(p.add(S),E=!0)}for(let[l,m]of Object.entries(d.tombstones)){t.has(l)||t.set(l,new Set);let p=t.get(l);for(let S of m)p.has(S)||(p.add(S),E=!0)}E&&(n=Math.max(n,d.version)+1,T=Date.now())},getNodeId(){return i},clear(){for(let[d,E]of e){t.has(d)||t.set(d,new Set);let l=t.get(d);for(let m of E)l.add(m)}n++,T=Date.now()}}}function P(i,e){let t=M(i);return t.applyState(e),t}var Y=R(()=>{"use strict";Z()});function H(i){let e={...xe,...i},{nodeId:t,enableDeltaTracking:n,maxDeltaHistory:T}=e,o=new Map,a=new Map,u=new Map,d=new Map,E=0,l=[],m=new Set,p={registers:new Set,gCounters:new Set,pnCounters:new Set,sets:new Set};function S(s,r,c){let _={key:s,type:r,operation:c,timestamp:Date.now(),nodeId:t};for(let Ae of m)try{Ae(_)}catch(Oe){console.error("[CRDTStore] Error in change listener:",Oe)}}function N(s,r){E++,n&&p[s].add(r)}function K(){if(!n||!(p.registers.size>0||p.gCounters.size>0||p.pnCounters.size>0||p.sets.size>0))return;let r={fromVersion:l.length>0?l[l.length-1].toVersion:0,toVersion:E,timestamp:Date.now(),nodeId:t};if(p.registers.size>0){r.registers={};for(let c of p.registers){let _=o.get(c);_&&(r.registers[c]=_.getState())}p.registers.clear()}if(p.gCounters.size>0){r.gCounters={};for(let c of p.gCounters){let _=a.get(c);_&&(r.gCounters[c]=_.getState())}p.gCounters.clear()}if(p.pnCounters.size>0){r.pnCounters={};for(let c of p.pnCounters){let _=u.get(c);_&&(r.pnCounters[c]=_.getState())}p.pnCounters.clear()}if(p.sets.size>0){r.sets={};for(let c of p.sets){let _=d.get(c);_&&(r.sets[c]=_.getState())}p.sets.clear()}for(l.push(r);l.length>T;)l.shift()}let L={getRegister(s){return o.has(s)||o.set(s,y(t)),o.get(s)},setRegister(s,r){L.getRegister(s).set(r),N("registers",s),S(s,"lww-register","set")},hasRegister(s){return o.has(s)},deleteRegister(s){let r=o.delete(s);return r&&N("registers",s),r},getGCounter(s){return a.has(s)||a.set(s,I(t)),a.get(s)},incrementGCounter(s,r){L.getGCounter(s).increment(r),N("gCounters",s),S(s,"g-counter","increment")},hasGCounter(s){return a.has(s)},deleteGCounter(s){let r=a.delete(s);return r&&N("gCounters",s),r},getCounter(s){return u.has(s)||u.set(s,F(t)),u.get(s)},incrementCounter(s,r){L.getCounter(s).increment(r),N("pnCounters",s),S(s,"pn-counter","increment")},decrementCounter(s,r){L.getCounter(s).decrement(r),N("pnCounters",s),S(s,"pn-counter","decrement")},hasCounter(s){return u.has(s)},deleteCounter(s){let r=u.delete(s);return r&&N("pnCounters",s),r},getSet(s){return d.has(s)||d.set(s,M(t)),d.get(s)},addToSet(s,r){L.getSet(s).add(r),N("sets",s),S(s,"or-set","add")},removeFromSet(s,r){L.getSet(s).remove(r),N("sets",s),S(s,"or-set","remove")},hasSet(s){return d.has(s)},deleteSet(s){let r=d.delete(s);return r&&N("sets",s),r},merge(s){let r=s.getState();L.applyState(r)},getState(){K();let s={version:E,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let[r,c]of o)s.registers[r]=c.getState();for(let[r,c]of a)s.gCounters[r]=c.getState();for(let[r,c]of u)s.pnCounters[r]=c.getState();for(let[r,c]of d)s.sets[r]=c.getState();return s},applyState(s){for(let[r,c]of Object.entries(s.registers))o.has(r)?o.get(r).applyState(c):o.set(r,X(t,c)),N("registers",r),S(r,"lww-register","merge");for(let[r,c]of Object.entries(s.gCounters))a.has(r)?a.get(r).applyState(c):a.set(r,w(t,c)),N("gCounters",r),S(r,"g-counter","merge");for(let[r,c]of Object.entries(s.pnCounters))u.has(r)?u.get(r).applyState(c):u.set(r,x(t,c)),N("pnCounters",r),S(r,"pn-counter","merge");for(let[r,c]of Object.entries(s.sets))d.has(r)?d.get(r).applyState(c):d.set(r,P(t,c)),N("sets",r),S(r,"or-set","merge");E=Math.max(E,s.version)+1},getDelta(s){if(K(),l.length===0)return s>=E,null;let r=l.filter(_=>_.toVersion>s);if(r.length===0)return null;let c={fromVersion:s,toVersion:E,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let _ of r)_.registers&&Object.assign(c.registers,_.registers),_.gCounters&&Object.assign(c.gCounters,_.gCounters),_.pnCounters&&Object.assign(c.pnCounters,_.pnCounters),_.sets&&Object.assign(c.sets,_.sets);return Object.keys(c.registers).length===0&&delete c.registers,Object.keys(c.gCounters).length===0&&delete c.gCounters,Object.keys(c.pnCounters).length===0&&delete c.pnCounters,Object.keys(c.sets).length===0&&delete c.sets,c},applyDelta(s){if(s.registers)for(let[r,c]of Object.entries(s.registers))o.has(r)?o.get(r).applyState(c):o.set(r,X(t,c)),N("registers",r),S(r,"lww-register","merge");if(s.gCounters)for(let[r,c]of Object.entries(s.gCounters))a.has(r)?a.get(r).applyState(c):a.set(r,w(t,c)),N("gCounters",r),S(r,"g-counter","merge");if(s.pnCounters)for(let[r,c]of Object.entries(s.pnCounters))u.has(r)?u.get(r).applyState(c):u.set(r,x(t,c)),N("pnCounters",r),S(r,"pn-counter","merge");if(s.sets)for(let[r,c]of Object.entries(s.sets))d.has(r)?d.get(r).applyState(c):d.set(r,P(t,c)),N("sets",r),S(r,"or-set","merge");E=Math.max(E,s.toVersion)+1},getVersion(){return E},getNodeId(){return t},on(s,r){if(s==="change")return m.add(r),()=>{m.delete(r)};throw new Error(`Unknown event type: ${s}`)},removeAllListeners(){m.clear()},keys(s){let r=[];return(!s||s==="lww-register")&&r.push(...Array.from(o.keys())),(!s||s==="g-counter")&&r.push(...Array.from(a.keys())),(!s||s==="pn-counter")&&r.push(...Array.from(u.keys())),(!s||s==="or-set")&&r.push(...Array.from(d.keys())),r},clear(){o.clear(),a.clear(),u.clear(),d.clear(),l.length=0,p.registers.clear(),p.gCounters.clear(),p.pnCounters.clear(),p.sets.clear(),E=0},getStats(){return{total:o.size+a.size+u.size+d.size,registers:o.size,gCounters:a.size,pnCounters:u.size,sets:d.size,version:E,nodeId:t,deltaHistorySize:l.length}}};return L}var xe,me=R(()=>{"use strict";j();U();B();Y();xe={nodeId:"default-node",enableDeltaTracking:!0,maxDeltaHistory:100}});var _e=R(()=>{"use strict"});var fe=R(()=>{"use strict";j();U();B();Y();me();_e()});var ke={};be(ke,{ALLOWED_TABLE_NAMES:()=>q,BinaryHeap:()=>ee,DEFAULT_UNIFIED_MEMORY_CONFIG:()=>Le,UnifiedHnswIndex:()=>v,UnifiedMemoryManager:()=>O,clearProjectRootCache:()=>Re,createHnswIndex:()=>te,findProjectRoot:()=>G,getDefaultDbPath:()=>he,getResolvedDefaultConfig:()=>Ce,getUnifiedMemory:()=>Ie,initializeUnifiedMemory:()=>Me,resetUnifiedMemory:()=>Pe,validateTableName:()=>A});import*as g from"fs";import*as Ne from"os";import*as f from"path";function Re(){h=null}function G(i=process.cwd()){if(h)return h;if(process.env.AQE_PROJECT_ROOT)return h=process.env.AQE_PROJECT_ROOT,h;let e=i,t=f.parse(e).root,n=e,T=null,o=null,a=null;for(;n!==t;)g.existsSync(f.join(n,".agentic-qe"))&&(T=n),g.existsSync(f.join(n,".git"))&&o===null&&(o=n),g.existsSync(f.join(n,"package.json"))&&(a=n),n=f.dirname(n);return T?h=T:o?h=o:a?h=a:h=process.cwd(),h}function he(){let i=G();return f.join(i,".agentic-qe","memory.db")}function Ce(){return{...Le,dbPath:he()}}function Ie(i){return O.getInstance(i)}async function Me(i){let e=Ie(i);return await e.initialize(),e}function Pe(){O.resetInstance()}function Ge(){if(Se)return;Se=!0;let i=()=>{try{let e=O.instance;e&&e.close()}catch(e){console.debug("[UnifiedMemory] Cleanup error:",e instanceof Error?e.message:e)}};process.on("beforeExit",i),process.on("SIGINT",()=>{i(),process.exit(0)}),process.on("SIGTERM",()=>{i(),process.exit(0)})}var $,h,Le,O,Se,qe=R(()=>{Xe();Z();ve();De();ye();z();z();ne();ne();ge();fe();$=Q.create("unified-memory"),h=null;Le={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:b.MMAP_SIZE_BYTES,cacheSize:b.CACHE_SIZE_KB,busyTimeout:b.BUSY_TIMEOUT_MS,vectorDimensions:b.DEFAULT_VECTOR_DIMENSIONS};O=class i{static instance=null;static instancePromise=null;db=null;config;initialized=!1;vectorsLoaded=!1;initPromise=null;preparedStatements=new Map;vectorIndex=new v("qe-memory");crdtStore=null;constructor(e){let t=Ce();if(this.config={...t,...e},!f.isAbsolute(this.config.dbPath)){let n=G();this.config.dbPath=f.join(n,this.config.dbPath)}}static getInstance(e){return i.instance||(i.instance=new i(e)),i.instance}static async getInstanceAsync(e){return i.instance?.initialized?i.instance:(i.instancePromise||(i.instancePromise=(async()=>{let t=i.getInstance(e);return await t.initialize(),t})()),i.instancePromise)}static resetInstance(){i.instance&&(i.instance.close(),i.instance=null),i.instancePromise=null,Re()}async initialize(e){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize(e?.signal)),this.initPromise}async _doInitialize(e){if(!this.initialized){e?.throwIfAborted();try{let t=process.env.AQE_PROJECT_ROOT;if(t){let a=f.resolve(this.config.dbPath),u=f.resolve(t);!a.startsWith(u)&&!a.startsWith(Ne.tmpdir())&&a.includes(".agentic-qe")&&(console.error(`[UnifiedMemory] WARNING: DB path "${this.config.dbPath}" points to a production .agentic-qe/ while AQE_PROJECT_ROOT="${t}". Redirecting to test-safe path.`),this.config.dbPath=f.join(t,".agentic-qe","memory.db"))}let n=f.dirname(this.config.dbPath);g.existsSync(n)||g.mkdirSync(n,{recursive:!0});let T=g.existsSync(this.config.dbPath),o=0;if(T)o=g.statSync(this.config.dbPath).size;else if(g.existsSync(n)){let a=this.findRecentBackups(n);if(a.length>0){let u=a[0];console.error(`[UnifiedMemory] CRITICAL: Database file missing but directory exists!
|
|
554
|
+
`,pe=["kv_store","vectors","rl_q_values","goap_actions","goap_goals","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","hypergraph_nodes","hypergraph_edges","sona_patterns","witness_chain"]});function y(i,e,t){let n={value:e,timestamp:t??(e!==void 0?Date.now():0),nodeId:e!==void 0?i:"",version:e!==void 0?1:0,lastUpdated:Date.now()};function E(o,c,u,d){return o!==u?o-u:c.localeCompare(d)}return{get(){return n.value},set(o,c){let u=c??Date.now();(n.timestamp===0||E(u,i,n.timestamp,n.nodeId)>0)&&(n={value:o,timestamp:u,nodeId:i,version:n.version+1,lastUpdated:Date.now()})},merge(o){let c=o.getState();this.applyState(c)},getState(){return{value:n.value,timestamp:n.timestamp,nodeId:n.nodeId,version:n.version,lastUpdated:n.lastUpdated}},applyState(o){(n.timestamp===0||E(o.timestamp,o.nodeId,n.timestamp,n.nodeId)>0)&&(n={value:o.value,timestamp:o.timestamp,nodeId:o.nodeId,version:Math.max(n.version,o.version)+1,lastUpdated:Date.now()})},getNodeId(){return i},getTimestamp(){return n.timestamp}}}function X(i,e){let t=y(i);return t.applyState(e),t}var j=R(()=>{"use strict"});function C(i){let e={counts:{},version:0,lastUpdated:Date.now()};return e.counts[i]=0,{get(){return Object.values(e.counts).reduce((t,n)=>t+n,0)},increment(t=1){if(t<0)throw new Error("G-Counter can only increment by positive values");t!==0&&(e.counts[i]=(e.counts[i]||0)+t,e.version++,e.lastUpdated=Date.now())},merge(t){let n=t.getState();this.applyState(n)},getState(){return{counts:{...e.counts},version:e.version,lastUpdated:e.lastUpdated}},applyState(t){let n=!1;for(let[E,o]of Object.entries(t.counts)){let c=e.counts[E]||0;o>c&&(e.counts[E]=o,n=!0)}n&&(e.version=Math.max(e.version,t.version)+1,e.lastUpdated=Date.now())},getNodeId(){return i},getLocalCount(){return e.counts[i]||0}}}function w(i,e){let t=C(i);return t.applyState(e),t}var U=R(()=>{"use strict"});function F(i){let e=C(i),t=C(i),n=0,E=Date.now();return{get(){return e.get()-t.get()},increment(o=1){if(o<0)throw new Error("Use decrement() for negative values");o!==0&&(e.increment(o),n++,E=Date.now())},decrement(o=1){if(o<0)throw new Error("Use increment() for negative values");o!==0&&(t.increment(o),n++,E=Date.now())},merge(o){let c=o.getState();this.applyState(c)},getState(){return{positive:e.getState(),negative:t.getState(),version:n,lastUpdated:E}},applyState(o){let c=this.get();e.applyState(o.positive),t.applyState(o.negative);let u=this.get();c!==u&&(n=Math.max(n,o.version)+1,E=Date.now())},getNodeId(){return i}}}function x(i,e){let t=F(i);return t.applyState(e),t}var B=R(()=>{"use strict";U()});function Ue(i,e){return`${i}:${Date.now()}:${e}`}function W(i){return typeof i=="string"?`s:${i}`:typeof i=="number"?`n:${i}`:typeof i=="boolean"?`b:${i}`:`j:${JSON.stringify(i)}`}function Fe(i){let e=i.substring(0,2),t=i.substring(2);switch(e){case"s:":return t;case"n:":return Number(t);case"b:":return t==="true";case"j:":return L(t);default:throw new Error(`Unknown serialization type: ${e}`)}}function M(i){let e=new Map,t=new Map,n=0,E=Date.now(),o=0;function c(d){let T=e.get(d);if(!T||T.size===0)return!1;let l=t.get(d);if(!l||l.size===0)return!0;for(let g of T)if(!l.has(g))return!0;return!1}function u(d){let T=e.get(d);if(!T)return new Set;let l=t.get(d)||new Set,g=new Set;for(let p of T)l.has(p)||g.add(p);return g}return{has(d){let T=W(d);return c(T)},values(){let d=[];for(let[T]of e)c(T)&&d.push(Fe(T));return d},size(){let d=0;for(let[T]of e)c(T)&&d++;return d},add(d){let T=W(d),l=Ue(i,o++);e.has(T)||e.set(T,new Set),e.get(T).add(l),n++,E=Date.now()},remove(d){let T=W(d),l=e.get(T);if(!l||l.size===0)return;t.has(T)||t.set(T,new Set);let g=t.get(T);for(let p of l)g.add(p);n++,E=Date.now()},merge(d){let T=d.getState();this.applyState(T)},getState(){let d={};for(let[l,g]of e)d[l]=Array.from(g);let T={};for(let[l,g]of t)g.size>0&&(T[l]=Array.from(g));return{elements:d,tombstones:T,version:n,lastUpdated:E}},applyState(d){let T=!1;for(let[l,g]of Object.entries(d.elements)){e.has(l)||e.set(l,new Set);let p=e.get(l);for(let f of g)p.has(f)||(p.add(f),T=!0)}for(let[l,g]of Object.entries(d.tombstones)){t.has(l)||t.set(l,new Set);let p=t.get(l);for(let f of g)p.has(f)||(p.add(f),T=!0)}T&&(n=Math.max(n,d.version)+1,E=Date.now())},getNodeId(){return i},clear(){for(let[d,T]of e){t.has(d)||t.set(d,new Set);let l=t.get(d);for(let g of T)l.add(g)}n++,E=Date.now()}}}function P(i,e){let t=M(i);return t.applyState(e),t}var Y=R(()=>{"use strict";Z()});function H(i){let e={...xe,...i},{nodeId:t,enableDeltaTracking:n,maxDeltaHistory:E}=e,o=new Map,c=new Map,u=new Map,d=new Map,T=0,l=[],g=new Set,p={registers:new Set,gCounters:new Set,pnCounters:new Set,sets:new Set};function f(s,r,a){let _={key:s,type:r,operation:a,timestamp:Date.now(),nodeId:t};for(let Ie of g)try{Ie(_)}catch(Ae){console.error("[CRDTStore] Error in change listener:",Ae)}}function N(s,r){T++,n&&p[s].add(r)}function K(){if(!n||!(p.registers.size>0||p.gCounters.size>0||p.pnCounters.size>0||p.sets.size>0))return;let r={fromVersion:l.length>0?l[l.length-1].toVersion:0,toVersion:T,timestamp:Date.now(),nodeId:t};if(p.registers.size>0){r.registers={};for(let a of p.registers){let _=o.get(a);_&&(r.registers[a]=_.getState())}p.registers.clear()}if(p.gCounters.size>0){r.gCounters={};for(let a of p.gCounters){let _=c.get(a);_&&(r.gCounters[a]=_.getState())}p.gCounters.clear()}if(p.pnCounters.size>0){r.pnCounters={};for(let a of p.pnCounters){let _=u.get(a);_&&(r.pnCounters[a]=_.getState())}p.pnCounters.clear()}if(p.sets.size>0){r.sets={};for(let a of p.sets){let _=d.get(a);_&&(r.sets[a]=_.getState())}p.sets.clear()}for(l.push(r);l.length>E;)l.shift()}let h={getRegister(s){return o.has(s)||o.set(s,y(t)),o.get(s)},setRegister(s,r){h.getRegister(s).set(r),N("registers",s),f(s,"lww-register","set")},hasRegister(s){return o.has(s)},deleteRegister(s){let r=o.delete(s);return r&&N("registers",s),r},getGCounter(s){return c.has(s)||c.set(s,C(t)),c.get(s)},incrementGCounter(s,r){h.getGCounter(s).increment(r),N("gCounters",s),f(s,"g-counter","increment")},hasGCounter(s){return c.has(s)},deleteGCounter(s){let r=c.delete(s);return r&&N("gCounters",s),r},getCounter(s){return u.has(s)||u.set(s,F(t)),u.get(s)},incrementCounter(s,r){h.getCounter(s).increment(r),N("pnCounters",s),f(s,"pn-counter","increment")},decrementCounter(s,r){h.getCounter(s).decrement(r),N("pnCounters",s),f(s,"pn-counter","decrement")},hasCounter(s){return u.has(s)},deleteCounter(s){let r=u.delete(s);return r&&N("pnCounters",s),r},getSet(s){return d.has(s)||d.set(s,M(t)),d.get(s)},addToSet(s,r){h.getSet(s).add(r),N("sets",s),f(s,"or-set","add")},removeFromSet(s,r){h.getSet(s).remove(r),N("sets",s),f(s,"or-set","remove")},hasSet(s){return d.has(s)},deleteSet(s){let r=d.delete(s);return r&&N("sets",s),r},merge(s){let r=s.getState();h.applyState(r)},getState(){K();let s={version:T,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let[r,a]of o)s.registers[r]=a.getState();for(let[r,a]of c)s.gCounters[r]=a.getState();for(let[r,a]of u)s.pnCounters[r]=a.getState();for(let[r,a]of d)s.sets[r]=a.getState();return s},applyState(s){for(let[r,a]of Object.entries(s.registers))o.has(r)?o.get(r).applyState(a):o.set(r,X(t,a)),N("registers",r),f(r,"lww-register","merge");for(let[r,a]of Object.entries(s.gCounters))c.has(r)?c.get(r).applyState(a):c.set(r,w(t,a)),N("gCounters",r),f(r,"g-counter","merge");for(let[r,a]of Object.entries(s.pnCounters))u.has(r)?u.get(r).applyState(a):u.set(r,x(t,a)),N("pnCounters",r),f(r,"pn-counter","merge");for(let[r,a]of Object.entries(s.sets))d.has(r)?d.get(r).applyState(a):d.set(r,P(t,a)),N("sets",r),f(r,"or-set","merge");T=Math.max(T,s.version)+1},getDelta(s){if(K(),l.length===0)return s>=T,null;let r=l.filter(_=>_.toVersion>s);if(r.length===0)return null;let a={fromVersion:s,toVersion:T,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let _ of r)_.registers&&Object.assign(a.registers,_.registers),_.gCounters&&Object.assign(a.gCounters,_.gCounters),_.pnCounters&&Object.assign(a.pnCounters,_.pnCounters),_.sets&&Object.assign(a.sets,_.sets);return Object.keys(a.registers).length===0&&delete a.registers,Object.keys(a.gCounters).length===0&&delete a.gCounters,Object.keys(a.pnCounters).length===0&&delete a.pnCounters,Object.keys(a.sets).length===0&&delete a.sets,a},applyDelta(s){if(s.registers)for(let[r,a]of Object.entries(s.registers))o.has(r)?o.get(r).applyState(a):o.set(r,X(t,a)),N("registers",r),f(r,"lww-register","merge");if(s.gCounters)for(let[r,a]of Object.entries(s.gCounters))c.has(r)?c.get(r).applyState(a):c.set(r,w(t,a)),N("gCounters",r),f(r,"g-counter","merge");if(s.pnCounters)for(let[r,a]of Object.entries(s.pnCounters))u.has(r)?u.get(r).applyState(a):u.set(r,x(t,a)),N("pnCounters",r),f(r,"pn-counter","merge");if(s.sets)for(let[r,a]of Object.entries(s.sets))d.has(r)?d.get(r).applyState(a):d.set(r,P(t,a)),N("sets",r),f(r,"or-set","merge");T=Math.max(T,s.toVersion)+1},getVersion(){return T},getNodeId(){return t},on(s,r){if(s==="change")return g.add(r),()=>{g.delete(r)};throw new Error(`Unknown event type: ${s}`)},removeAllListeners(){g.clear()},keys(s){let r=[];return(!s||s==="lww-register")&&r.push(...Array.from(o.keys())),(!s||s==="g-counter")&&r.push(...Array.from(c.keys())),(!s||s==="pn-counter")&&r.push(...Array.from(u.keys())),(!s||s==="or-set")&&r.push(...Array.from(d.keys())),r},clear(){o.clear(),c.clear(),u.clear(),d.clear(),l.length=0,p.registers.clear(),p.gCounters.clear(),p.pnCounters.clear(),p.sets.clear(),T=0},getStats(){return{total:o.size+c.size+u.size+d.size,registers:o.size,gCounters:c.size,pnCounters:u.size,sets:d.size,version:T,nodeId:t,deltaHistorySize:l.length}}};return h}var xe,me=R(()=>{"use strict";j();U();B();Y();xe={nodeId:"default-node",enableDeltaTracking:!0,maxDeltaHistory:100}});var _e=R(()=>{"use strict"});var fe=R(()=>{"use strict";j();U();B();Y();me();_e()});var ke={};Oe(ke,{ALLOWED_TABLE_NAMES:()=>q,BinaryHeap:()=>ee,DEFAULT_UNIFIED_MEMORY_CONFIG:()=>he,UnifiedHnswIndex:()=>v,UnifiedMemoryManager:()=>A,clearProjectRootCache:()=>k,createHnswIndex:()=>te,findProjectRoot:()=>b,getDefaultDbPath:()=>Re,getResolvedDefaultConfig:()=>Le,getUnifiedMemory:()=>Ce,initializeUnifiedMemory:()=>Me,resetUnifiedMemory:()=>Pe,validateTableName:()=>I});import*as m from"fs";import*as Se from"os";import*as S from"path";function Re(){let i=b();return S.join(i,".agentic-qe","memory.db")}function Le(){return{...he,dbPath:Re()}}function Ce(i){return A.getInstance(i)}async function Me(i){let e=Ce(i);return await e.initialize(),e}function Pe(){A.resetInstance()}function Ge(){if(Ne)return;Ne=!0;let i=()=>{try{let e=A.instance;e&&e.close()}catch(e){console.debug("[UnifiedMemory] Cleanup error:",e instanceof Error?e.message:e)}};process.on("beforeExit",i),process.on("SIGINT",()=>{i(),process.exit(0)}),process.on("SIGTERM",()=>{i(),process.exit(0)})}var $,he,A,Ne,qe=R(()=>{ye();Z();be();ve();De();z();z();ne();ne();ge();fe();we();$=Q.create("unified-memory");he={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:O.MMAP_SIZE_BYTES,cacheSize:O.CACHE_SIZE_KB,busyTimeout:O.BUSY_TIMEOUT_MS,vectorDimensions:O.DEFAULT_VECTOR_DIMENSIONS};A=class i{static instance=null;static instancePromise=null;db=null;config;initialized=!1;vectorsLoaded=!1;initPromise=null;preparedStatements=new Map;vectorIndex=new v("qe-memory");crdtStore=null;constructor(e){let t=Le();if(this.config={...t,...e},!S.isAbsolute(this.config.dbPath)){let n=b();this.config.dbPath=S.join(n,this.config.dbPath)}}static getInstance(e){return i.instance||(i.instance=new i(e)),i.instance}static async getInstanceAsync(e){return i.instance?.initialized?i.instance:(i.instancePromise||(i.instancePromise=(async()=>{let t=i.getInstance(e);return await t.initialize(),t})()),i.instancePromise)}static resetInstance(){i.instance&&(i.instance.close(),i.instance=null),i.instancePromise=null,k()}async initialize(e){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize(e?.signal)),this.initPromise}async _doInitialize(e){if(!this.initialized){e?.throwIfAborted();try{let t=process.env.AQE_PROJECT_ROOT;if(t){let c=S.resolve(this.config.dbPath),u=S.resolve(t);!c.startsWith(u)&&!c.startsWith(Se.tmpdir())&&c.includes(".agentic-qe")&&(console.error(`[UnifiedMemory] WARNING: DB path "${this.config.dbPath}" points to a production .agentic-qe/ while AQE_PROJECT_ROOT="${t}". Redirecting to test-safe path.`),this.config.dbPath=S.join(t,".agentic-qe","memory.db"))}let n=S.dirname(this.config.dbPath);m.existsSync(n)||m.mkdirSync(n,{recursive:!0});let E=m.existsSync(this.config.dbPath),o=0;if(E)o=m.statSync(this.config.dbPath).size;else if(m.existsSync(n)){let c=this.findRecentBackups(n);if(c.length>0){let u=c[0];console.error(`[UnifiedMemory] CRITICAL: Database file missing but directory exists!
|
|
555
555
|
Expected: ${this.config.dbPath}
|
|
556
|
-
Found ${
|
|
557
|
-
Restoring from backup to prevent data loss...`),
|
|
556
|
+
Found ${c.length} backup(s), newest: ${u.path} (${(u.size/1024/1024).toFixed(1)}MB)
|
|
557
|
+
Restoring from backup to prevent data loss...`),m.copyFileSync(u.path,this.config.dbPath);for(let d of["-wal","-shm"]){let T=this.config.dbPath+d;m.existsSync(T)&&m.unlinkSync(T)}o=u.size}}if(e?.throwIfAborted(),this.db=J(this.config.dbPath,{walMode:this.config.walMode,busyTimeout:this.config.busyTimeout}),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.db.pragma("foreign_keys = ON"),e?.aborted){try{this.db.close()}catch{}this.db=null,e.throwIfAborted()}if(await this.runMigrations(),e?.throwIfAborted(),E&&o>1e6)try{let c=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get();if(c&&c.cnt===0){let u=m.statSync(this.config.dbPath).size;u<o*.1&&console.error(`[UnifiedMemory] CRITICAL: Possible data loss detected!
|
|
558
558
|
DB was ${(o/1024/1024).toFixed(1)}MB, now ${(u/1024/1024).toFixed(1)}MB with 0 patterns.
|
|
559
559
|
This looks like the DB was replaced with an empty schema.
|
|
560
|
-
Check backups in ${n} and restore manually.`)}}catch{}this.vectorsLoaded=!1,this.initialized=!0,console.log(`[UnifiedMemory] Initialized: ${this.config.dbPath}`),this.warnIfDuplicateDatabases()}catch(t){throw this.initPromise=null,t instanceof Error&&(t.name==="AbortError"||(e?.aborted??!1))?t:new Error(`Failed to initialize UnifiedMemoryManager: ${V(t)}`)}}}findRecentBackups(e){try{let n=
|
|
560
|
+
Check backups in ${n} and restore manually.`)}}catch{}this.vectorsLoaded=!1,this.initialized=!0,console.log(`[UnifiedMemory] Initialized: ${this.config.dbPath}`),this.warnIfDuplicateDatabases()}catch(t){throw this.initPromise=null,t instanceof Error&&(t.name==="AbortError"||(e?.aborted??!1))?t:new Error(`Failed to initialize UnifiedMemoryManager: ${V(t)}`)}}}findRecentBackups(e){try{let n=m.readdirSync(e).filter(o=>o.startsWith("memory")&&o.endsWith(".db")&&o!=="memory.db").map(o=>{let c=S.join(e,o),u=m.statSync(c);return{path:c,size:u.size,mtime:u.mtimeMs}}).filter(o=>o.size>1e6).sort((o,c)=>c.mtime-o.mtime),E=S.join(e,"backups");if(m.existsSync(E)){let o=m.readdirSync(E);for(let c of o)if(c.endsWith(".db")){let u=S.join(E,c),d=m.statSync(u);d.size>1e6&&n.push({path:u,size:d.size,mtime:d.mtimeMs})}n.sort((c,u)=>u.mtime-c.mtime)}return n}catch{return[]}}warnIfDuplicateDatabases(){try{let e=b(),t=S.resolve(this.config.dbPath),E=[S.join(e,".agentic-qe","memory.db"),S.join(e,"v3",".agentic-qe","memory.db")].map(o=>S.resolve(o)).filter(o=>o!==t&&m.existsSync(o));E.length>0&&console.warn(`[UnifiedMemory] WARNING: Duplicate database(s) detected!
|
|
561
561
|
Canonical: ${t}
|
|
562
|
-
Duplicates: ${
|
|
563
|
-
This can cause data splits. Remove duplicates or set AQE_PROJECT_ROOT.`)}catch(e){$.debug("Duplicate database check failed",{error:e instanceof Error?e.message:String(e)})}}columnExists(e,t){if(!this.db)return!1;try{let n=
|
|
562
|
+
Duplicates: ${E.join(", ")}
|
|
563
|
+
This can cause data splits. Remove duplicates or set AQE_PROJECT_ROOT.`)}catch(e){$.debug("Duplicate database check failed",{error:e instanceof Error?e.message:String(e)})}}columnExists(e,t){if(!this.db)return!1;try{let n=I(e);return this.db.prepare(`PRAGMA table_info(${n})`).all().some(o=>o.name===t)}catch(n){return $.debug("Column existence check failed",{table:e,column:t,error:n instanceof Error?n.message:String(n)}),!1}}handleV2SchemaIncompatibilities(){if(!this.db)return;let e=[{table:"goap_plans",requiredColumn:"status",columnDef:"TEXT DEFAULT 'pending'"},{table:"goap_actions",requiredColumn:"agent_type",columnDef:"TEXT DEFAULT 'unknown'"},{table:"concept_nodes",requiredColumn:"concept_type",columnDef:"TEXT DEFAULT 'general'"},{table:"concept_edges",requiredColumn:"edge_type",columnDef:"TEXT DEFAULT 'related'"},{table:"dream_insights",requiredColumn:"cycle_id",columnDef:"TEXT DEFAULT ''"},{table:"rl_q_values",requiredColumn:"algorithm",columnDef:"TEXT DEFAULT 'q-learning'"}];for(let{table:t,requiredColumn:n,columnDef:E}of e)if(this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(t)&&!this.columnExists(t,n)){let c=I(t);try{this.db.exec(`ALTER TABLE ${c} ADD COLUMN ${n} ${E}`),console.log(`[UnifiedMemory] Added column ${n} to ${t} (safe migration)`)}catch(u){console.log(`[UnifiedMemory] Column ${n} on ${t}: ${u instanceof Error?u.message:String(u)}`)}}}async runMigrations(){if(!this.db)throw new Error("Database not initialized");this.db.exec(se),this.handleV2SchemaIncompatibilities();let t=this.db.prepare("SELECT version FROM schema_version WHERE id = 1").get()?.version??0;t<D&&(console.log(`[UnifiedMemory] Migrating from v${t} to v${D}`),this.db.transaction(()=>{t<1&&this.db.exec(oe),t<2&&this.db.exec(ie),t<3&&(this.db.exec(ae),this.db.exec(ce),this.db.exec(Te)),t<4&&this.db.exec(Ee),t<5&&this.db.exec(de),t<6&&this.db.exec(G),t<7&&this.db.exec(ue),t<8&&this.db.exec(le),t<9&&(this.db.exec(`
|
|
564
564
|
CREATE VIRTUAL TABLE IF NOT EXISTS qe_patterns_fts USING fts5(
|
|
565
565
|
name, description, pattern_type, qe_domain,
|
|
566
566
|
content='qe_patterns',
|
|
@@ -589,23 +589,23 @@ import{d as k,f as we}from"./chunk-R5ONQAQL.js";import{b as C,d as Z}from"./chun
|
|
|
589
589
|
`)),this.db.prepare(`
|
|
590
590
|
INSERT OR REPLACE INTO schema_version (id, version, migrated_at)
|
|
591
591
|
VALUES (1, ?, datetime('now'))
|
|
592
|
-
`).run(D)})(),console.log("[UnifiedMemory] Migration complete"))}async loadVectorIndex(){if(this.vectorsLoaded)return;if(!this.db)throw new Error("Database not initialized");this.vectorIndex.clear();let e=this.db.prepare("SELECT id, embedding, dimensions FROM vectors").all();for(let t of e){let n=this.bufferToFloatArray(t.embedding,t.dimensions);this.vectorIndex.add(t.id,n)}this.vectorsLoaded=!0,console.log(`[UnifiedMemory] Loaded ${e.length} vectors into vector index (ruvector flat)`)}async kvSet(e,t,n="default",
|
|
592
|
+
`).run(D)})(),console.log("[UnifiedMemory] Migration complete"))}async loadVectorIndex(){if(this.vectorsLoaded)return;if(!this.db)throw new Error("Database not initialized");this.vectorIndex.clear();let e=this.db.prepare("SELECT id, embedding, dimensions FROM vectors").all();for(let t of e){let n=this.bufferToFloatArray(t.embedding,t.dimensions);this.vectorIndex.add(t.id,n)}this.vectorsLoaded=!0,console.log(`[UnifiedMemory] Loaded ${e.length} vectors into vector index (ruvector flat)`)}async kvSet(e,t,n="default",E){this.ensureInitialized();let o=E?Date.now()+E*1e3:null,c=JSON.stringify(t);this.db.prepare(`
|
|
593
593
|
INSERT OR REPLACE INTO kv_store (key, namespace, value, expires_at)
|
|
594
594
|
VALUES (?, ?, ?, ?)
|
|
595
|
-
`).run(e,n,
|
|
595
|
+
`).run(e,n,c,o)}async kvGet(e,t="default"){this.ensureInitialized();let n=this.db.prepare(`
|
|
596
596
|
SELECT value, expires_at FROM kv_store
|
|
597
597
|
WHERE key = ? AND namespace = ?
|
|
598
|
-
`).get(e,t);if(n){if(n.expires_at&&Date.now()>n.expires_at){this.db.prepare("DELETE FROM kv_store WHERE key = ? AND namespace = ?").run(e,t);return}return
|
|
598
|
+
`).get(e,t);if(n){if(n.expires_at&&Date.now()>n.expires_at){this.db.prepare("DELETE FROM kv_store WHERE key = ? AND namespace = ?").run(e,t);return}return L(n.value)}}async kvDelete(e,t="default"){return this.ensureInitialized(),this.db.prepare("DELETE FROM kv_store WHERE key = ? AND namespace = ?").run(e,t).changes>0}async kvExists(e,t="default"){return this.ensureInitialized(),this.db.prepare(`
|
|
599
599
|
SELECT 1 FROM kv_store
|
|
600
600
|
WHERE key = ? AND namespace = ? AND (expires_at IS NULL OR expires_at > ?)
|
|
601
|
-
`).get(e,t,Date.now())!==void 0}async kvSearch(e,t="default",n=100){this.ensureInitialized();let
|
|
601
|
+
`).get(e,t,Date.now())!==void 0}async kvSearch(e,t="default",n=100){this.ensureInitialized();let E=e.replace(/\*/g,"%").replace(/\?/g,"_");return this.db.prepare(`
|
|
602
602
|
SELECT key FROM kv_store
|
|
603
603
|
WHERE namespace = ? AND key LIKE ?
|
|
604
604
|
AND (expires_at IS NULL OR expires_at > ?)
|
|
605
605
|
LIMIT ?
|
|
606
|
-
`).all(t,
|
|
606
|
+
`).all(t,E,Date.now(),n).map(c=>c.key)}async kvCleanupExpired(){return this.ensureInitialized(),this.db.prepare("DELETE FROM kv_store WHERE expires_at IS NOT NULL AND expires_at < ?").run(Date.now()).changes}async vectorStore(e,t,n="default",E){this.ensureInitialized();let o=this.floatArrayToBuffer(t),c=E?JSON.stringify(E):null;this.db.prepare(`
|
|
607
607
|
INSERT OR REPLACE INTO vectors (id, namespace, embedding, dimensions, metadata, updated_at)
|
|
608
608
|
VALUES (?, ?, ?, ?, ?, datetime('now'))
|
|
609
|
-
`).run(e,n,o,t.length,
|
|
609
|
+
`).run(e,n,o,t.length,c),this.vectorIndex.add(e,t)}async vectorGet(e){this.ensureInitialized();let t=this.db.prepare(`
|
|
610
610
|
SELECT embedding, dimensions, metadata FROM vectors WHERE id = ?
|
|
611
|
-
`).get(e);if(t)return{embedding:this.bufferToFloatArray(t.embedding,t.dimensions),metadata:t.metadata?
|
|
611
|
+
`).get(e);if(t)return{embedding:this.bufferToFloatArray(t.embedding,t.dimensions),metadata:t.metadata?L(t.metadata):void 0}}async vectorDelete(e){this.ensureInitialized();let t=this.db.prepare("DELETE FROM vectors WHERE id = ?").run(e);return this.vectorIndex.remove(e),t.changes>0}async vectorSearch(e,t=10,n){this.ensureInitialized(),this.vectorsLoaded||await this.loadVectorIndex();let E=this.vectorIndex.search(e,t*2);if(E.length===0)return[];let o=E.map(T=>T.id),c=o.map(()=>"?").join(","),u=this.db.prepare(`SELECT id, namespace, metadata FROM vectors WHERE id IN (${c})`).all(...o),d=new Map(u.map(T=>[T.id,T]));if(n){let T=[];for(let l of E){let g=d.get(l.id);if(g&&g.namespace===n&&(T.push({id:l.id,score:l.score,metadata:g.metadata?L(g.metadata):void 0}),T.length>=t))break}return T}return E.slice(0,t).map(T=>{let l=d.get(T.id);return{id:T.id,score:T.score,metadata:l?.metadata?L(l.metadata):void 0}})}async vectorCount(e){return this.ensureInitialized(),e?this.db.prepare("SELECT COUNT(*) as count FROM vectors WHERE namespace = ?").get(e).count:this.db.prepare("SELECT COUNT(*) as count FROM vectors").get().count}queryCount(e){this.ensureInitialized();let t=I(e);return this.db.prepare(`SELECT COUNT(*) as c FROM ${t}`).get().c}initializeCRDT(e){if(this.crdtStore){console.warn("[UnifiedMemory] CRDT store already initialized");return}this.crdtStore=H({nodeId:e}),console.log(`[UnifiedMemory] CRDT store initialized for node: ${e}`)}getCRDTStore(){return this.crdtStore}isCRDTInitialized(){return this.crdtStore!==null}async crdtSet(e,t,n="crdt"){this.ensureInitialized(),this.crdtStore&&this.crdtStore.setRegister(e,t),await this.kvSet(e,t,n)}async crdtGet(e,t="crdt"){if(this.crdtStore){let n=this.crdtStore.getRegister(e);if(n)return n.get()}return this.kvGet(e,t)}crdtIncrement(e,t=1){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");let n=this.crdtStore.getCounter(e);n||(this.crdtStore.incrementCounter(e,0),n=this.crdtStore.getCounter(e));for(let E=0;E<t;E++)this.crdtStore.incrementCounter(e)}crdtGetCounter(e){return this.crdtStore?this.crdtStore.getCounter(e)?.get()??0:0}crdtAddToSet(e,t){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.addToSet(e,t)}crdtRemoveFromSet(e,t){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.removeFromSet(e,t)}crdtGetSet(e){if(!this.crdtStore)return new Set;let t=this.crdtStore.getSet(e);return new Set(t.values())}crdtGetState(){return this.crdtStore?this.crdtStore.getState():null}crdtGetDelta(e){return this.crdtStore?this.crdtStore.getDelta(e??0):null}crdtMerge(e){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.applyState(e)}crdtApplyDelta(e){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.applyDelta(e)}async crdtPersist(){if(!this.crdtStore)return;let e=this.crdtStore.getState();await this.kvSet("__crdt_state__",e,"crdt-internal")}async crdtRestore(){if(!this.crdtStore)return!1;let e=await this.kvGet("__crdt_state__","crdt-internal");return e?(this.crdtStore.applyState(e),!0):!1}getDatabase(){if(!this.db||!this.initialized)throw new Error("UnifiedMemoryManager not initialized");return this.db}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(e,t){if(!this.db)throw new Error("Database not initialized");let n=this.preparedStatements.get(e);return n||(n=this.db.prepare(t),this.preparedStatements.set(e,n)),n}transaction(e){if(!this.db)throw new Error("Database not initialized");return this.db.transaction(e)()}getStats(){if(!this.db)throw new Error("Database not initialized");let e=pe.map(E=>{try{let o=this.db.prepare(`SELECT COUNT(*) as count FROM ${E}`).get();return{name:E,rowCount:o.count}}catch(o){return $.debug("Table row count query failed",{table:E,error:o instanceof Error?o.message:String(o)}),{name:E,rowCount:0}}}),t=0,n=0;try{m.existsSync(this.config.dbPath)&&(t=m.statSync(this.config.dbPath).size);let E=this.config.dbPath+"-wal";m.existsSync(E)&&(n=m.statSync(E).size)}catch(E){console.debug("[UnifiedMemory] File stat error:",E instanceof Error?E.message:E)}return{tables:e,fileSize:t,walSize:n,vectorIndexSize:this.vectorIndex.size()}}vacuum(){if(!this.db)throw new Error("Database not initialized");this.db.exec("VACUUM")}checkpoint(){if(!this.db)throw new Error("Database not initialized");this.db.pragma("wal_checkpoint(TRUNCATE)")}close(){this.db&&(this.preparedStatements.clear(),this.vectorIndex.clear(),this.db.close(),this.db=null,this.initialized=!1,console.log("[UnifiedMemory] Database closed"))}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("UnifiedMemoryManager not initialized. Call initialize() first.")}floatArrayToBuffer(e){let t=Buffer.alloc(e.length*4);for(let n=0;n<e.length;n++)t.writeFloatLE(e[n],n*4);return t}bufferToFloatArray(e,t){let n=new Float32Array(e.buffer,e.byteOffset,t);return Array.from(n)}};Ne=!1;Ge()});export{q as a,I as b,ze as c,z as d,Re as e,he as f,Le as g,A as h,Ce as i,Me as j,Pe as k,ke as l,qe as m};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.4");process.exit(0)}
|
|
2
2
|
import*as h from"fs";import*as M from"path";var S=["coverage/coverage-final.json","coverage/coverage-summary.json",".coverage/coverage-final.json"];function x(s){for(let v of S){let i=M.join(s,v);if(h.existsSync(i))try{let n=JSON.parse(h.readFileSync(i,"utf-8"));if(n.total&&n.total.lines)return L(n,s);let o=new Map;for(let[r,C]of Object.entries(n)){let c=C,g=Object.keys(c.s),u=g.filter(a=>c.s[a]>0).length,b=Object.keys(c.b),p=0,m=0;for(let a of b)for(let y of c.b[a])p++,y>0&&m++;let e=Object.keys(c.f),t=e.filter(a=>c.f[a]>0).length,f=new Set,d=new Set;for(let a of g){let y=c.statementMap[a];for(let F=y.start.line;F<=y.end.line;F++)d.add(F),c.s[a]>0&&f.add(F)}let l=[...d].filter(a=>!f.has(a)).sort((a,y)=>a-y);o.set(r,{path:r,lines:{covered:f.size,total:d.size},branches:{covered:m,total:p},functions:{covered:t,total:e.length},statements:{covered:u,total:g.length},uncoveredLines:l,uncoveredBranches:l.slice(0,Math.floor(l.length/2))})}return o.size>0?o:null}catch{continue}}return null}function L(s,v){let i=new Map;for(let[n,o]of Object.entries(s)){if(n==="total")continue;let r=o;i.set(n,{path:n,lines:{covered:r.lines.covered,total:r.lines.total},branches:{covered:r.branches.covered,total:r.branches.total},functions:{covered:r.functions.covered,total:r.functions.total},statements:{covered:r.statements.covered,total:r.statements.total},uncoveredLines:[],uncoveredBranches:[]})}return i.size>0?i:null}function B(s,v){let n=v.split(`
|
|
3
3
|
`).length,r=[s.replace(".ts",".test.ts").replace("/src/","/tests/"),s.replace(".ts",".spec.ts").replace("/src/","/tests/"),s.replace(".ts",".test.ts"),s.replace("/src/","/test/").replace(".ts",".test.ts")].some(d=>h.existsSync(d)),C=(v.match(/\bexport\b/g)||[]).length,c=(v.match(/\b(function|=>)\b/g)||[]).length,g=(v.match(/\b(if|switch|case|\?\?|\|\|)\b/g)||[]).length,u;if(r){let d=Math.min(g*.005,.15),l=Math.min(n*1e-4,.1);u=.85-d-l}else u=.2+(C>5?.1:0);u=Math.max(.05,Math.min(.95,u));let b=Math.floor(n*u),p=Math.max(c,1),m=Math.max(g,1),e=Math.floor(b*.7),t=Math.floor(p*u*.9),f=Array.from({length:n-b},(d,l)=>l+b+1);return{path:s,lines:{covered:b,total:n},branches:{covered:Math.min(e,m),total:m},functions:{covered:Math.min(t,p),total:p},statements:{covered:b,total:n},uncoveredLines:f,uncoveredBranches:f.slice(0,Math.floor(f.length/2))}}function j(s,v){let i=v||process.cwd(),n=x(i),o=[],r=!1;if(n&&n.size>0){r=!0;for(let e of s){let t=M.resolve(e),f=n.get(t)||n.get(e)||n.get(M.relative(i,t));if(f)o.push({...f,path:e});else{let l=(h.existsSync(e)?h.readFileSync(e,"utf-8"):"").split(`
|
|
4
4
|
`).length;o.push({path:e,lines:{covered:0,total:l},branches:{covered:0,total:1},functions:{covered:0,total:1},statements:{covered:0,total:l},uncoveredLines:Array.from({length:l},(a,y)=>y+1),uncoveredBranches:[]})}}}else for(let e of s){let t=h.existsSync(e)?h.readFileSync(e,"utf-8"):"";o.push(B(e,t))}let C=o.reduce((e,t)=>e+t.lines.total,0),c=o.reduce((e,t)=>e+t.lines.covered,0),g=o.reduce((e,t)=>e+t.branches.total,0),u=o.reduce((e,t)=>e+t.branches.covered,0),b=o.reduce((e,t)=>e+t.functions.total,0),p=o.reduce((e,t)=>e+t.functions.covered,0),m=(e,t)=>t>0?Math.round(e/t*100):0;return{files:o,summary:{line:m(c,C),branch:m(u,g),function:m(p,b),statement:m(c,C),files:o.length},instrumented:r}}export{j as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.4");process.exit(0)}
|
|
2
2
|
var s={"test-generation":/test|spec|describe|it\(|expect|assert|mock|stub|fixture|tdd|bdd/i,"test-execution":/run|execute|parallel|retry|flaky|timeout|worker|orchestrat/i,"coverage-analysis":/coverage|branch|line|uncovered|gap|untested|percentage|sublinear/i,"quality-assessment":/quality|gate|deploy|readiness|metric|threshold|sla|score/i,"defect-intelligence":/defect|bug|predict|root.?cause|regression|failure|incident/i,"requirements-validation":/requirement|bdd|gherkin|testabil|accept|criteri|scenario/i,"code-intelligence":/semantic|knowledge|graph|ast|symbol|reference|impact|depend/i,"security-compliance":/vuln|cve|owasp|xss|sqli|injection|csrf|auth|secret|compliance|sast|dast/i,"contract-testing":/contract|pact|openapi|swagger|graphql|schema|endpoint|api/i,"visual-accessibility":/screenshot|visual|snapshot|pixel|percy|a11y|aria|wcag|screen.?reader|accessible|contrast/i,"chaos-resilience":/chaos|resilience|fault|inject|blast|recover|latency|failure|stress|load/i,"learning-optimization":/learn|pattern|optim|neural|embedding|vector|memory|adapt|train/i};function l(e){for(let[t,a]of Object.entries(s))if(a.test(e))return t;return null}function m(e){let t=[];for(let[a,n]of Object.entries(s))n.test(e)&&t.push(a);return t}function u(e){return e}function d(e){let t=Math.min(e.usageCount/100,1);return e.confidence*.3+t*.2+e.successRate*.5}var c=3;function p(e,t,a=.4){let n=e.tier==="short-term"&&e.successfulUses>=c,r=e.successRate>=.7&&e.confidence>=.6,i=t===void 0||t<a,o;return n?r?i||(o="coherence_violation"):o="low_quality":o="insufficient_usage",{meetsUsageCriteria:n,meetsQualityCriteria:r,meetsCoherenceCriteria:i,blockReason:o}}function y(e){let t=[];if(e.id||t.push("Pattern ID is required"),e.patternType||t.push("Pattern type is required"),e.qeDomain||t.push("QE domain is required"),e.name||t.push("Pattern name is required"),e.template?.content||t.push("Template content is required"),e.confidence!==void 0&&(e.confidence<0||e.confidence>1)&&t.push("Confidence must be between 0 and 1"),e.successRate!==void 0&&(e.successRate<0||e.successRate>1)&&t.push("Success rate must be between 0 and 1"),e.template?.variables){let a=new Set;for(let n of e.template.variables)a.has(n.name)&&t.push(`Duplicate variable name: ${n.name}`),a.add(n.name),e.template.content.includes(`{{${n.name}}}`)||t.push(`Variable ${n.name} not referenced in template`)}return{valid:t.length===0,errors:t}}function f(e,t){let a=e.content;for(let n of e.variables){let r=t[n.name]??n.defaultValue;if(n.required&&r===void 0)throw new Error(`Required variable ${n.name} not provided`);if(r!==void 0){let i=`{{${n.name}}}`,o=typeof r=="object"?JSON.stringify(r):String(r);a=a.split(i).join(o)}}return a}var g=Object.keys(s);export{l as a,m as b,u as c,d,c as e,p as f,y as g,f as h,g as i};
|
|
@@ -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.10.
|
|
2
|
-
import{a as ne}from"./chunk-
|
|
3
|
-
`)}var gt=(function(n){ut(e,n);function e(t,r,i,s,a){var c=this.constructor,u=n.call(this,Le(t,{name:r,index:i,operation:s,tree:a}))||this;return u.name=r,u.index=i,u.operation=s,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=Le(t,{name:r,index:i,operation:s,tree:a}),u}return e})(Error);S.PatchError=gt});var he=J(p=>{Object.defineProperty(p,"__esModule",{value:!0});var b=V();p.JsonPatchError=b.PatchError;p.deepClone=b._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=Y(t,this.path);r&&(r=b._deepClone(r));var i=I(t,{op:"remove",path:this.from}).removed;return I(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Y(t,this.from);return I(t,{op:"add",path:this.path,value:b._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},yt={add:function(n,e,t){return b.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function Y(n,e){if(e=="")return n;var t={op:"_get",path:e};return I(n,t),t.value}p.getValueByPointer=Y;function I(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):K(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=Y(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new p.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 p.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=b._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,h=u.length,f=void 0,d=void 0,m=void 0;for(typeof t=="function"?m=t:m=K;;){if(d=u[l],d&&d.indexOf("~")!=-1&&(d=b.unescapePathComponent(d)),i&&(d=="__proto__"||d=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&f===void 0&&(o[d]===void 0?f=u.slice(0,l).join("/"):l==h-1&&(f=e.path),f!==void 0&&m(e,0,n,f)),l++,Array.isArray(o)){if(d==="-")d=o.length;else{if(t&&!b.isInteger(d))throw new p.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);b.isInteger(d)&&(d=~~d)}if(l>=h){if(t&&e.op==="add"&&d>o.length)throw new p.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=yt[e.op].call(e,o,d,n);if(a.test===!1)throw new p.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=h){var a=L[e.op].call(e,o,d,n);if(a.test===!1)throw new p.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[d],t&&l<h&&(!o||typeof o!="object"))throw new p.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}p.applyOperation=I;function Ue(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new p.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=b._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=I(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}p.applyPatch=Ue;function vt(n,e,t){var r=I(n,e);if(r.test===!1)throw new p.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}p.applyReducer=vt;function K(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new p.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new p.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 p.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 p.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 p.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")&&b.hasUndefined(n.value))throw new p.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 p.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 p.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=qe([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new p.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new p.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}p.validator=K;function qe(n,e,t){try{if(!Array.isArray(n))throw new p.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ue(b._deepClone(e),b._deepClone(n),t||!0);else{t=t||K;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof p.JsonPatchError)return i;throw i}}p.validate=qe;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!z(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],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}p._areEquals=z});var Qe=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var P=V(),wt=he(),fe=new WeakMap,Pt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),St=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function bt(n){return fe.get(n)}function Et(n,e){return n.observers.get(e)}function At(n,e){n.observers.delete(e.callback)}function Rt(n,e){e.unobserve()}k.unobserve=Rt;function Tt(n,e){var t=[],r,i=bt(n);if(!i)i=new Pt(n),fe.set(n,i);else{var s=Et(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=P._deepClone(n),e){r.callback=e,r.next=null;var a=function(){de(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(){de(r),clearTimeout(r.next),At(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 St(e,r)),r}k.observe=Tt;function de(n,e){e===void 0&&(e=!1);var t=fe.get(n.object);me(t.value,n.object,n.patches,"",e),n.patches.length&&wt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=de;function me(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=P._objectKeys(e),a=P._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],h=n[l];if(P.hasOwnProperty(e,l)&&!(e[l]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var f=e[l];typeof h=="object"&&h!=null&&typeof f=="object"&&f!=null&&Array.isArray(h)===Array.isArray(f)?me(h,f,t,r+"/"+P.escapePathComponent(l),i):h!==f&&(c=!0,i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"replace",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(f)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"remove",path:r+"/"+P.escapePathComponent(l)}),u=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&s.length==a.length))for(var o=0;o<s.length;o++){var l=s[o];!P.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(e[l])})}}}function xt(n,e,t){t===void 0&&(t=!1);var r=[];return me(n,e,r,"",t),r}k.compare=xt});var ze=J(O=>{var Ct=he();Object.assign(O,Ct);var Dt=Qe();Object.assign(O,Dt);var Z=V();O.JsonPatchError=Z.PatchError;O.deepClone=Z._deepClone;O.escapePathComponent=Z.escapePathComponent;O.unescapePathComponent=Z.unescapePathComponent});Te();var Q=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}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=y(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-CYESP7NG.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")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${y(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,y(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,y(r))}return v(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:B({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?v(i):w(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)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,i*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.score);s.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",y(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),u=e,o=Math.sqrt(u.reduce((l,h)=>l+h*h,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let h=this.sqliteStore.getPattern(l.id),f=h?.embedding;if(!f||f.length!==u.length)continue;let d=0,m=0;for(let A=0;A<u.length;A++)d+=u[A]*f[A],m+=f[A]*f[A];if(m=Math.sqrt(m),m===0)continue;let g=d/(o*m),E=this.calculateReuseInfo(h,g);s.push({pattern:h,score:g,matchType:"vector",similarity:g,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:i*2}),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);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),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch{}s.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,v(s.slice(0,i))}async recordUsage(e,t){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t),v(void 0)}catch(r){return w(new Error(`recordUsage failed: ${y(r)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),v(void 0)}catch(t){return w(new Error(`promote failed: ${y(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,y(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${y(t)}`))}return v(void 0)}async getStats(){let e=this.adapter?.status(),t=e?.totalVectors??0;if(t===0&&this.sqliteStore)try{t=this.sqliteStore.getStats().totalPatterns}catch{}return{totalPatterns:t,byTier:{shortTerm:0,longTerm:0},byDomain:{},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:",y(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}}};De();Te();F();function nt(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 it(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=nt(n,e.field);return it(t,e.operator,e.value)}default:return!0}}function Fe(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var Oe=1e4,_e=2166136261;function Ne(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 ae=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;ae[n]=e}var Ie="0123456789abcdef";function st(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Ie[i>>4]+Ie[i&15]}return t}function at(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 ot(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,u=1<<a;for(let o=0;o<n.length;o++)n[o][i]&u&&c++;c>=r&&(s|=u)}t[i]=s}return t}function ct(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+=ae[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function lt(n,e,t){return 1-ct(n,e,t)}var ie=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,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=Ne(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=at(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 ot([r,i])}similarity(e,t){return lt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ne(e),i=0;for(;i<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-i);for(let u=0;u<c;u++)t[i++]=a>>>u*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},se=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,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=Ne(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:st(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+=ae[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 ne(e),s=0;for(;s<t;){let c=i.next(),u=t-s,o=u<4?u: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 He(n){return new se(n)}function Me(n){return q()?new ie(n):null}var $=Ke(ze(),1),Ft=`
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.4");process.exit(0)}
|
|
2
|
+
import{a as ne}from"./chunk-KGPAWNNR.js";import{d as B,e as j,f as re,g as W}from"./chunk-OIFJH7TF.js";import{g as rt,h as nt}from"./chunk-MQIAN57O.js";import{b as xe,c as et}from"./chunk-U27GVYXA.js";import{a as Ce,d as De,e as tt,f as Fe}from"./chunk-KWZEBHAP.js";import{b as v,c as w}from"./chunk-UFKVKNAA.js";import{a as y,b as Ae,c as Te}from"./chunk-2B6ETC7C.js";import{i as C}from"./chunk-PISW5HUX.js";import{B as q,D as H,G as te,P as M,S as F,b as D}from"./chunk-D7IWGQTW.js";import{a as Ee,d as J,f as Ze,g as Re}from"./chunk-SVILIQQQ.js";var V=J(S=>{var dt=S&&S.__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(S,"__esModule",{value:!0});var ft=Object.prototype.hasOwnProperty;function le(n,e){return ft.call(n,e)}S.hasOwnProperty=le;function Ue(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)le(n,i)&&r.push(i);return r}S._objectKeys=Ue;function pt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}S._deepClone=pt;function mt(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}S.isInteger=mt;function oe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}S.escapePathComponent=oe;function gt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}S.unescapePathComponent=gt;function ue(n,e){var t;for(var r in n)if(le(n,r)){if(n[r]===e)return oe(r)+"/";if(typeof n[r]=="object"&&(t=ue(n[r],e),t!=""))return oe(r)+"/"+t}return""}S._getPathRecursive=ue;function yt(n,e){if(n===e)return"/";var t=ue(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}S.getPath=yt;function ce(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(ce(n[e]))return!0}else if(typeof n=="object"){for(var r=Ue(n),i=r.length,s=0;s<i;s++)if(ce(n[r[s]]))return!0}}return!1}S.hasUndefined=ce;function ke(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 vt=(function(n){dt(e,n);function e(t,r,i,s,a){var c=this.constructor,u=n.call(this,ke(t,{name:r,index:i,operation:s,tree:a}))||this;return u.name=r,u.index=i,u.operation=s,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=ke(t,{name:r,index:i,operation:s,tree:a}),u}return e})(Error);S.PatchError=vt});var he=J(g=>{Object.defineProperty(g,"__esModule",{value:!0});var b=V();g.JsonPatchError=b.PatchError;g.deepClone=b._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=Y(t,this.path);r&&(r=b._deepClone(r));var i=O(t,{op:"remove",path:this.from}).removed;return O(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Y(t,this.from);return O(t,{op:"add",path:this.path,value:b._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},wt={add:function(n,e,t){return b.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function Y(n,e){if(e=="")return n;var t={op:"_get",path:e};return O(n,t),t.value}g.getValueByPointer=Y;function O(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):K(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=Y(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",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=b._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,h=u.length,d=void 0,f=void 0,p=void 0;for(typeof t=="function"?p=t:p=K;;){if(f=u[l],f&&f.indexOf("~")!=-1&&(f=b.unescapePathComponent(f)),i&&(f=="__proto__"||f=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&d===void 0&&(o[f]===void 0?d=u.slice(0,l).join("/"):l==h-1&&(d=e.path),d!==void 0&&p(e,0,n,d)),l++,Array.isArray(o)){if(f==="-")f=o.length;else{if(t&&!b.isInteger(f))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);b.isInteger(f)&&(f=~~f)}if(l>=h){if(t&&e.op==="add"&&f>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=wt[e.op].call(e,o,f,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=h){var a=L[e.op].call(e,o,f,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[f],t&&l<h&&(!o||typeof o!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}g.applyOperation=O;function qe(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=b._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=O(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}g.applyPatch=qe;function Pt(n,e,t){var r=O(n,e);if(r.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}g.applyReducer=Pt;function K(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new g.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new g.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new g.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new g.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&b.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=Qe([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=K;function Qe(n,e,t){try{if(!Array.isArray(n))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)qe(b._deepClone(e),b._deepClone(n),t||!0);else{t=t||K;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=Qe;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!z(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],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}g._areEquals=z});var ze=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var P=V(),St=he(),fe=new WeakMap,bt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Et=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function Rt(n){return fe.get(n)}function At(n,e){return n.observers.get(e)}function Tt(n,e){n.observers.delete(e.callback)}function xt(n,e){e.unobserve()}k.unobserve=xt;function Ct(n,e){var t=[],r,i=Rt(n);if(!i)i=new bt(n),fe.set(n,i);else{var s=At(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=P._deepClone(n),e){r.callback=e,r.next=null;var a=function(){de(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(){de(r),clearTimeout(r.next),Tt(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 Et(e,r)),r}k.observe=Ct;function de(n,e){e===void 0&&(e=!1);var t=fe.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&St.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=de;function pe(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=P._objectKeys(e),a=P._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],h=n[l];if(P.hasOwnProperty(e,l)&&!(e[l]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var d=e[l];typeof h=="object"&&h!=null&&typeof d=="object"&&d!=null&&Array.isArray(h)===Array.isArray(d)?pe(h,d,t,r+"/"+P.escapePathComponent(l),i):h!==d&&(c=!0,i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"replace",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(d)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"remove",path:r+"/"+P.escapePathComponent(l)}),u=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&s.length==a.length))for(var o=0;o<s.length;o++){var l=s[o];!P.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(e[l])})}}}function Dt(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=Dt});var $e=J(I=>{var Ft=he();Object.assign(I,Ft);var Ot=ze();Object.assign(I,Ot);var Z=V();I.JsonPatchError=Z.PatchError;I.deepClone=Z._deepClone;I.escapePathComponent=Z.escapePathComponent;I.unescapePathComponent=Z.unescapePathComponent});et();Te();var Q=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}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=y(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-SWNBO257.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")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${y(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=W(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,y(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,y(r))}return v(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:B({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?v(i):w(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)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,i*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.score);s.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",y(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),u=e,o=Math.sqrt(u.reduce((l,h)=>l+h*h,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let h=this.sqliteStore.getPattern(l.id),d=h?.embedding;if(!d||d.length!==u.length)continue;let f=0,p=0;for(let R=0;R<u.length;R++)f+=u[R]*d[R],p+=d[R]*d[R];if(p=Math.sqrt(p),p===0)continue;let m=f/(o*p),E=this.calculateReuseInfo(h,m);s.push({pattern:h,score:m,matchType:"vector",similarity:m,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:i*2}),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);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),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch{}s.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,v(s.slice(0,i))}async recordUsage(e,t){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t),v(void 0)}catch(r){return w(new Error(`recordUsage failed: ${y(r)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),v(void 0)}catch(t){return w(new Error(`promote failed: ${y(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,y(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${y(t)}`))}return v(void 0)}async getStats(){let e=this.adapter?.status(),t=e?.totalVectors??0;if(t===0&&this.sqliteStore)try{t=this.sqliteStore.getStats().totalPatterns}catch{}return{totalPatterns:t,byTier:{shortTerm:0,longTerm:0},byDomain:{},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>=j&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",y(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}}};Fe();Te();F();function st(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 at(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=st(n,e.field);return at(t,e.operator,e.value)}default:return!0}}function Oe(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var _e=1e4,Ne=2166136261;function He(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 ae=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;ae[n]=e}var Ie="0123456789abcdef";function ot(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Ie[i>>4]+Ie[i&15]}return t}function ct(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 lt(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,u=1<<a;for(let o=0;o<n.length;o++)n[o][i]&u&&c++;c>=r&&(s|=u)}t[i]=s}return t}function ut(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+=ae[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function ht(n,e,t){return 1-ut(n,e,t)}var ie=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??_e,this.baseSeed=e?.seed??Ne,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=He(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=ct(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 lt([r,i])}similarity(e,t){return ht(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ne(e),i=0;for(;i<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-i);for(let u=0;u<c;u++)t[i++]=a>>>u*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},se=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??_e,this.baseSeed=e?.seed??Ne,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=He(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:ot(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+=ae[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 ne(e),s=0;for(;s<t;){let c=i.next(),u=t-s,o=u<4?u: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 Me(n){return new se(n)}function Le(n){return q()?new ie(n):null}var $=Ze($e(),1),It=`
|
|
4
4
|
CREATE TABLE IF NOT EXISTS pattern_deltas (
|
|
5
5
|
id TEXT PRIMARY KEY,
|
|
6
6
|
pattern_id TEXT NOT NULL,
|
|
@@ -15,7 +15,7 @@ import{a as ne}from"./chunk-UDV4YB42.js";import{d as B,e as W,f as re,g as j}fro
|
|
|
15
15
|
ON pattern_deltas (pattern_id, version);
|
|
16
16
|
CREATE INDEX IF NOT EXISTS idx_pattern_deltas_timestamp
|
|
17
17
|
ON pattern_deltas (timestamp);
|
|
18
|
-
`;function
|
|
18
|
+
`;function Je(n,e){let t=$.compare(n,e),r=$.compare(e,n);return{forward:t,reverse:r}}function _t(n,e){let t=JSON.parse(JSON.stringify(n));return $.applyPatch(t,e).newDocument}function Be(n){return{id:n.id,patternId:n.pattern_id,version:n.version,timestamp:n.timestamp,type:n.type,patch:JSON.parse(n.patch),reversePatch:JSON.parse(n.reverse_patch),metadata:n.metadata?JSON.parse(n.metadata):void 0}}var ee=class{db;config;prepared=new Map;initialized=!1;constructor(e,t){this.db=e,this.config={maxVersionsPerPattern:t?.maxVersionsPerPattern??100,compressDeltas:t?.compressDeltas??!1}}initialize(){this.initialized||(this.db.exec(It),this.prepareStatements(),this.initialized=!0)}prepareStatements(){this.prepared.set("insert",this.db.prepare(`
|
|
19
19
|
INSERT INTO pattern_deltas (id, pattern_id, version, timestamp, type, patch, reverse_patch, metadata)
|
|
20
20
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
21
21
|
`)),this.prepared.set("getHistory",this.db.prepare(`
|
|
@@ -40,13 +40,13 @@ import{a as ne}from"./chunk-UDV4YB42.js";import{d as B,e as W,f as re,g as j}fro
|
|
|
40
40
|
ORDER BY version ASC
|
|
41
41
|
LIMIT ?
|
|
42
42
|
)
|
|
43
|
-
`))}ensureInitialized(){if(!this.initialized)throw new Error("DeltaTracker not initialized. Call initialize() first.")}createGenesis(e,t,r){this.ensureInitialized();let i=this.getCurrentVersion(e);if(i>=0)throw new Error(`Genesis already exists for pattern ${e} (current version: ${i})`);let s={id:C(),patternId:e,version:0,timestamp:Date.now(),type:"genesis",patch:[],reversePatch:[],metadata:{...r,snapshot:t}};return this.insertEvent(s),s}recordDelta(e,t,r,i){this.ensureInitialized();let s=this.getCurrentVersion(e);if(s<0)throw new Error(`No genesis found for pattern ${e}. Call createGenesis() first.`);let{forward:a,reverse:c}
|
|
43
|
+
`))}ensureInitialized(){if(!this.initialized)throw new Error("DeltaTracker not initialized. Call initialize() first.")}createGenesis(e,t,r){this.ensureInitialized();let i=this.getCurrentVersion(e);if(i>=0)throw new Error(`Genesis already exists for pattern ${e} (current version: ${i})`);let s={id:C(),patternId:e,version:0,timestamp:Date.now(),type:"genesis",patch:[],reversePatch:[],metadata:{...r,snapshot:t}};return this.insertEvent(s),s}recordDelta(e,t,r,i){this.ensureInitialized();let s=this.getCurrentVersion(e);if(s<0)throw new Error(`No genesis found for pattern ${e}. Call createGenesis() first.`);let{forward:a,reverse:c}=Je(t,r),u={id:C(),patternId:e,version:s+1,timestamp:Date.now(),type:"update",patch:a,reversePatch:c,metadata:i};return this.insertEvent(u),this.enforceRetention(e),u}rollback(e,t){this.ensureInitialized();let r=this.getHistory(e);if(r.length===0)throw new Error(`No history found for pattern ${e}`);let i=r[r.length-1].version;if(t<0||t>i)throw new Error(`Invalid rollback version ${t}. Valid range: 0-${i}`);if(t===i)return this.reconstructState(r,i);let s=this.reconstructState(r,t),a=this.reconstructState(r,i),{forward:c,reverse:u}=Je(a,s),o={id:C(),patternId:e,version:i+1,timestamp:Date.now(),type:"rollback",patch:c,reversePatch:u,metadata:{rolledBackTo:t}};return this.insertEvent(o),this.enforceRetention(e),s}getHistory(e){return this.ensureInitialized(),this.prepared.get("getHistory").all(e).map(Be)}incrementalSync(e){return this.ensureInitialized(),this.prepared.get("incrementalSync").all(e).map(Be)}getCurrentVersion(e){return this.ensureInitialized(),this.prepared.get("currentVersion").get(e).max_version??-1}insertEvent(e){this.prepared.get("insert").run(e.id,e.patternId,e.version,e.timestamp,e.type,JSON.stringify(e.patch),JSON.stringify(e.reversePatch),e.metadata?JSON.stringify(e.metadata):null)}reconstructState(e,t){let r=e.find(s=>s.type==="genesis");if(!r||!r.metadata?.snapshot)throw new Error("Cannot reconstruct state: no genesis snapshot found");let i=JSON.parse(JSON.stringify(r.metadata.snapshot));for(let s of e)if(s.version!==0){if(s.version>t)break;i=_t(i,s.patch)}return i}enforceRetention(e){let{maxVersionsPerPattern:t}=this.config,i=this.prepared.get("countForPattern").get(e).cnt;if(i>t){let s=i-t;this.db.prepare(`DELETE FROM pattern_deltas
|
|
44
44
|
WHERE pattern_id = ? AND version != 0 AND id IN (
|
|
45
45
|
SELECT id FROM pattern_deltas
|
|
46
46
|
WHERE pattern_id = ? AND version != 0
|
|
47
47
|
ORDER BY version ASC
|
|
48
48
|
LIMIT ?
|
|
49
|
-
)`).run(e,e,s)}}};F();var Ot={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},pe=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ot,...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),u={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(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let 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],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,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),u=a.findIndex(h=>h.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(h=>h.version===0||h.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 Be(n){return H()?new pe(n):null}F();var _t=128,Nt=8,Ht=1e4,ge=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??_t,this.beta=e?.beta??Nt,this.maxPatterns=e?.maxPatterns??Ht,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],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let 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)),u=this.dotProduct(t,t);return-c+.5*u}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(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function We(n){return new ge(n)}F();var Mt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,je=1-_;function Lt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function R(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function kt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var T=class n{static poincareDistance(e,t){let r=R(kt(e,t)),i=Math.max(_,1-R(e)),s=Math.max(_,1-R(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Lt(e,t),i=R(e),s=R(t),a=Math.max(_,1+2*r+i*s),c=1+2*r+s,u=1-i,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-R(e)),i=Math.sqrt(R(t));if(i<_)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(R(e));if(t<=je)return new Float32Array(e);let r=je/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(R(e));if(t<_)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)}},ye=class{config;points=new Map;constructor(e){if(this.config={...Mt,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:T.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 u of e)if(s.set(u.id,u),!u.parentId)a.push(u.id);else{let o=i.get(u.parentId);o||(o=[],i.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:h}=c.shift(),f=Math.tanh(.3*(o+.1)),d=l+h/2,m=new Float32Array(r);m[0]=f*Math.cos(d),m[1]=f*Math.sin(d);let g=s.get(u);if(g&&g.features.length>0){let N=f*.1;for(let x=2;x<r&&x-2<g.features.length;x++)m[x]=g.features[x-2]*N}let E=T.project(m);t.set(u,E),this.points.set(u,{id:u,coordinates:E,metadata:{depth:o,parentId:g?.parentId}});let A=i.get(u)??[];for(let N=0;N<A.length;N++){let x=h/Math.max(1,A.length);c.push({id:A[N],depth:o+1,angOff:l+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Xe(n){return Ut()?new ye(n):null}function Ut(){return D().useHyperbolicHnsw}F();var ve=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=Xe(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=T.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=T.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 Ge(n){return new ve(n)}var we=null;function Ve(){return we||(we=He({dimensions:1e4})),we}var Pe;function qt(){return Pe===void 0&&(Pe=Me()),Pe}var U=null,Se=0;function Ye(n){return(!U||Se!==n)&&(U=We({dimension:n,maxPatterns:1e4}),Se=n),U}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}},be=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ee(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-LVHQ5SG7.js"),{HnswAdapter:c}=await import("./hnsw-adapter-K62GEHIL.js"),u=new c("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new a(u),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-VCAK3TWN.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:",y(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;for(let{patternId:s,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){i++;continue}let c=this.patternCache.get(s);if(!c){i++;continue}try{await this.hnswIndex.insert(s,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{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:",y(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Be()),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:",y(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let i=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{this.sqliteStore.storePattern(e,e.embedding)}catch(s){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,y(s))}if(e.embedding){let s=await this.ensureHNSW();if(s)try{await s.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(q())try{let a=Ve().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(s){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,y(s))}try{let s=qt();if(s){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=s.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(s){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,y(s))}if(te()&&e.embedding)try{Ye(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(s){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,y(s))}if(H()&&this.deltaTracker)try{let s={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,s)}catch(s){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,y(s))}if(e.embedding)try{let s=this.getVectorDeltaTracker();s&&(i?.embedding?s.recordDelta(e.id,i.embedding,e.embedding):s.getVersion(e.id)<0&&s.recordGenesis(e.id,e.embedding))}catch(s){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,y(s))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return v(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):w(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)&&te())try{let h=Ye(e.length);if(h.getPatternCount()>0){let f=h.recall(new Float32Array(e));if(f&&f.similarity>.98){let d=f.metadata.id,m=await this.get(d);if(m&&this.matchesFilters(m,t)){let g=this.calculateReuseInfo(m,f.similarity);s.push({pattern:m,score:f.similarity,matchType:"vector",similarity:f.similarity,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",y(h))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let h=await this.ensureHNSW();if(h){let f=await h.search(e,i*2);for(let d of f){let m=await this.get(d.key);if(m&&this.matchesFilters(m,t)){let g=this.calculateReuseInfo(m,d.score);s.push({pattern:m,score:d.score,matchType:"vector",similarity:d.score,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let f=new Map(h.map(m=>[m.id,m.ftsScore])),d=new Set(s.map(m=>m.pattern.id));for(let m of s){let g=f.get(m.pattern.id);g!==void 0&&(m.score=.75*m.score+.25*g)}for(let m of h){if(d.has(m.id))continue;let g=await this.get(m.id);if(g&&this.matchesFilters(g,t)){let E=this.calculateReuseInfo(g,m.ftsScore);s.push({pattern:g,score:.5*m.ftsScore,matchType:"exact",similarity:m.ftsScore,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let h=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),f=new Set(s.map(d=>d.pattern.id));for(let d of h)f.has(d.pattern.id)||s.push(d)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let f=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),d=c-f,m=Math.pow(.5,d/a),g=h.pattern.usageCount>0?m:.5;h.score=h.score*(.7+.3*g)}s.sort((h,f)=>f.score-h.score);let u=s;t.filter&&(u=Fe(s,t.filter));let o=u.slice(0,i),l=performance.now()-r;return this.recordSearchLatency(l),v(o)}catch(a){return w(Re(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(q()&&s&&this.hdcCache.size>0)try{let u=Ve(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(d=>this.hdcCache.has(d)).map(d=>({id:d,similarity:u.similarity(o.vector,this.hdcCache.get(d))}));l.sort((d,m)=>m.similarity-d.similarity);let h=l.map(d=>d.id),f=c.filter(d=>!this.hdcCache.has(d));c=[...h,...f]}catch{}for(let u of c){if(i.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(s){let h=o.name.toLowerCase(),f=o.description.toLowerCase();h.includes(s)&&(l+=.5),f.includes(s)&&(s.length/f.length>.3?l+=.5:l+=.3);for(let d of o.context.tags)if(d.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let h=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.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(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,f=e.successRate,d=Math.min(e.reuseCount/10,1),m=o?h*.4+f*.4+d*.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){let r=await this.get(e);if(!r)return w(new Error(`Pattern not found: ${e}`));let i=new Date,s=r.usageCount+1,a=r.successfulUses+(t?1:0),c=a/s,u=t?.02:-.01,o=Math.max(.1,Math.min(1,r.confidence+u)),l=B({confidence:o,usageCount:s,successRate:c}),h={...r,usageCount:s,successfulUses:a,successRate:c,confidence:o,qualityScore:l,lastUsedAt:i};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t)}catch(m){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,y(m))}if(H()&&this.deltaTracker)try{let m={id:r.id,name:r.name,confidence:r.confidence,qualityScore:r.qualityScore,usageCount:r.usageCount,successRate:r.successRate,tier:r.tier},g={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,m,g,{success:t})}catch(m){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,y(m))}let f=re(h);return f.meetsUsageCriteria&&f.meetsQualityCriteria&&f.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),v(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return v(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`),v(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return v(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(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=re(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let u=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,h=s.qualityScore<.2,f=s.usageCount===0&&o>1440*60*1e3;(l&&h||f)&&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),U&&(U.clear(),U=null,Se=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ge({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(!M()||!this.hyperbolicIndex)return v([]);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),u=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return v(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),v([])}}};function Lr(n,e){try{if(D().useRVFPatternStore&&Ce()){let{existsSync:r}=Ee("fs"),i=".agentic-qe/patterns.rvf",s=Ee("path").dirname(i);if(r(s)){let a={...X,...e},c=!1;try{let{getSharedRvfAdapter:u}=(tt(),Ae(et)),o=u(s,a.embeddingDimension);if(o){c=!0;let l=new Q(()=>o,{rvfPath:i,base:a,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}catch{}if(!c){let u=new Q((o,l)=>{let{openRvfStore:h}=(De(),Ae(Ze)),f=()=>{try{return h(o)}catch{return null}},d=f();if(d){if(d.dimension()!==l){try{d.close()}catch{}throw new Error(`RVF dimension mismatch (file=${d.dimension()}, requested=${l})`)}return d}try{return xe(o,l)}catch(m){if(d=f(),d&&d.dimension()===l)return d;throw m}},{rvfPath:i,base:a});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),u}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new be(n,e)}export{Lr as a};
|
|
49
|
+
)`).run(e,e,s)}}};F();var Nt={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},me=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Nt,...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),u={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(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let 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],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,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),u=a.findIndex(h=>h.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(h=>h.version===0||h.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 je(n){return H()?new me(n):null}F();var Ht=128,Mt=8,Lt=1e4,ge=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Ht,this.beta=e?.beta??Mt,this.maxPatterns=e?.maxPatterns??Lt,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],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let 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)),u=this.dotProduct(t,t);return-c+.5*u}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(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function We(n){return new ge(n)}F();var kt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,Xe=1-_;function Ut(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function A(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function qt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var T=class n{static poincareDistance(e,t){let r=A(qt(e,t)),i=Math.max(_,1-A(e)),s=Math.max(_,1-A(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Ut(e,t),i=A(e),s=A(t),a=Math.max(_,1+2*r+i*s),c=1+2*r+s,u=1-i,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-A(e)),i=Math.sqrt(A(t));if(i<_)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(A(e));if(t<=Xe)return new Float32Array(e);let r=Xe/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(A(e));if(t<_)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)}},ye=class{config;points=new Map;constructor(e){if(this.config={...kt,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:T.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 u of e)if(s.set(u.id,u),!u.parentId)a.push(u.id);else{let o=i.get(u.parentId);o||(o=[],i.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:h}=c.shift(),d=Math.tanh(.3*(o+.1)),f=l+h/2,p=new Float32Array(r);p[0]=d*Math.cos(f),p[1]=d*Math.sin(f);let m=s.get(u);if(m&&m.features.length>0){let N=d*.1;for(let x=2;x<r&&x-2<m.features.length;x++)p[x]=m.features[x-2]*N}let E=T.project(p);t.set(u,E),this.points.set(u,{id:u,coordinates:E,metadata:{depth:o,parentId:m?.parentId}});let R=i.get(u)??[];for(let N=0;N<R.length;N++){let x=h/Math.max(1,R.length);c.push({id:R[N],depth:o+1,angOff:l+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Ge(n){return Qt()?new ye(n):null}function Qt(){return D().useHyperbolicHnsw}F();var ve=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=Ge(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=T.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=T.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 Ve(n){return new ve(n)}var we=null;function Ye(){return we||(we=Me({dimensions:1e4})),we}var Pe;function zt(){return Pe===void 0&&(Pe=Le()),Pe}var U=null,Se=0;function Ke(n){return(!U||Se!==n)&&(U=We({dimension:n,maxPatterns:1e4}),Se=n),U}var X={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:j,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}},be=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ee(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-W3T5ZDDP.js"),{HnswAdapter:c}=await import("./hnsw-adapter-EOOA4WXD.js"),u=new c("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new a(u),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-TD3KRPND.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:",y(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;for(let{patternId:s,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){i++;continue}let c=this.patternCache.get(s);if(!c){i++;continue}try{await this.hnswIndex.insert(s,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{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:",y(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=je()),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:",y(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=W(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let i=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{this.sqliteStore.storePattern(e,e.embedding)}catch(s){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,y(s))}if(e.embedding){let s=await this.ensureHNSW();if(s)try{await s.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(q())try{let a=Ye().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(s){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,y(s))}try{let s=zt();if(s){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=s.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(s){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,y(s))}if(te()&&e.embedding)try{Ke(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(s){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,y(s))}if(H()&&this.deltaTracker)try{let s={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,s)}catch(s){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,y(s))}if(e.embedding)try{let s=this.getVectorDeltaTracker();s&&(i?.embedding?s.recordDelta(e.id,i.embedding,e.embedding):s.getVersion(e.id)<0&&s.recordGenesis(e.id,e.embedding))}catch(s){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,y(s))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return v(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):w(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)&&te())try{let h=Ke(e.length);if(h.getPatternCount()>0){let d=h.recall(new Float32Array(e));if(d&&d.similarity>.98){let f=d.metadata.id,p=await this.get(f);if(p&&this.matchesFilters(p,t)){let m=this.calculateReuseInfo(p,d.similarity);s.push({pattern:p,score:d.similarity,matchType:"vector",similarity:d.similarity,canReuse:m.canReuse,estimatedTokenSavings:m.estimatedTokenSavings,reuseConfidence:m.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",y(h))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let h=await this.ensureHNSW();if(h){let d=await h.search(e,i*2);for(let f of d){let p=await this.get(f.key);if(p&&this.matchesFilters(p,t)){let m=this.calculateReuseInfo(p,f.score);s.push({pattern:p,score:f.score,matchType:"vector",similarity:f.score,canReuse:m.canReuse,estimatedTokenSavings:m.estimatedTokenSavings,reuseConfidence:m.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let d=new Map(h.map(p=>[p.id,p.ftsScore])),f=new Set(s.map(p=>p.pattern.id));for(let p of s){let m=d.get(p.pattern.id);m!==void 0&&(p.score=.75*p.score+.25*m)}for(let p of h){if(f.has(p.id))continue;let m=await this.get(p.id);if(m&&this.matchesFilters(m,t)){let E=this.calculateReuseInfo(m,p.ftsScore);s.push({pattern:m,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let h=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),d=new Set(s.map(f=>f.pattern.id));for(let f of h)d.has(f.pattern.id)||s.push(f)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let d=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),f=c-d,p=Math.pow(.5,f/a),m=h.pattern.usageCount>0?p:.5;h.score=h.score*(.7+.3*m)}s.sort((h,d)=>d.score-h.score);let u=s;t.filter&&(u=Oe(s,t.filter));let o=u.slice(0,i),l=performance.now()-r;return this.recordSearchLatency(l),v(o)}catch(a){return w(Ae(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(q()&&s&&this.hdcCache.size>0)try{let u=Ye(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(f=>this.hdcCache.has(f)).map(f=>({id:f,similarity:u.similarity(o.vector,this.hdcCache.get(f))}));l.sort((f,p)=>p.similarity-f.similarity);let h=l.map(f=>f.id),d=c.filter(f=>!this.hdcCache.has(f));c=[...h,...d]}catch{}for(let u of c){if(i.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(s){let h=o.name.toLowerCase(),d=o.description.toLowerCase();h.includes(s)&&(l+=.5),d.includes(s)&&(s.length/d.length>.3?l+=.5:l+=.3);for(let f of o.context.tags)if(f.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let h=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.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(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,d=e.successRate,f=Math.min(e.reuseCount/10,1),p=o?h*.4+d*.4+f*.2:0;return{canReuse:o,estimatedTokenSavings:l,reuseConfidence:p}}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){let r=await this.get(e);if(!r)return w(new Error(`Pattern not found: ${e}`));let i=new Date,s=r.usageCount+1,a=r.successfulUses+(t?1:0),c=a/s,u=t?.02:-.01,o=Math.max(.1,Math.min(1,r.confidence+u)),l=B({confidence:o,usageCount:s,successRate:c}),h={...r,usageCount:s,successfulUses:a,successRate:c,confidence:o,qualityScore:l,lastUsedAt:i};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t)}catch(p){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,y(p))}if(H()&&this.deltaTracker)try{let p={id:r.id,name:r.name,confidence:r.confidence,qualityScore:r.qualityScore,usageCount:r.usageCount,successRate:r.successRate,tier:r.tier},m={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,p,m,{success:t})}catch(p){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,y(p))}let d=re(h);return d.meetsUsageCriteria&&d.meetsQualityCriteria&&d.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),v(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return v(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`),v(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return v(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(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=re(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let u=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,h=s.qualityScore<.2,d=s.usageCount===0&&o>1440*60*1e3;(l&&h||d)&&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),U&&(U.clear(),U=null,Se=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ve({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(!M()||!this.hyperbolicIndex)return v([]);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),u=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return v(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),v([])}}};function qr(n,e){try{if(D().useRVFPatternStore&&De()){let{existsSync:r}=Ee("fs"),{join:i}=Ee("path"),s=process.env.AQE_PROJECT_ROOT??xe(),a=i(s,".agentic-qe"),c=i(a,"patterns.rvf");if(r(a)){let u={...X,...e},o=!1;try{let{getSharedRvfAdapter:l}=(nt(),Re(rt)),h=l(a,u.embeddingDimension);if(h){o=!0;let d=new Q(()=>h,{rvfPath:c,base:u,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),d}}catch{}if(!o){let l=new Q((h,d)=>{let{openRvfStore:f}=(Fe(),Re(tt)),p=()=>{try{return f(h)}catch{return null}},m=p();if(m){if(m.dimension()!==d){try{m.close()}catch{}throw new Error(`RVF dimension mismatch (file=${m.dimension()}, requested=${d})`)}return m}try{return Ce(h,d)}catch(E){if(m=p(),m&&m.dimension()===d)return m;throw E}},{rvfPath:c,base:u});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new be(n,e)}export{qr as a};
|
|
50
50
|
/*! Bundled license information:
|
|
51
51
|
|
|
52
52
|
fast-json-patch/commonjs/helpers.js:
|