agentic-qe 3.9.4 → 3.9.6
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 +38 -0
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-XV7RUOO7.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-MGGEPROV.js → agent-booster-wasm-ID2COJCQ.js} +2 -2
- package/dist/cli/chunks/{agent-handler-AFHYFQXV.js → agent-handler-EWK6FHKU.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-SQ3KDIG6.js → agent-memory-branch-BDKB7HER.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-Q5CC43GW.js +2 -0
- package/dist/cli/chunks/{audit-SM5CK2K5.js → audit-EB62PPY4.js} +2 -2
- package/dist/cli/chunks/base-UL4PX45P.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-UGOYRNXI.js → better-sqlite3-C4HK6YT3.js} +2 -2
- package/dist/cli/chunks/{brain-handler-SKXTB63O.js → brain-handler-QLIHJDGD.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-77NSOLNK.js → branch-enumerator-HWWHSETZ.js} +2 -2
- package/dist/cli/chunks/{browser-MCE5DWPV.js → browser-PEMYUQ6B.js} +2 -2
- package/dist/cli/chunks/browser-workflow-K77KPDRF.js +2 -0
- package/dist/cli/chunks/{chunk-4BQTEPAD.js → chunk-2DGTT6D2.js} +2 -2
- package/dist/cli/chunks/{chunk-7ST2YENJ.js → chunk-2FTTRGRS.js} +2 -2
- package/dist/cli/chunks/{chunk-QVZSIFSJ.js → chunk-3BAC7NLV.js} +3 -3
- package/dist/cli/chunks/{chunk-DZHGYZJP.js → chunk-3TAJSNCZ.js} +1 -1
- package/dist/cli/chunks/{chunk-7EL65Y27.js → chunk-3U3NUFII.js} +1 -1
- package/dist/cli/chunks/{chunk-G72E5DL3.js → chunk-3VBPPW7H.js} +1 -1
- package/dist/cli/chunks/{chunk-C3BXT3ZC.js → chunk-3WQ7MLAJ.js} +4 -4
- package/dist/cli/chunks/{chunk-QPC4STR6.js → chunk-46442R6Q.js} +2 -2
- package/dist/cli/chunks/{chunk-VBXJBXMG.js → chunk-4H3YCKAI.js} +4 -4
- package/dist/cli/chunks/{chunk-JVUNZBKX.js → chunk-4NYVSHN3.js} +2 -2
- package/dist/cli/chunks/{chunk-LW3DV23G.js → chunk-5A5ECZCN.js} +2 -2
- package/dist/cli/chunks/{chunk-ZQSEPDIJ.js → chunk-5AXU6KCI.js} +2 -2
- package/dist/cli/chunks/{chunk-KELYPHMV.js → chunk-5CKG46BM.js} +2 -2
- package/dist/cli/chunks/{chunk-IQE6GOH6.js → chunk-64SU2UFL.js} +2 -2
- package/dist/cli/chunks/{chunk-XYVMKCSI.js → chunk-67WBMX7K.js} +1 -1
- package/dist/cli/chunks/{chunk-RGRYL4MG.js → chunk-6T6TPZCK.js} +2 -2
- package/dist/cli/chunks/{chunk-QEYPK7KS.js → chunk-6X6NWAVQ.js} +1 -1
- package/dist/cli/chunks/{chunk-XB5HXTL4.js → chunk-775KESYW.js} +2 -2
- package/dist/cli/chunks/{chunk-RAZ2PGZD.js → chunk-7B3IZBNN.js} +2 -2
- package/dist/cli/chunks/{chunk-IGJ472XJ.js → chunk-7B46Q5OU.js} +2 -2
- package/dist/cli/chunks/{chunk-TT2TB6UF.js → chunk-7CSZCRSS.js} +3 -3
- package/dist/cli/chunks/{chunk-WHT46PJM.js → chunk-7EDVNITA.js} +2 -2
- package/dist/cli/chunks/{chunk-B252DDC5.js → chunk-7MD7PQYH.js} +1 -1
- package/dist/cli/chunks/{chunk-QOU4R6AF.js → chunk-AFOGTLSY.js} +2 -2
- package/dist/cli/chunks/{chunk-27P4VTCY.js → chunk-AJX44TJ7.js} +2 -2
- package/dist/cli/chunks/{chunk-MR5I6UR2.js → chunk-AMLREU5W.js} +2 -2
- package/dist/cli/chunks/{chunk-GT35EJKR.js → chunk-ARRJKSDK.js} +1 -1
- package/dist/cli/chunks/{chunk-RPYUKEAH.js → chunk-BHOJLQLF.js} +2 -2
- package/dist/cli/chunks/{chunk-MUX762XZ.js → chunk-BKCIW3O2.js} +2 -2
- package/dist/cli/chunks/{chunk-54OLXGXJ.js → chunk-C723FDLL.js} +2 -2
- package/dist/cli/chunks/{chunk-2MQMXI7C.js → chunk-CJ6GN5QT.js} +2 -2
- package/dist/cli/chunks/{chunk-27FNBMUC.js → chunk-CLVHHUZB.js} +2 -2
- package/dist/cli/chunks/{chunk-3MN7E6HY.js → chunk-CQNNNR53.js} +2 -2
- package/dist/cli/chunks/{chunk-RN3SN4ZC.js → chunk-CU3LGMOK.js} +2 -2
- package/dist/cli/chunks/{chunk-BH5XPYA3.js → chunk-DAWI2HRN.js} +2 -2
- package/dist/cli/chunks/{chunk-3MRFR534.js → chunk-E5J3GKCP.js} +2 -2
- package/dist/cli/chunks/{chunk-Q2ZYUIS2.js → chunk-EJSRKZ5M.js} +2 -2
- package/dist/cli/chunks/{chunk-Q6FSXNQP.js → chunk-EMKI4ZV5.js} +2 -2
- package/dist/cli/chunks/{chunk-SKWI5QBM.js → chunk-ESFKNND3.js} +2 -2
- package/dist/cli/chunks/{chunk-GQ7DCSKS.js → chunk-EVRJS6CN.js} +2 -2
- package/dist/cli/chunks/{chunk-NEYZXYFH.js → chunk-FZ77DJFC.js} +2 -2
- package/dist/cli/chunks/{chunk-OHZ6RJLS.js → chunk-G3VIZON2.js} +2 -2
- package/dist/cli/chunks/{chunk-LH3ZL2OK.js → chunk-GXVUDSYW.js} +2 -2
- package/dist/cli/chunks/{chunk-B6HLXE3D.js → chunk-H3KGRTY2.js} +9 -9
- package/dist/cli/chunks/{chunk-UJLSCJJS.js → chunk-H4J456F2.js} +1 -1
- package/dist/cli/chunks/{chunk-A6ZBQCYB.js → chunk-H5OYJKPR.js} +2 -2
- package/dist/cli/chunks/{chunk-TNWTQWLL.js → chunk-H7OP3RI2.js} +1 -1
- package/dist/cli/chunks/{chunk-DLMEBVLF.js → chunk-HUPIHL55.js} +2 -2
- package/dist/cli/chunks/{chunk-ENKPW6MA.js → chunk-HZSYBKRI.js} +2 -2
- package/dist/cli/chunks/{chunk-U7YC7VCM.js → chunk-JB3G5ZLL.js} +2 -2
- package/dist/cli/chunks/{chunk-ZW5DRPZY.js → chunk-JDGUTBC3.js} +2 -2
- package/dist/cli/chunks/{chunk-GSKZL36U.js → chunk-JEF3S4ER.js} +2 -2
- package/dist/cli/chunks/{chunk-BZ22GI4E.js → chunk-JRPYXCDT.js} +1 -1
- package/dist/cli/chunks/{chunk-5UKAEBKC.js → chunk-K52WNOTU.js} +3 -3
- package/dist/cli/chunks/{chunk-YDJKQKQH.js → chunk-K5RE6ODJ.js} +2 -2
- package/dist/cli/chunks/{chunk-EHGTXIT7.js → chunk-K6XC52U3.js} +1 -1
- package/dist/cli/chunks/{chunk-VBYREHZI.js → chunk-KI4W6CVC.js} +1 -1
- package/dist/cli/chunks/{chunk-O6QAOPUA.js → chunk-KIEXP4F3.js} +3 -3
- package/dist/cli/chunks/{chunk-HKTNFHWI.js → chunk-L6HQVZQL.js} +1 -1
- package/dist/cli/chunks/{chunk-VFXTZWNF.js → chunk-LFTQYU65.js} +2 -2
- package/dist/cli/chunks/{chunk-J222JLZ6.js → chunk-LSFJKCAQ.js} +2 -2
- package/dist/cli/chunks/{chunk-2JLKOGNU.js → chunk-LZ5LS4LF.js} +1 -1
- package/dist/cli/chunks/chunk-MA7OLK56.js +2 -0
- package/dist/cli/chunks/{chunk-SHJZ3YNX.js → chunk-MAZWSPEQ.js} +2 -2
- package/dist/cli/chunks/{chunk-RUJU5XEQ.js → chunk-MRDXDXPW.js} +1 -1
- package/dist/cli/chunks/{chunk-4GJAYXB7.js → chunk-MROCXAXJ.js} +2 -2
- package/dist/cli/chunks/{chunk-4TZTGYBQ.js → chunk-MV52OH7P.js} +1 -1
- package/dist/cli/chunks/{chunk-RRQEIGLS.js → chunk-MX3ORXM3.js} +2 -2
- package/dist/cli/chunks/{chunk-C2HGOUEB.js → chunk-N5CEEWWJ.js} +1 -1
- package/dist/cli/chunks/{chunk-RTC3ZCPK.js → chunk-NA5ZOZIF.js} +2 -2
- package/dist/cli/chunks/{chunk-MS6LTE4L.js → chunk-NOK2ICQT.js} +2 -2
- package/dist/cli/chunks/{chunk-C567IO5M.js → chunk-NPNGSE7X.js} +2 -2
- package/dist/cli/chunks/{chunk-MN2MYLVW.js → chunk-NSRIYP76.js} +2 -2
- package/dist/cli/chunks/{chunk-EZTUUOVI.js → chunk-O65ZAUG3.js} +1 -1
- package/dist/cli/chunks/{chunk-VSNPI2NO.js → chunk-P4X6YTOY.js} +8 -8
- package/dist/cli/chunks/{chunk-NZ5LY2BT.js → chunk-PKD6LEQZ.js} +1 -1
- package/dist/cli/chunks/{chunk-53M65YFH.js → chunk-QBQ52YUU.js} +2 -2
- package/dist/cli/chunks/{chunk-UUL3D5HR.js → chunk-QE255FHS.js} +4 -4
- package/dist/cli/chunks/{chunk-7FJIIB4H.js → chunk-QGEZJKVO.js} +1 -1
- package/dist/cli/chunks/{chunk-GVFHRHXC.js → chunk-QWVILMUX.js} +2 -2
- package/dist/cli/chunks/{chunk-EFD2J6GG.js → chunk-QYGI32T4.js} +3 -3
- package/dist/cli/chunks/{chunk-RS7ZGWHV.js → chunk-RD5N2722.js} +2 -2
- package/dist/cli/chunks/{chunk-3SPYUOSS.js → chunk-RZLRPLRC.js} +2 -2
- package/dist/cli/chunks/{chunk-G6RTCJFY.js → chunk-SQCNABS4.js} +2 -2
- package/dist/cli/chunks/chunk-SYYGXU7I.js +2 -0
- package/dist/cli/chunks/{chunk-GX7MEHQ2.js → chunk-T4L6MHRW.js} +1 -1
- package/dist/cli/chunks/{chunk-UPJZRDZK.js → chunk-TG7PATSN.js} +2 -2
- package/dist/cli/chunks/{chunk-ZODUKKPC.js → chunk-TPXS5KEC.js} +2 -2
- package/dist/cli/chunks/{chunk-MGRE767N.js → chunk-TSZ6VMCF.js} +2 -2
- package/dist/cli/chunks/{chunk-EEARIB4C.js → chunk-UB53OWSL.js} +1 -1
- package/dist/cli/chunks/{chunk-RE6XD6RI.js → chunk-V2IUGAJ7.js} +2 -2
- package/dist/cli/chunks/{chunk-JMBUIVVE.js → chunk-V3D6AA2P.js} +1 -1
- package/dist/cli/chunks/{chunk-GAG2P4I2.js → chunk-VJKIPTA2.js} +1 -1
- package/dist/cli/chunks/{chunk-3RHIPCBG.js → chunk-VMDSTKVR.js} +2 -2
- package/dist/cli/chunks/{chunk-72EC26AS.js → chunk-WFWVSI2W.js} +2 -2
- package/dist/cli/chunks/{chunk-ZKWNZ3ZK.js → chunk-WOR67NKR.js} +2 -2
- package/dist/cli/chunks/{chunk-NRH2QE4X.js → chunk-WQ76RMU3.js} +3 -3
- package/dist/cli/chunks/{chunk-ONOYANDX.js → chunk-XKU2LJIM.js} +1 -1
- package/dist/cli/chunks/{chunk-DHJJJ24V.js → chunk-XOTBE543.js} +2 -2
- package/dist/cli/chunks/{chunk-YS6C2Q4F.js → chunk-XQAZHVHD.js} +1 -1
- package/dist/cli/chunks/{chunk-V57PXZIK.js → chunk-Y2BEI3DL.js} +3 -3
- package/dist/cli/chunks/{chunk-J6KBI5NW.js → chunk-Y65KKN4T.js} +1 -1
- package/dist/cli/chunks/{chunk-Z75DMTMI.js → chunk-YI54PU4P.js} +1 -1
- package/dist/cli/chunks/{chunk-J72Q6ERO.js → chunk-YOLOT7MX.js} +2 -2
- package/dist/cli/chunks/{chunk-P3EOWBME.js → chunk-YQ7X6LKA.js} +2 -2
- package/dist/cli/chunks/{chunk-7ZXNJT4Q.js → chunk-YV34KLBV.js} +2 -2
- package/dist/cli/chunks/{chunk-KSMQH2CV.js → chunk-YWWQRNKI.js} +1 -1
- package/dist/cli/chunks/{chunk-COIRFVFO.js → chunk-Z4UUJUZO.js} +1 -1
- package/dist/cli/chunks/{chunk-F6AU2MAZ.js → chunk-Z5IOTEQI.js} +2 -2
- package/dist/cli/chunks/{chunk-NS4CCCTZ.js → chunk-ZV6CCRP2.js} +2 -2
- package/dist/cli/chunks/{ci-THZEECIQ.js → ci-6L22RUNC.js} +2 -2
- package/dist/cli/chunks/{ci-output-G6QLGL4S.js → ci-output-C2PAMUXM.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-5MTYQM34.js → claude-flow-setup-S3HHSSIM.js} +2 -2
- package/dist/cli/chunks/client-KXLRKXSG.js +2 -0
- package/dist/cli/chunks/{cline-installer-E2LF2DQS.js → cline-installer-YIXOIHBL.js} +2 -2
- package/dist/cli/chunks/{code-QRF7ZGXG.js → code-QVFF72Z4.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-II6IRWU6.js → code-index-extractor-BRNK2X4M.js} +2 -2
- package/dist/cli/chunks/{codex-installer-LGOQ23ZS.js → codex-installer-TLRH3SG7.js} +2 -2
- package/dist/cli/chunks/{completions-LB2RR2OQ.js → completions-A46MED6L.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-PUIPIRX3.js → complexity-analyzer-FJSG676O.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-HQAEAQZU.js → continuedev-installer-7HHND63H.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-3PKCX5K5.js → copilot-installer-UQ4IEG4H.js} +2 -2
- package/dist/cli/chunks/{cost-tracker-JG3SZ2Q3.js → cost-tracker-R6FXO2MO.js} +2 -2
- package/dist/cli/chunks/{coverage-D3PZTOKT.js → coverage-3AGGT36D.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-I2WPLKVN.js +2 -0
- package/dist/cli/chunks/{cursor-installer-UY6GWKTO.js → cursor-installer-7PABDYDI.js} +2 -2
- package/dist/cli/chunks/{daemon-UNO3LRRN.js → daemon-YTCKYJB4.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-S2MXANYL.js → dag-attention-scheduler-LZZ4O2PT.js} +2 -2
- package/dist/cli/chunks/{detect-DU2FTRKR.js → detect-OBCGJIYW.js} +2 -2
- package/dist/cli/chunks/{domain-handler-KPNO36LF.js → domain-handler-5PHN6YQM.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-6X3ZZF6A.js → domain-transfer-K6YSBC2L.js} +2 -2
- package/dist/cli/chunks/dream-BH35JQRS.js +2 -0
- package/dist/cli/chunks/esm-node-VI5DSKCM.js +2 -0
- package/dist/cli/chunks/{eval-6RXEDTBZ.js → eval-UAAFW3YU.js} +2 -2
- package/dist/cli/chunks/{fast-paths-FYODFGZB.js → fast-paths-7IFG4BYW.js} +2 -2
- package/dist/cli/chunks/{feature-flags-ZJ42B4IL.js → feature-flags-AEO5C73R.js} +2 -2
- package/dist/cli/chunks/{feature-flags-YOULURDA.js → feature-flags-TVJAGLLH.js} +2 -2
- package/dist/cli/chunks/{file-discovery-KOL7FSBQ.js → file-discovery-STTTDBN3.js} +2 -2
- package/dist/cli/chunks/{fleet-22I74LGD.js → fleet-L6RVZQ2B.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-DFHTHLIZ.js → gnn-wrapper-W4QHVBUD.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-SQ6VYEAA.js → heartbeat-handler-3KZOB7MZ.js} +4 -4
- package/dist/cli/chunks/{heartbeat-scheduler-W6PQJ5SG.js → heartbeat-scheduler-IR57JOZR.js} +2 -2
- package/dist/cli/chunks/hnsw-adapter-2SFTC2VH.js +2 -0
- package/dist/cli/chunks/hnsw-index-OBEYJRMU.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-AYTRT54U.js → hnsw-legacy-bridge-5BYAJDVC.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-4IA56UH4.js → hnswlib-node-MUXAWCUE.js} +2 -2
- package/dist/cli/chunks/{hooks-T6UMR72X.js → hooks-QT4NVEDG.js} +6 -6
- package/dist/cli/chunks/{hypergraph-engine-WVPYKMFY.js → hypergraph-engine-MLLU5WQB.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-NB6GL4CR.js → hypergraph-handler-LJWRQ2WW.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-C5SKESHG.js +2 -0
- package/dist/cli/chunks/{init-handler-UOFNBXEP.js → init-handler-MKAZHZJS.js} +6 -6
- package/dist/cli/chunks/init-wizard-DV34KMTN.js +2 -0
- package/dist/cli/chunks/kernel-3HL4J5WJ.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-VWMNI4QX.js → kilocode-installer-5MAYAROV.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-RNM47FV5.js → kiro-installer-3JJ7TSXH.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-XPFESDWZ.js +2 -0
- package/dist/cli/chunks/{learning-L4RB5XYP.js → learning-G7MWQMRY.js} +3 -3
- package/dist/cli/chunks/{llm-router-BZYZL3YI.js → llm-router-HYK5VS4A.js} +2 -2
- package/dist/cli/chunks/{load-4UGEGRMO.js → load-YVN3F5ZP.js} +2 -2
- package/dist/cli/chunks/load-test-EF3BRFGO.js +2 -0
- package/dist/cli/chunks/{mcp-FWWZIWCI.js → mcp-I43GRN5E.js} +2 -2
- package/dist/cli/chunks/{memory-5OXPMXU6.js → memory-TMKTUI37.js} +5 -5
- package/dist/cli/chunks/memory-backend-FJDNXX6N.js +2 -0
- package/dist/cli/chunks/{memory-handlers-JS7BTWJK.js → memory-handlers-YFJOLCGN.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-BS5TQKHB.js → opencode-installer-KYDQUOAW.js} +2 -2
- package/dist/cli/chunks/{orchestrator-G6BUZ6QE.js → orchestrator-C6XRSC6Z.js} +25 -22
- package/dist/cli/chunks/{pipeline-3MZ5COPR.js → pipeline-IULH5B62.js} +2 -2
- package/dist/cli/chunks/{platform-TKD4JCUG.js → platform-CACMGVB3.js} +2 -2
- package/dist/cli/chunks/{plugin-XXJ7R6SY.js → plugin-6VSTK54C.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-JLJ6NKIP.js → prime-radiant-advanced-wasm-UA6FGPKX.js} +2 -2
- package/dist/cli/chunks/protocol-executor-OFL7H2VR.js +2 -0
- package/dist/cli/chunks/{protocol-handler-ZLYGQPHG.js → protocol-handler-UYJISQUT.js} +2 -2
- package/dist/cli/chunks/{prove-E2WZ335X.js → prove-H7PAIHGE.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-4NWLHIEM.js +2 -0
- package/dist/cli/chunks/{quality-6MHHBINU.js → quality-NT3N4UDM.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-I7YDKGZD.js +2 -0
- package/dist/cli/chunks/{real-embeddings-QN5BY3WS.js → real-embeddings-K46PTHOR.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-GTVII272.js → roocode-installer-K47KSTXW.js} +2 -2
- package/dist/cli/chunks/router-LNGYBIC4.js +2 -0
- package/dist/cli/chunks/routing-feedback-4RFHNTYV.js +2 -0
- package/dist/cli/chunks/{routing-handler-HYKZ3ISS.js → routing-handler-5RXV3FRV.js} +2 -2
- package/dist/cli/chunks/ruvector-commands-V46KRNUZ.js +8 -0
- package/dist/cli/chunks/{rvf-dual-writer-TVCJ2Y6N.js → rvf-dual-writer-YX5K3XO7.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-34ITXLU3.js → rvf-migration-adapter-SURDRXWQ.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-SX2C7777.js → rvf-migration-coordinator-FMUHUWTB.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-7REIX6DO.js +2 -0
- package/dist/cli/chunks/safe-db-SVN2BQFW.js +2 -0
- package/dist/cli/chunks/schedule-S6Z3DNRK.js +2 -0
- package/dist/cli/chunks/scheduler-BE5RHB4R.js +2 -0
- package/dist/cli/chunks/{security-7A4EW77M.js → security-ENEWXTNE.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-PNVIYEDK.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-27L4R5WK.js → shared-rvf-dual-writer-KJ67FATL.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-XBTALZ2S.js +2 -0
- package/dist/cli/chunks/{status-handler-JN6PRYLD.js → status-handler-CEMWQKE6.js} +2 -2
- package/dist/cli/chunks/{structural-health-JSY3DY7H.js → structural-health-B4VGYG4F.js} +2 -2
- package/dist/cli/chunks/{sync-ET3LYW2V.js → sync-P7PLECMB.js} +2 -2
- package/dist/cli/chunks/{task-handler-R24MR74L.js → task-handler-YGKMS5E2.js} +2 -2
- package/dist/cli/chunks/{task-handlers-YNPEEPPZ.js → task-handlers-LKTBRIPS.js} +2 -2
- package/dist/cli/chunks/{test-7BZXFZCT.js → test-ZWWGVM5X.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-EVIFD5EY.js → test-scheduling-HTFVIWWL.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-QYYQRXM5.js → token-bootstrap-7VYNREQH.js} +2 -2
- package/dist/cli/chunks/{token-usage-H4OZA77I.js → token-usage-D67GP7FV.js} +2 -2
- package/dist/cli/chunks/{transformers-ILQFO5HZ.js → transformers-CI3CZC2C.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-KTST5NWH.js → tree-sitter-wasm-parser-BMRWIP7P.js} +2 -2
- package/dist/cli/chunks/{types-4Z7XELU6.js → types-SAPPKMCS.js} +2 -2
- package/dist/cli/chunks/unified-memory-OYIJOZ2E.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-JRWF6EEB.js +2 -0
- package/dist/cli/chunks/unified-persistence-OOUATKAN.js +2 -0
- package/dist/cli/chunks/{validate-GSQCH6VN.js → validate-UZL2Y3GR.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-SP2RPOYD.js → validate-swarm-ILNS64DZ.js} +2 -2
- package/dist/cli/chunks/{vibium-2SGOFYTF.js → vibium-CJMPXUAU.js} +2 -2
- package/dist/cli/chunks/visual-security-77T3APRH.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-QSQ27UTH.js → web-tree-sitter-HO5UYPPH.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-NIEH46E2.js → windsurf-installer-TEXMCEBB.js} +2 -2
- package/dist/cli/chunks/witness-chain-QIARNA6D.js +2 -0
- package/dist/cli/chunks/{witness-chain-62GJTCT5.js → witness-chain-TF35D7QS.js} +2 -2
- package/dist/cli/chunks/{workflow-WZMV2MGW.js → workflow-APRDB3SB.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-IRZVM4MZ.js +2 -0
- package/dist/cli/chunks/{wrappers-LNTV533I.js → wrappers-VGV5RU5Q.js} +2 -2
- package/dist/cli/commands/ruvector-commands.js +5 -2
- package/dist/cli/index.js +5 -4
- package/dist/init/phases/04-database.js +19 -0
- package/dist/init/phases/06-code-intelligence.js +9 -6
- package/dist/init/phases/10-workers.js +2 -0
- package/dist/integrations/ruvector/feature-flags.d.ts +27 -5
- package/dist/integrations/ruvector/feature-flags.js +14 -1
- package/dist/kernel/hnsw-adapter.js +1 -1
- package/dist/kernel/native-hnsw-backend.d.ts +100 -37
- package/dist/kernel/native-hnsw-backend.js +207 -192
- package/dist/kernel/unified-memory.js +15 -10
- package/dist/mcp/bundle.js +189 -189
- package/package.json +1 -1
- package/dist/cli/chunks/adapter-5ODIX6ZG.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-PWGRS6KK.js +0 -2
- package/dist/cli/chunks/base-TJGIYR7L.js +0 -2
- package/dist/cli/chunks/browser-workflow-GUR7RLFP.js +0 -2
- package/dist/cli/chunks/chunk-MDFXPCBO.js +0 -2
- package/dist/cli/chunks/chunk-OZC42UMD.js +0 -2
- package/dist/cli/chunks/client-IFMC3AYQ.js +0 -2
- package/dist/cli/chunks/cross-domain-router-2LPBUUWY.js +0 -2
- package/dist/cli/chunks/dream-NGRDMOTE.js +0 -2
- package/dist/cli/chunks/esm-node-3COTOSO3.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-BASJNTEV.js +0 -2
- package/dist/cli/chunks/hnsw-index-NFN2AUIX.js +0 -2
- package/dist/cli/chunks/impact-analyzer-ZMQXHQDV.js +0 -2
- package/dist/cli/chunks/init-wizard-QHAA4GWF.js +0 -2
- package/dist/cli/chunks/kernel-SNJFYN3T.js +0 -2
- package/dist/cli/chunks/knowledge-graph-EP5UTODP.js +0 -2
- package/dist/cli/chunks/load-test-KMMRHABK.js +0 -2
- package/dist/cli/chunks/memory-backend-Q5MWPMDE.js +0 -2
- package/dist/cli/chunks/protocol-executor-ORFR4WJ3.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-PLTOH4SG.js +0 -2
- package/dist/cli/chunks/queen-coordinator-L3TRAX7H.js +0 -2
- package/dist/cli/chunks/router-3PBJJLRQ.js +0 -2
- package/dist/cli/chunks/routing-feedback-Q775MZ3Z.js +0 -2
- package/dist/cli/chunks/ruvector-commands-LBWHPUTZ.js +0 -8
- package/dist/cli/chunks/rvf-native-adapter-HLY2652E.js +0 -2
- package/dist/cli/chunks/safe-db-CCKCBZ5I.js +0 -2
- package/dist/cli/chunks/schedule-WZ5VV55N.js +0 -2
- package/dist/cli/chunks/scheduler-6PIKLCH7.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-VCJNSACZ.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-HMXYD56G.js +0 -2
- package/dist/cli/chunks/unified-memory-RBHCTAWW.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-UBF5PT6D.js +0 -2
- package/dist/cli/chunks/unified-persistence-ZIJDP6GW.js +0 -2
- package/dist/cli/chunks/visual-security-WKIWOUTH.js +0 -2
- package/dist/cli/chunks/witness-chain-4BRX3GGH.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-G6VU7QZ4.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as W}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.6");process.exit(0)}
|
|
2
|
+
import{a as W}from"./chunk-AMLREU5W.js";import{c as V,d as q}from"./chunk-3BAC7NLV.js";import{c as M}from"./chunk-C723FDLL.js";import{a as $}from"./chunk-MA7OLK56.js";import{c as N}from"./chunk-BHOJLQLF.js";import{b as D,d as H}from"./chunk-MROCXAXJ.js";import{a as E,c as k}from"./chunk-Z5IOTEQI.js";import{f as y}from"./chunk-3VBPPW7H.js";import{a as R,b as U,d as J}from"./chunk-YQ7X6LKA.js";var P={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};H();k();var A=class{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...P,...e}}async initialize(){if(!this.initialized)try{if(this.persistence=M(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.prepareStatements(),this.initialized=!0,this.config.debug){let e=await this.getStats();console.log(`[ConceptGraph] Initialized: ${this.persistence.getDbPath()}`,e)}}catch(e){throw new Error(`Failed to initialize ConceptGraph: ${E(e)}`)}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertNode",this.db.prepare(`
|
|
3
3
|
INSERT INTO concept_nodes
|
|
4
4
|
(id, concept_type, content, embedding, activation_level, last_activated, pattern_id, metadata)
|
|
5
5
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -59,7 +59,7 @@ import{a as W}from"./chunk-MR5I6UR2.js";import{c as V,d as q}from"./chunk-QVZSIF
|
|
|
59
59
|
ORDER BY weight DESC
|
|
60
60
|
LIMIT -1 OFFSET ?
|
|
61
61
|
)
|
|
62
|
-
`).run(s,e);a+=c.changes}return a})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,a=t.get().count,r={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)r[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:a,byType:r,avgEdgesPerNode:i>0?a/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?D(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function K(h){return new A(h)}J();function Z(h,e){if(e<0||e>=h.length)return h[0]??0;let t=0,n=h.length-1;for(;t<n;){let i=t+n>>1;if(h[i]<h[t]){let s=h[t];h[t]=h[i],h[i]=s}if(h[n]<h[t]){let s=h[t];h[t]=h[n],h[n]=s}if(h[i]<h[n]){let s=h[i];h[i]=h[n],h[n]=s}let a=h[n],r=t;for(let s=t;s<n;s++)if(h[s]<=a){let c=h[r];h[r]=h[s],h[s]=c,r++}let o=h[r];if(h[r]=h[n],h[n]=o,r===e)return h[r];r<e?t=r+1:n=r-1}return h[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},S=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(d=>this.graph.getConcept(d)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let d of i)this.graph.setActivation(d,t),this.recordActivation(d,t);let a=0,r=t,o=0,s=0;for(;a<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),l=this.graph.getActiveNodes(this.config.threshold);for(let u of l)u.activationLevel>r&&(r=u.activationLevel);if(l.length===o&&d===0){if(s++,s>=3)break}else s=0;o=l.length,a++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,l)=>l.activation-d.activation),p=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:a,nodesActivated:c.length,peakActivation:r,activatedNodes:c,novelAssociations:p.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,a=0,r=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let d=U(0,o.length),l=o[d];if(l){let u=this.config.noiseLevel+R()*this.config.noiseLevel*2,m=l.activationLevel,v=Math.min(1,m+u+.3);this.graph.setActivation(l.id,v);let f=await this.spread([l.id],v,s);i+=f.iterations,f.peakActivation>a&&(a=f.peakActivation);for(let b of f.activatedNodes)r.add(b.nodeId);for(let b of f.novelAssociations)n.push(b)}if(Date.now()>=s)break;await this.sleep(50+R()*50)}let c=this.deduplicateAssociations(n),p=Array.from(r).map(d=>{let l=this.graph.getConcept(d);return{nodeId:d,activation:l?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,l)=>l.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:p.length,peakActivation:a,activatedNodes:p,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((r,o)=>o.activationLevel-r.activationLevel).slice(0,i));let a=[];for(let r=0;r<n.length;r++)for(let o=r+1;o<n.length;o++){let s=n[r],c=n[o],p=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),l=this.graph.getEdge(c.id,s.id),u=d!==void 0||l!==void 0,m=d?.weight??l?.weight??0,v=!u||m<.3;p>.3&&(a.push({source:s,target:c,coActivation:p,isNovel:v}),this.trackCoActivation(s.id,c.id))}return a.sort((r,o)=>r.isNovel!==o.isNovel?r.isNovel?-1:1:o.coActivation-r.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=B)return;let e=Math.floor(B*F),t=this.activationHistory.size-e,n=Array.from(this.activationHistory.keys()).slice(0,t);for(let i of n)this.activationHistory.delete(i)}trimCoActivationCounts(){if(this.coActivationCounts.size<=O)return;let e=Math.floor(O*F),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=Z(n,t-1),a=[];for(let[r,o]of this.coActivationCounts){if(a.length>=t)break;o<=i&&a.push(r)}for(let r of a)this.coActivationCounts.delete(r)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let a=this.graph.getEdges(i.id);for(let r of a){let o=this.graph.getConcept(r.target);if(!o)continue;let s=i.activationLevel*r.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,p=Math.min(1,c+s);n.push({nodeId:r.target,newActivation:p})}}}for(let i of n){let a=this.graph.getConcept(i.nodeId);a&&i.newActivation>a.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(R()-.5)*2*this.config.noiseLevel,i=Math.max(0,Math.min(1,t.activationLevel+n));this.graph.setActivation(t.id,i)}}recordActivation(e,t){let n=this.activationHistory.get(e)||[];n.push(t),n.length>50&&n.shift(),this.activationHistory.set(e,n)}trackCoActivation(e,t){let n=[e,t].sort().join(":"),i=this.coActivationCounts.get(n)||0;this.coActivationCounts.set(n,i+1)}deduplicateAssociations(e){let t=new Map;for(let n of e){let i=[n.source,n.target].sort().join(":"),a=t.get(i);(!a||n.strength>a.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ee}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},I=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let a=await this.detectPatternMerges(i);for(let c of a)c.cycleId=e,n.push(c);let r=await this.detectNovelAssociations(t.novelAssociations);for(let c of r)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,p)=>p.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let a=i+1;a<n.length;a++){let r=n[i],o=n[a],s=this.graph.getEdge(r.id,o.id),c=this.graph.getEdge(o.id,r.id),p=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(r.content,o.content),l=Math.sqrt(r.activationLevel*o.activationLevel),u=p*.4+d*.3+l*.3;if(u>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[r.id,o.id]}),v=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[r.id,o.id],edgeWeight:p,contentSimilarity:d,coActivation:l});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[r.id,o.id],description:this.generatePatternMergeDescription(r,o,u),noveltyScore:m,confidenceScore:v,actionable:v>=this.config.minConfidence,applied:!1,suggestedAction:v>=this.config.minConfidence?`Merge "${this.truncate(r.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),a=this.graph.getConcept(n.target);if(!i||!a)continue;let r=this.graph.getEdge(n.source,n.target);if(r&&r.weight>.5)continue;let o=i.conceptType!==a.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,a,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(a.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},a=i.successRate,r=i.executionCount,o=i.confidence,s=a!==void 0&&a<.7,c=r!==void 0&&r>10,p=o!==void 0&&o<.6;if(s||c&&p){let d=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),l=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,a,r),noveltyScore:d,confidenceScore:l,actionable:l>=this.config.minConfidence,applied:!1,suggestedAction:l>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let a=i.conceptType??"pattern";n[a]||(n[a]=[]),n[a].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(a=>a.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ee().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),a=new Set(n),r=new Set(i),o=n.filter(c=>r.has(c)),s=a.size+r.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let a=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${a}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};H();k();$();import{existsSync as te,unlinkSync as ne}from"fs";var T={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},C=class{constructor(e,t=T){this.db=e;this.thresholds=t}activeBranches=new Map;listeners=[];rvfAdapter;useRvfFork=!1;_witnessChain=null;set witnessChain(e){this._witnessChain=e}setRvfAdapter(e,t=!0){this.rvfAdapter=e,this.useRvfFork=t,import("./feature-flags-ZJ42B4IL.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let a=`/tmp/dream-branch-${t}.rvf`,r=this.rvfAdapter.derive(a),o=i;o._rvfBranchPath=a,o._rvfChildAdapter=r}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),a=i.patternCount-n.patternCount,r=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-a/n.patternCount;d>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(d*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(r<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-r).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let d=o/n.highConfidenceCount;d>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(d*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let d=this.rvfAdapter.dimension?.()??384,l=new Float32Array(d);for(let m=0;m<d;m++)l[m]=Math.sin(m*.1);let u=this.rvfAdapter.search?.(l,10)??[];u.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${u.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let p=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:p,patternCountDelta:a,avgConfidenceDelta:r,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&te(n)&&ne(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var x=N.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...T}},z=class{constructor(e){this.graph=e}nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let a=(await this.graph.getNeighbors(n.id)).map(r=>r.edge);this.edgeCache.set(n.id,a)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let r of e)t[r.conceptType]=(t[r.conceptType]??0)+1,n+=this.activationLevels.get(r.id)??r.activationLevel;let i=0,a=Array.from(this.edgeCache.values());for(let r of a)i+=r.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},_=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=M(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.migrateSchema(),this.graph=new A,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new C(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${E(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),a=new Set(i.map(s=>s.name)),r=a.has("insight_type"),o=a.has("source_concepts");if(!r)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),x.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),x.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){x.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:y(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let a=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(a),this.emitBranchEvent("dream:branch_created",i)}try{let a=await this.graph.getActiveNodes(0);if(a.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${a.length} < ${this.config.minConceptsRequired}`);let r=new z(this.graph);await r.loadIntoMemory(30);let s=await new S(r,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await r.persistActivations();let p=await new I(r,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=p.length;for(let l of p)await this.saveInsight(l);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let l=this.branchManager.validateBranch(i);if(l.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,l);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,l);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:l.reason},"dream-engine")}catch{}x.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:l.reason})}i=null}let d={cycle:{...this.currentCycle},insights:p,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(a){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=E(a),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,a}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async ensureConceptsLoaded(){if(this.ensureInitialized(),(await this.graph.getActiveNodes(0)).length>=this.config.minConceptsRequired)return 0;let t=this.db.prepare(`SELECT id, name, description, qe_domain as domain, pattern_type as patternType,
|
|
62
|
+
`).run(s,e);a+=c.changes}return a})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,a=t.get().count,r={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)r[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:a,byType:r,avgEdgesPerNode:i>0?a/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?D(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function K(h){return new A(h)}J();function Z(h,e){if(e<0||e>=h.length)return h[0]??0;let t=0,n=h.length-1;for(;t<n;){let i=t+n>>1;if(h[i]<h[t]){let s=h[t];h[t]=h[i],h[i]=s}if(h[n]<h[t]){let s=h[t];h[t]=h[n],h[n]=s}if(h[i]<h[n]){let s=h[i];h[i]=h[n],h[n]=s}let a=h[n],r=t;for(let s=t;s<n;s++)if(h[s]<=a){let c=h[r];h[r]=h[s],h[s]=c,r++}let o=h[r];if(h[r]=h[n],h[n]=o,r===e)return h[r];r<e?t=r+1:n=r-1}return h[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},S=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(d=>this.graph.getConcept(d)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let d of i)this.graph.setActivation(d,t),this.recordActivation(d,t);let a=0,r=t,o=0,s=0;for(;a<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),l=this.graph.getActiveNodes(this.config.threshold);for(let u of l)u.activationLevel>r&&(r=u.activationLevel);if(l.length===o&&d===0){if(s++,s>=3)break}else s=0;o=l.length,a++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,l)=>l.activation-d.activation),p=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:a,nodesActivated:c.length,peakActivation:r,activatedNodes:c,novelAssociations:p.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,a=0,r=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let d=U(0,o.length),l=o[d];if(l){let u=this.config.noiseLevel+R()*this.config.noiseLevel*2,m=l.activationLevel,v=Math.min(1,m+u+.3);this.graph.setActivation(l.id,v);let f=await this.spread([l.id],v,s);i+=f.iterations,f.peakActivation>a&&(a=f.peakActivation);for(let b of f.activatedNodes)r.add(b.nodeId);for(let b of f.novelAssociations)n.push(b)}if(Date.now()>=s)break;await this.sleep(50+R()*50)}let c=this.deduplicateAssociations(n),p=Array.from(r).map(d=>{let l=this.graph.getConcept(d);return{nodeId:d,activation:l?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,l)=>l.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:p.length,peakActivation:a,activatedNodes:p,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((r,o)=>o.activationLevel-r.activationLevel).slice(0,i));let a=[];for(let r=0;r<n.length;r++)for(let o=r+1;o<n.length;o++){let s=n[r],c=n[o],p=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),l=this.graph.getEdge(c.id,s.id),u=d!==void 0||l!==void 0,m=d?.weight??l?.weight??0,v=!u||m<.3;p>.3&&(a.push({source:s,target:c,coActivation:p,isNovel:v}),this.trackCoActivation(s.id,c.id))}return a.sort((r,o)=>r.isNovel!==o.isNovel?r.isNovel?-1:1:o.coActivation-r.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=B)return;let e=Math.floor(B*F),t=this.activationHistory.size-e,n=Array.from(this.activationHistory.keys()).slice(0,t);for(let i of n)this.activationHistory.delete(i)}trimCoActivationCounts(){if(this.coActivationCounts.size<=O)return;let e=Math.floor(O*F),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=Z(n,t-1),a=[];for(let[r,o]of this.coActivationCounts){if(a.length>=t)break;o<=i&&a.push(r)}for(let r of a)this.coActivationCounts.delete(r)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let a=this.graph.getEdges(i.id);for(let r of a){let o=this.graph.getConcept(r.target);if(!o)continue;let s=i.activationLevel*r.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,p=Math.min(1,c+s);n.push({nodeId:r.target,newActivation:p})}}}for(let i of n){let a=this.graph.getConcept(i.nodeId);a&&i.newActivation>a.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(R()-.5)*2*this.config.noiseLevel,i=Math.max(0,Math.min(1,t.activationLevel+n));this.graph.setActivation(t.id,i)}}recordActivation(e,t){let n=this.activationHistory.get(e)||[];n.push(t),n.length>50&&n.shift(),this.activationHistory.set(e,n)}trackCoActivation(e,t){let n=[e,t].sort().join(":"),i=this.coActivationCounts.get(n)||0;this.coActivationCounts.set(n,i+1)}deduplicateAssociations(e){let t=new Map;for(let n of e){let i=[n.source,n.target].sort().join(":"),a=t.get(i);(!a||n.strength>a.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ee}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},I=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let a=await this.detectPatternMerges(i);for(let c of a)c.cycleId=e,n.push(c);let r=await this.detectNovelAssociations(t.novelAssociations);for(let c of r)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,p)=>p.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let a=i+1;a<n.length;a++){let r=n[i],o=n[a],s=this.graph.getEdge(r.id,o.id),c=this.graph.getEdge(o.id,r.id),p=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(r.content,o.content),l=Math.sqrt(r.activationLevel*o.activationLevel),u=p*.4+d*.3+l*.3;if(u>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[r.id,o.id]}),v=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[r.id,o.id],edgeWeight:p,contentSimilarity:d,coActivation:l});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[r.id,o.id],description:this.generatePatternMergeDescription(r,o,u),noveltyScore:m,confidenceScore:v,actionable:v>=this.config.minConfidence,applied:!1,suggestedAction:v>=this.config.minConfidence?`Merge "${this.truncate(r.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),a=this.graph.getConcept(n.target);if(!i||!a)continue;let r=this.graph.getEdge(n.source,n.target);if(r&&r.weight>.5)continue;let o=i.conceptType!==a.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,a,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(a.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},a=i.successRate,r=i.executionCount,o=i.confidence,s=a!==void 0&&a<.7,c=r!==void 0&&r>10,p=o!==void 0&&o<.6;if(s||c&&p){let d=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),l=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,a,r),noveltyScore:d,confidenceScore:l,actionable:l>=this.config.minConfidence,applied:!1,suggestedAction:l>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let a=i.conceptType??"pattern";n[a]||(n[a]=[]),n[a].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(a=>a.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ee().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),a=new Set(n),r=new Set(i),o=n.filter(c=>r.has(c)),s=a.size+r.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let a=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${a}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};H();k();$();import{existsSync as te,unlinkSync as ne}from"fs";var T={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},C=class{constructor(e,t=T){this.db=e;this.thresholds=t}activeBranches=new Map;listeners=[];rvfAdapter;useRvfFork=!1;_witnessChain=null;set witnessChain(e){this._witnessChain=e}setRvfAdapter(e,t=!0){this.rvfAdapter=e,this.useRvfFork=t,import("./feature-flags-AEO5C73R.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let a=`/tmp/dream-branch-${t}.rvf`,r=this.rvfAdapter.derive(a),o=i;o._rvfBranchPath=a,o._rvfChildAdapter=r}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),a=i.patternCount-n.patternCount,r=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-a/n.patternCount;d>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(d*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(r<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-r).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let d=o/n.highConfidenceCount;d>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(d*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let d=this.rvfAdapter.dimension?.()??384,l=new Float32Array(d);for(let m=0;m<d;m++)l[m]=Math.sin(m*.1);let u=this.rvfAdapter.search?.(l,10)??[];u.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${u.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let p=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:p,patternCountDelta:a,avgConfidenceDelta:r,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&te(n)&&ne(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var x=N.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...T}},z=class{constructor(e){this.graph=e}nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let a=(await this.graph.getNeighbors(n.id)).map(r=>r.edge);this.edgeCache.set(n.id,a)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let r of e)t[r.conceptType]=(t[r.conceptType]??0)+1,n+=this.activationLevels.get(r.id)??r.activationLevel;let i=0,a=Array.from(this.edgeCache.values());for(let r of a)i+=r.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},_=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=M(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.migrateSchema(),this.graph=new A,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new C(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${E(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),a=new Set(i.map(s=>s.name)),r=a.has("insight_type"),o=a.has("source_concepts");if(!r)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),x.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),x.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){x.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:y(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let a=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(a),this.emitBranchEvent("dream:branch_created",i)}try{let a=await this.graph.getActiveNodes(0);if(a.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${a.length} < ${this.config.minConceptsRequired}`);let r=new z(this.graph);await r.loadIntoMemory(30);let s=await new S(r,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await r.persistActivations();let p=await new I(r,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=p.length;for(let l of p)await this.saveInsight(l);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let l=this.branchManager.validateBranch(i);if(l.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,l);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,l);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:l.reason},"dream-engine")}catch{}x.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:l.reason})}i=null}let d={cycle:{...this.currentCycle},insights:p,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(a){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=E(a),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,a}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async ensureConceptsLoaded(){if(this.ensureInitialized(),(await this.graph.getActiveNodes(0)).length>=this.config.minConceptsRequired)return 0;let t=this.db.prepare(`SELECT id, name, description, qe_domain as domain, pattern_type as patternType,
|
|
63
63
|
confidence, success_rate as successRate
|
|
64
64
|
FROM qe_patterns
|
|
65
65
|
WHERE confidence >= 0.3
|
|
@@ -92,4 +92,4 @@ import{a as W}from"./chunk-MR5I6UR2.js";import{c as V,d as q}from"./chunk-QVZSIF
|
|
|
92
92
|
(id, cycle_id, insight_type, source_concepts, description, novelty_score,
|
|
93
93
|
confidence_score, actionable, applied, suggested_action, pattern_id)
|
|
94
94
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
95
|
-
`).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:D(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function ie(h){let e=new _(h);return import("./feature-flags-ZJ42B4IL.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-VCJNSACZ.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var re=_;$();var g=N.create("DreamScheduler"),Y={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},L=class h{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Y,...t},this.metaLearningEngine=new q}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,g.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),g.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),g.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,g.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(g.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{g.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,g.info("Starting dream cycle",{durationMs:e});try{let t=await this.dreamEngine.ensureConceptsLoaded();t>0&&g.info("Auto-loaded concepts for dream",{loaded:t});let n=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=n,this.totalDreamsCompleted++,this.clearExperienceBuffer(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(n),await this.publishDreamCompletedEvent(n),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(i){g.warn("Post-dream meta-learning failed (non-critical)",{error:i instanceof Error?i.message:String(i)})}return this.running&&this.scheduleNextDream(),g.info("Dream completed",{insightsGenerated:n.insights.length}),n}finally{this.dreaming=!1}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&g.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){g.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new W,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>h.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){g.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)g.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>h.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:y(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{g.debug("Failed to publish meta-learning insight event")}}}else g.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),g.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){g.info("Quality gate failed but cannot start dream yet");return}g.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){g.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){g.info("Milestone reached but cannot start dream yet");return}g.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:y(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){g.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){g.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],g.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){g.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function ae(h,e){return new L(h,e)}var se=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],G=class{constructor(e,t){this.db=e;this.branchManager=new C(e,t??T)}branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),a=[];for(let s of e){let c=await this.executeStrategy(s,i,t);a.push(c)}let r=a.filter(s=>s.validation.passed),o=null;if(r.length>0){o=r.reduce((c,p)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(p.validation)>d?p:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:a,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,a=this.branchManager.createBranch(i),r=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(a,t);return this.branchManager.discardBranch(a),{strategy:e,branch:a,validation:o,selected:!1,durationMs:Date.now()-r}}catch{return this.branchManager.discardBranch(a),{strategy:e,branch:a,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-r}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{P as a,A as b,K as c,B as d,O as e,F as f,j as g,S as h,Q as i,I as j,T as k,C as l,X as m,_ as n,ie as o,re as p,Y as q,L as r,ae as s,se as t,G as u};
|
|
95
|
+
`).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:D(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function ie(h){let e=new _(h);return import("./feature-flags-AEO5C73R.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-PNVIYEDK.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var re=_;$();var g=N.create("DreamScheduler"),Y={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},L=class h{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Y,...t},this.metaLearningEngine=new q}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,g.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),g.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),g.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,g.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(g.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{g.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,g.info("Starting dream cycle",{durationMs:e});try{let t=await this.dreamEngine.ensureConceptsLoaded();t>0&&g.info("Auto-loaded concepts for dream",{loaded:t});let n=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=n,this.totalDreamsCompleted++,this.clearExperienceBuffer(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(n),await this.publishDreamCompletedEvent(n),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(i){g.warn("Post-dream meta-learning failed (non-critical)",{error:i instanceof Error?i.message:String(i)})}return this.running&&this.scheduleNextDream(),g.info("Dream completed",{insightsGenerated:n.insights.length}),n}finally{this.dreaming=!1}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&g.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){g.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new W,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>h.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){g.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)g.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>h.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:y(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{g.debug("Failed to publish meta-learning insight event")}}}else g.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),g.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){g.info("Quality gate failed but cannot start dream yet");return}g.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){g.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){g.info("Milestone reached but cannot start dream yet");return}g.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:y(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){g.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){g.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],g.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){g.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function ae(h,e){return new L(h,e)}var se=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],G=class{constructor(e,t){this.db=e;this.branchManager=new C(e,t??T)}branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),a=[];for(let s of e){let c=await this.executeStrategy(s,i,t);a.push(c)}let r=a.filter(s=>s.validation.passed),o=null;if(r.length>0){o=r.reduce((c,p)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(p.validation)>d?p:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:a,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,a=this.branchManager.createBranch(i),r=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(a,t);return this.branchManager.discardBranch(a),{strategy:e,branch:a,validation:o,selected:!1,durationMs:Date.now()-r}}catch{return this.branchManager.discardBranch(a),{strategy:e,branch:a,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-r}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{P as a,A as b,K as c,B as d,O as e,F as f,j as g,S as h,Q as i,I as j,T as k,C as l,X as m,_ as n,ie as o,re as p,Y as q,L as r,ae as s,se as t,G as u};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as L}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.6");process.exit(0)}
|
|
2
|
+
import{a as L}from"./chunk-KI4W6CVC.js";import*as w from"fs";var R={"aqe test generate":{domain:"test-generation",action:"generateTests"},"aqe test execute":{domain:"test-execution",action:"execute"},"aqe coverage analyze":{domain:"coverage-analysis",action:"analyze"},"aqe coverage gaps":{domain:"coverage-analysis",action:"detectGaps"},"aqe quality gate":{domain:"quality-assessment",action:"evaluateGate"},"aqe quality assess":{domain:"quality-assessment",action:"analyzeQuality"},"aqe security scan":{domain:"security-compliance",action:"runSASTScan"},"aqe security audit":{domain:"security-compliance",action:"runAudit"},"aqe defect predict":{domain:"defect-intelligence",action:"predictDefects"},"aqe code index":{domain:"code-intelligence",action:"index"},"aqe code impact":{domain:"code-intelligence",action:"analyzeImpact"},"aqe contract validate":{domain:"contract-testing",action:"validateContract"},"aqe chaos test":{domain:"chaos-resilience",action:"runChaosTest"},"aqe requirements validate":{domain:"requirements-validation",action:"validateRequirements"},"aqe visual test":{domain:"visual-accessibility",action:"runVisualTest"},"aqe accessibility test":{domain:"visual-accessibility",action:"runAccessibilityTest"},"aqe learn optimize":{domain:"learning-optimization",action:"optimizeAllStrategies"}},D={daily:"0 0 * * *",weekly:"0 0 * * 0",hourly:"0 * * * *",minutely:"* * * * *"},S=1e4,x=20,M=1e4,W=["__proto__","constructor","prototype"];function v(t){return!W.includes(t)}function C(t){let n=t.split(`
|
|
3
3
|
`);if(n.length>S)throw new Error(`YAML content exceeds maximum allowed lines (${S}). File has ${n.length} lines.`);for(let i=0;i<n.length;i++)if(n[i].length>M)throw new Error(`YAML line ${i+1} exceeds maximum allowed length (${M} characters).`);let a={};for(let i=0;i<n.length;i++){let e=n[i];if(e.trim()===""||e.trim().startsWith("#")||e.search(/\S/)!==0)continue;let o=e.match(/^([\w_-]+):\s*(.+)$/);if(o){let[,c,u]=o;v(c)&&(a[c]=f(u))}}let r=["tags","stages","triggers"];for(let i of r){let e=new RegExp(`^${i}:\\s*$`),s=-1;for(let l=0;l<n.length;l++){let d=n[l];if(!(d.trim()===""||d.trim().startsWith("#"))&&e.test(d.trim())){s=l;break}}if(s===-1)continue;let o=[];a[i]=o;let c=n[s].search(/\S/),u=s+1;for(;u<n.length;){let l=n[u];if(l.trim()===""||l.trim().startsWith("#")){u++;continue}let d=l.search(/\S/),p=l.trim();if(d<=c&&!p.startsWith("-"))break;if(p.startsWith("- ")){let m=p.slice(2).trim();if(!m.includes(":")){o.push(f(m)),u++;continue}let g={},k=m.match(/^([\w_-]+):\s*(.*)$/);if(k){let[,h,y]=k;g[h]=f(y)}let T=d;for(u++;u<n.length;){let h=n[u];if(h.trim()===""||h.trim().startsWith("#")){u++;continue}let y=h.search(/\S/),q=h.trim();if(y<=T)break;let _=q.match(/^([\w_-]+):\s*(.*)$/);if(_){let[,A,$]=_;if($===""){let b=E(n,u+1,y,1);g[A]=b.value,u=b.nextLine;continue}else g[A]=f($)}u++}o.push(g)}else u++}}return a}function E(t,n,a,r=0){if(r>x)throw new Error(`YAML nesting exceeds maximum allowed depth (${x}).`);let i={},e=null,s=null,o=n;for(;o<t.length;){let u=t[o];if(u.trim()===""||u.trim().startsWith("#")){o++;continue}let l=u.search(/\S/),d=u.trim();if(l<=a)break;if(d.startsWith("- ")){let m=d.slice(2).trim();s&&!Array.isArray(i[s])&&(i[s]=[]),s?i[s].push(f(m)):(e||(e=[]),e.push(f(m))),o++;continue}let p=d.match(/^([\w_-]+):\s*(.*)$/);if(p){let[,m,g]=p;if(!v(m)){o++;continue}g===""?(s=m,i[m]=[]):(i[m]=f(g),s=null)}o++}if(e&&Object.keys(i).length===0)return{value:e,nextLine:o};let c=Object.keys(i);return c.length===1&&Array.isArray(i[c[0]])?{value:i[c[0]],nextLine:o}:{value:i,nextLine:o}}function f(t){if(t==="")return"";if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t==="true")return!0;if(t==="false")return!1;if(t==="null"||t==="~")return null;let n=Number(t);return!isNaN(n)&&t!==""?n:t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1).split(",").map(r=>f(r.trim())):t}function K(t){let n=[];if(!w.existsSync(t))return{success:!1,errors:[`File not found: ${t}`]};let a;try{a=w.readFileSync(t,"utf-8")}catch(r){return{success:!1,errors:[`Failed to read file: ${r}`]}}return Y(a,t)}function Y(t,n){let a=[],r;try{r=C(t)}catch(s){return{success:!1,errors:[`Invalid YAML syntax: ${s}`]}}if((!r.name||typeof r.name!="string")&&a.push('Pipeline must have a "name" field'),(!r.stages||!Array.isArray(r.stages))&&a.push('Pipeline must have a "stages" array'),a.length>0)return{success:!1,errors:a};let i={name:r.name,description:r.description,version:r.version||"1.0.0",schedule:r.schedule,stages:r.stages.map((s,o)=>{let c=s;return{name:c.name||`stage-${o}`,command:c.command,params:c.params,depends_on:c.depends_on,condition:c.condition,timeout:c.timeout,retry:c.retry,continue_on_failure:c.continue_on_failure}}),triggers:r.triggers,tags:r.tags,timeout:r.timeout};for(let s=0;s<i.stages.length;s++){let o=i.stages[s];o.command||a.push(`Stage ${s+1} (${o.name}) must have a "command" field`)}if(a.length>0)return{success:!1,pipeline:i,errors:a};let e=O(i,n);return{success:!0,pipeline:i,workflow:e,errors:[]}}function O(t,n){let a=`pipeline-${t.name.replace(/\s+/g,"-").toLowerCase()}`,r=t.stages.map((e,s)=>{let o=P(e.command),c={};if(e.params)for(let[l,d]of Object.entries(e.params))v(l)&&(c[l]=`input.${l}`);let u={id:`stage-${e.name.replace(/\s+/g,"-").toLowerCase()}`,name:e.name,domain:o.domain,action:o.action,inputMapping:Object.keys(c).length>0?c:void 0,dependsOn:e.depends_on?.map(l=>`stage-${l.replace(/\s+/g,"-").toLowerCase()}`),timeout:e.timeout?e.timeout*1e3:void 0,continueOnFailure:e.continue_on_failure};return e.condition&&(u.condition={path:e.condition.path,operator:e.condition.operator,value:e.condition.value}),e.retry&&(u.retry={maxAttempts:e.retry.max_attempts||3,backoffMs:(e.retry.backoff_seconds||1)*1e3}),u}),i=t.triggers?.map(e=>{let s={eventType:I(e),sourceDomain:e.source_domain};return e.condition&&(s.condition={path:e.condition.path,operator:e.condition.operator,value:e.condition.value}),s});return{id:a,name:t.name,description:t.description||`Pipeline from ${n||"inline YAML"}`,version:t.version||"1.0.0",steps:r,triggers:i,tags:t.tags,timeout:t.timeout?t.timeout*1e3:void 0}}function P(t){let n=t.trim().replace(/\s+/g," ").toLowerCase();for(let[a,r]of Object.entries(R))if(n.startsWith(a.toLowerCase()))return r;return n.includes("test")&&n.includes("generate")?{domain:"test-generation",action:"generateTests"}:n.includes("test")&&(n.includes("execute")||n.includes("run"))?{domain:"test-execution",action:"execute"}:n.includes("coverage")?{domain:"coverage-analysis",action:"analyze"}:n.includes("quality")||n.includes("gate")?{domain:"quality-assessment",action:"evaluateGate"}:n.includes("security")||n.includes("scan")?{domain:"security-compliance",action:"runSASTScan"}:n.includes("defect")||n.includes("predict")?{domain:"defect-intelligence",action:"predictDefects"}:{domain:"learning-optimization",action:"runLearningCycle"}}function I(t){let n=t.event.toLowerCase();return n==="push"?"code-intelligence.CodePushed":n==="pull_request"||n==="pr"?"code-intelligence.PullRequestOpened":n==="schedule"?"workflow.ScheduleTrigger":n==="quality_gate"?"quality-assessment.QualityGateEvaluated":n==="test_complete"?"test-execution.TestRunCompleted":n}function F(t){let n=[],a=[];if(t.name||n.push({path:"name",message:"Pipeline name is required",severity:"error"}),!t.stages||t.stages.length===0)n.push({path:"stages",message:"Pipeline must have at least one stage",severity:"error"});else{let r=new Set;for(let e=0;e<t.stages.length;e++){let s=t.stages[e],o=`stages[${e}]`;if(r.has(s.name)&&n.push({path:`${o}.name`,message:`Duplicate stage name: ${s.name}`,severity:"error"}),r.add(s.name),s.command?P(s.command).domain==="learning-optimization"&&!s.command.toLowerCase().includes("learn")&&a.push({path:`${o}.command`,message:`Command "${s.command}" not recognized, will default to learning-optimization domain`,severity:"warning"}):n.push({path:`${o}.command`,message:"Stage must have a command",severity:"error"}),s.depends_on)for(let c of s.depends_on)t.stages.some(u=>u.name===c)||n.push({path:`${o}.depends_on`,message:`Unknown dependency: ${c}`,severity:"error"});s.timeout!==void 0&&s.timeout<=0&&n.push({path:`${o}.timeout`,message:"Timeout must be a positive number",severity:"error"}),s.retry&&s.retry.max_attempts!==void 0&&s.retry.max_attempts<1&&n.push({path:`${o}.retry.max_attempts`,message:"max_attempts must be at least 1",severity:"error"})}let i=N(t.stages);i&&n.push({path:"stages",message:`Circular dependency detected: ${i}`,severity:"error"})}if(t.schedule&&(z(t.schedule)||n.push({path:"schedule",message:`Invalid cron expression: ${t.schedule}`,severity:"error"})),t.triggers)for(let r=0;r<t.triggers.length;r++){let i=t.triggers[r],e=`triggers[${r}]`;i.event||n.push({path:`${e}.event`,message:"Trigger must have an event type",severity:"error"}),i.source_domain&&!L.includes(i.source_domain)&&a.push({path:`${e}.source_domain`,message:`Unknown domain: ${i.source_domain}`,severity:"warning"})}return{valid:n.length===0,errors:n,warnings:a}}function N(t){let n=new Set,a=new Set,r=(i,e)=>{if(a.has(i))return[...e,i].join(" -> ");if(n.has(i))return null;n.add(i),a.add(i);let s=t.find(o=>o.name===i);if(s?.depends_on)for(let o of s.depends_on){let c=r(o,[...e,i]);if(c)return c}return a.delete(i),null};for(let i of t){let e=r(i.name,[]);if(e)return e}return null}function z(t){if(Object.keys(D).includes(t))return!0;let n=t.trim().split(/\s+/);if(n.length!==5)return!1;let a=[/^(\*|[0-5]?\d)(-[0-5]?\d)?(\/\d+)?$/,/^(\*|1?\d|2[0-3])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|[12]\d|3[01])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|1[0-2])(-\d+)?(\/\d+)?$/,/^(\*|[0-7])(-[0-7])?(\/\d+)?$/];for(let r=0;r<5;r++){let i=n[r].split(",");for(let e of i)if(!a[r].test(e)&&e!=="*")return!1}return!0}function G(t){let n={"@daily":"Daily at midnight","@weekly":"Weekly on Sunday at midnight","@hourly":"Every hour","@minutely":"Every minute"};if(n[t])return n[t];if(Object.keys(D).includes(t))return{daily:"Daily at midnight",weekly:"Weekly on Sunday at midnight",hourly:"Every hour",minutely:"Every minute"}[t]||t;let a=t.trim().split(/\s+/);if(a.length!==5)return t;let[r,i,e,s,o]=a;return r==="0"&&i==="0"&&e==="*"&&s==="*"&&o==="*"?"Daily at midnight":r==="0"&&e==="*"&&s==="*"&&o==="*"?`Daily at ${i}:00`:r!=="*"&&i!=="*"&&e==="*"&&s==="*"?`Daily at ${i}:${r.padStart(2,"0")}`:i==="*"&&r==="0"?"Every hour":r!=="*"&&i==="*"?`Every hour at minute ${r}`:t}function H(t,n=new Date){let a=t.trim().split(/\s+/);if(a.length!==5)return new Date(n.getTime()+1440*60*1e3);let[r,i]=a,e=new Date(n);return i!=="*"&&r!=="*"?(e.setHours(parseInt(i,10),parseInt(r,10),0,0),e<=n&&e.setDate(e.getDate()+1)):i!=="*"?(e.setHours(parseInt(i,10),0,0,0),e<=n&&e.setDate(e.getDate()+1)):r!=="*"?(e.setMinutes(parseInt(r,10),0,0),e<=n&&e.setHours(e.getHours()+1)):(e.setSeconds(0,0),e.setMinutes(e.getMinutes()+1)),e}export{C as a,K as b,F as c,G as d,H as e};
|
|
@@ -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.9.
|
|
2
|
-
import{a as ne}from"./chunk-
|
|
3
|
-
`)}var pt=(function(n){lt(e,n);function e(t,r,i,s,a){var c=this.constructor,l=n.call(this,He(t,{name:r,index:i,operation:s,tree:a}))||this;return l.name=r,l.index=i,l.operation=s,l.tree=a,Object.setPrototypeOf(l,c.prototype),l.message=He(t,{name:r,index:i,operation:s,tree:a}),l}return e})(Error);S.PatchError=pt});var he=J(p=>{Object.defineProperty(p,"__esModule",{value:!0});var b=Y();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=K(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=K(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:q(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},gt={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 K(n,e){if(e=="")return n;var t={op:"_get",path:e};return I(n,t),t.value}p.getValueByPointer=K;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):V(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=K(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=q(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||"",l=c.split("/"),o=n,u=1,h=l.length,f=void 0,d=void 0,m=void 0;for(typeof t=="function"?m=t:m=V;;){if(d=l[u],d&&d.indexOf("~")!=-1&&(d=b.unescapePathComponent(d)),i&&(d=="__proto__"||d=="prototype"&&u>0&&l[u-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=l.slice(0,u).join("/"):u==h-1&&(f=e.path),f!==void 0&&m(e,0,n,f)),u++,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(u>=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=gt[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(u>=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&&u<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 Le(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=Le;function yt(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=yt;function V(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=ke([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=V;function ke(n,e,t){try{if(!Array.isArray(n))throw new p.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Le(b._deepClone(e),b._deepClone(n),t||!0);else{t=t||V;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=ke;function q(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(!q(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],!q(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}p._areEquals=q});var Ue=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var w=Y(),vt=he(),fe=new WeakMap,Pt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),wt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function St(n){return fe.get(n)}function bt(n,e){return n.observers.get(e)}function Et(n,e){n.observers.delete(e.callback)}function Tt(n,e){e.unobserve()}k.unobserve=Tt;function Rt(n,e){var t=[],r,i=St(n);if(!i)i=new Pt(n),fe.set(n,i);else{var s=bt(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=w._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),Et(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 wt(e,r)),r}k.observe=Rt;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&&vt.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=w._objectKeys(e),a=w._objectKeys(n),c=!1,l=!1,o=a.length-1;o>=0;o--){var u=a[o],h=n[u];if(w.hasOwnProperty(e,u)&&!(e[u]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var f=e[u];typeof h=="object"&&h!=null&&typeof f=="object"&&f!=null&&Array.isArray(h)===Array.isArray(f)?me(h,f,t,r+"/"+w.escapePathComponent(u),i):h!==f&&(c=!0,i&&t.push({op:"test",path:r+"/"+w.escapePathComponent(u),value:w._deepClone(h)}),t.push({op:"replace",path:r+"/"+w.escapePathComponent(u),value:w._deepClone(f)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+w.escapePathComponent(u),value:w._deepClone(h)}),t.push({op:"remove",path:r+"/"+w.escapePathComponent(u)}),l=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!l&&s.length==a.length))for(var o=0;o<s.length;o++){var u=s[o];!w.hasOwnProperty(n,u)&&e[u]!==void 0&&t.push({op:"add",path:r+"/"+w.escapePathComponent(u),value:w._deepClone(e[u])})}}}function At(n,e,t){t===void 0&&(t=!1);var r=[];return me(n,e,r,"",t),r}k.compare=At});var Qe=J(O=>{var xt=he();Object.assign(O,xt);var Ct=Ue();Object.assign(O,Ct);var Z=Y();O.JsonPatchError=Z.PatchError;O.deepClone=Z._deepClone;O.escapePathComponent=Z.escapePathComponent;O.unescapePathComponent=Z.unescapePathComponent});Re();var z=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??X,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}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-HMXYD56G.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}}}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 P(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return P(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{this.sqliteStore.storePattern(e,e.embedding)}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):P(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),l=this.adapter.search(c,i*2);for(let o of l){let u=await this.get(o.id);if(u&&this.matchesFilters(u,t)){let h=this.calculateReuseInfo(u,o.score);s.push({pattern:u,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}),l=e,o=Math.sqrt(l.reduce((u,h)=>u+h*h,0));if(o>0)for(let u of c){if(!this.matchesFilters(u,t))continue;let h=this.sqliteStore.getPattern(u.id),f=h?.embedding;if(!f||f.length!==l.length)continue;let d=0,m=0;for(let T=0;T<l.length;T++)d+=l[T]*f[T],m+=f[T]*f[T];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}),l=new Set(s.map(o=>o.pattern.id));for(let o of c){if(l.has(o.id)||!this.matchesFilters(o,t))continue;let u=this.calculateReuseInfo(o,o.confidence);s.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,i*2),l=new Set(s.map(o=>o.pattern.id));for(let o of c){if(l.has(o.id))continue;let u=await this.get(o.id);if(u&&this.matchesFilters(u,t)){let h=this.calculateReuseInfo(u,o.ftsScore);s.push({pattern:u,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch{}s.sort((c,l)=>l.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 P(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t),v(void 0)}catch(r){return P(new Error(`recordUsage failed: ${y(r)}`))}}async promote(e){if(!this.sqliteStore)return P(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),v(void 0)}catch(t){return P(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 P(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}}};Ve();Re();F();function rt(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 nt(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=rt(n,e.field);return nt(t,e.operator,e.value)}default:return!0}}function Ce(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var Fe=1e4,Ie=2166136261;function Oe(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 De="0123456789abcdef";function it(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=De[i>>4]+De[i&15]}return t}function st(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 at(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,l=1<<a;for(let o=0;o<n.length;o++)n[o][i]&l&&c++;c>=r&&(s|=l)}t[i]=s}return t}function ot(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 ct(n,e,t){return 1-ot(n,e,t)}var ie=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Fe,this.baseSeed=e?.seed??Ie,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=Oe(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=st(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 at([r,i])}similarity(e,t){return ct(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 l=0;l<c;l++)t[i++]=a>>>l*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??Fe,this.baseSeed=e?.seed??Ie,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=Oe(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:it(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(),l=t-s,o=l<4?l:4;for(let u=0;u<o;u++)r[s++]=c>>>u*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function _e(n){return new se(n)}function Ne(n){return Q()?new ie(n):null}var $=Ye(Qe(),1),Dt=`
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.6");process.exit(0)}
|
|
2
|
+
import{a as ne}from"./chunk-O65ZAUG3.js";import{d as B,e as j,f as re,g as W}from"./chunk-H4J456F2.js";import{c as Ze,d as et}from"./chunk-AJX44TJ7.js";import{a as Ae,d as xe,f as Ve}from"./chunk-EMKI4ZV5.js";import{b as v,c as P}from"./chunk-KI4W6CVC.js";import{a as y,b as Te,c as Re}from"./chunk-Z5IOTEQI.js";import{f as C}from"./chunk-3VBPPW7H.js";import{B as Q,D as H,G as te,P as M,S as F,b as D}from"./chunk-NSRIYP76.js";import{a as Ee,d as J,f as Ye,g as Ke}from"./chunk-N5CEEWWJ.js";var Y=J(S=>{var lt=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 ut=Object.prototype.hasOwnProperty;function le(n,e){return ut.call(n,e)}S.hasOwnProperty=le;function Me(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=Me;function ht(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}S._deepClone=ht;function dt(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=dt;function oe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}S.escapePathComponent=oe;function ft(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}S.unescapePathComponent=ft;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 mt(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=mt;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=Me(n),i=r.length,s=0;s<i;s++)if(ce(n[r[s]]))return!0}}return!1}S.hasUndefined=ce;function He(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 pt=(function(n){lt(e,n);function e(t,r,i,s,a){var c=this.constructor,l=n.call(this,He(t,{name:r,index:i,operation:s,tree:a}))||this;return l.name=r,l.index=i,l.operation=s,l.tree=a,Object.setPrototypeOf(l,c.prototype),l.message=He(t,{name:r,index:i,operation:s,tree:a}),l}return e})(Error);S.PatchError=pt});var he=J(p=>{Object.defineProperty(p,"__esModule",{value:!0});var b=Y();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=K(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=K(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:q(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},gt={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 K(n,e){if(e=="")return n;var t={op:"_get",path:e};return I(n,t),t.value}p.getValueByPointer=K;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):V(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=K(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=q(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||"",l=c.split("/"),o=n,u=1,h=l.length,f=void 0,d=void 0,m=void 0;for(typeof t=="function"?m=t:m=V;;){if(d=l[u],d&&d.indexOf("~")!=-1&&(d=b.unescapePathComponent(d)),i&&(d=="__proto__"||d=="prototype"&&u>0&&l[u-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=l.slice(0,u).join("/"):u==h-1&&(f=e.path),f!==void 0&&m(e,0,n,f)),u++,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(u>=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=gt[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(u>=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&&u<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 Le(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=Le;function yt(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=yt;function V(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=ke([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=V;function ke(n,e,t){try{if(!Array.isArray(n))throw new p.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Le(b._deepClone(e),b._deepClone(n),t||!0);else{t=t||V;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=ke;function q(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(!q(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],!q(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}p._areEquals=q});var Ue=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var w=Y(),vt=he(),fe=new WeakMap,Pt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),wt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function St(n){return fe.get(n)}function bt(n,e){return n.observers.get(e)}function Et(n,e){n.observers.delete(e.callback)}function Tt(n,e){e.unobserve()}k.unobserve=Tt;function Rt(n,e){var t=[],r,i=St(n);if(!i)i=new Pt(n),fe.set(n,i);else{var s=bt(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=w._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),Et(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 wt(e,r)),r}k.observe=Rt;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&&vt.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=w._objectKeys(e),a=w._objectKeys(n),c=!1,l=!1,o=a.length-1;o>=0;o--){var u=a[o],h=n[u];if(w.hasOwnProperty(e,u)&&!(e[u]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var f=e[u];typeof h=="object"&&h!=null&&typeof f=="object"&&f!=null&&Array.isArray(h)===Array.isArray(f)?me(h,f,t,r+"/"+w.escapePathComponent(u),i):h!==f&&(c=!0,i&&t.push({op:"test",path:r+"/"+w.escapePathComponent(u),value:w._deepClone(h)}),t.push({op:"replace",path:r+"/"+w.escapePathComponent(u),value:w._deepClone(f)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+w.escapePathComponent(u),value:w._deepClone(h)}),t.push({op:"remove",path:r+"/"+w.escapePathComponent(u)}),l=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!l&&s.length==a.length))for(var o=0;o<s.length;o++){var u=s[o];!w.hasOwnProperty(n,u)&&e[u]!==void 0&&t.push({op:"add",path:r+"/"+w.escapePathComponent(u),value:w._deepClone(e[u])})}}}function At(n,e,t){t===void 0&&(t=!1);var r=[];return me(n,e,r,"",t),r}k.compare=At});var Qe=J(O=>{var xt=he();Object.assign(O,xt);var Ct=Ue();Object.assign(O,Ct);var Z=Y();O.JsonPatchError=Z.PatchError;O.deepClone=Z._deepClone;O.escapePathComponent=Z.escapePathComponent;O.unescapePathComponent=Z.unescapePathComponent});Re();var z=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??X,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}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-XBTALZ2S.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}}}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 P(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return P(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{this.sqliteStore.storePattern(e,e.embedding)}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):P(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),l=this.adapter.search(c,i*2);for(let o of l){let u=await this.get(o.id);if(u&&this.matchesFilters(u,t)){let h=this.calculateReuseInfo(u,o.score);s.push({pattern:u,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}),l=e,o=Math.sqrt(l.reduce((u,h)=>u+h*h,0));if(o>0)for(let u of c){if(!this.matchesFilters(u,t))continue;let h=this.sqliteStore.getPattern(u.id),f=h?.embedding;if(!f||f.length!==l.length)continue;let d=0,m=0;for(let T=0;T<l.length;T++)d+=l[T]*f[T],m+=f[T]*f[T];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}),l=new Set(s.map(o=>o.pattern.id));for(let o of c){if(l.has(o.id)||!this.matchesFilters(o,t))continue;let u=this.calculateReuseInfo(o,o.confidence);s.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,i*2),l=new Set(s.map(o=>o.pattern.id));for(let o of c){if(l.has(o.id))continue;let u=await this.get(o.id);if(u&&this.matchesFilters(u,t)){let h=this.calculateReuseInfo(u,o.ftsScore);s.push({pattern:u,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch{}s.sort((c,l)=>l.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 P(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t),v(void 0)}catch(r){return P(new Error(`recordUsage failed: ${y(r)}`))}}async promote(e){if(!this.sqliteStore)return P(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),v(void 0)}catch(t){return P(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 P(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}}};Ve();Re();F();function rt(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 nt(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=rt(n,e.field);return nt(t,e.operator,e.value)}default:return!0}}function Ce(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var Fe=1e4,Ie=2166136261;function Oe(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 De="0123456789abcdef";function it(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=De[i>>4]+De[i&15]}return t}function st(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 at(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,l=1<<a;for(let o=0;o<n.length;o++)n[o][i]&l&&c++;c>=r&&(s|=l)}t[i]=s}return t}function ot(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 ct(n,e,t){return 1-ot(n,e,t)}var ie=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Fe,this.baseSeed=e?.seed??Ie,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=Oe(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=st(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 at([r,i])}similarity(e,t){return ct(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 l=0;l<c;l++)t[i++]=a>>>l*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??Fe,this.baseSeed=e?.seed??Ie,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=Oe(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:it(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(),l=t-s,o=l<4?l:4;for(let u=0;u<o;u++)r[s++]=c>>>u*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function _e(n){return new se(n)}function Ne(n){return Q()?new ie(n):null}var $=Ye(Qe(),1),Dt=`
|
|
4
4
|
CREATE TABLE IF NOT EXISTS pattern_deltas (
|
|
5
5
|
id TEXT PRIMARY KEY,
|
|
6
6
|
pattern_id TEXT NOT NULL,
|
|
@@ -46,7 +46,7 @@ import{a as ne}from"./chunk-EZTUUOVI.js";import{d as B,e as j,f as re,g as W}fro
|
|
|
46
46
|
WHERE pattern_id = ? AND version != 0
|
|
47
47
|
ORDER BY version ASC
|
|
48
48
|
LIMIT ?
|
|
49
|
-
)`).run(e,e,s)}}};F();var It={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={...It,...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),l={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(l),this.buffer.push(l),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:l.timestamp}),this.enforceRetention(e),l}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],l=a.version+1;for(let o of r)if(!(o.version<l)){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),l=a.findIndex(h=>h.deltaType==="genesis");l>=0&&(c.unshift(a[l]),a.splice(l,1)),this.history.set(e,c);let o=c[0]?.version??0,u=this.snapshots.get(e);return u&&this.snapshots.set(e,u.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 $e(n){return H()?new pe(n):null}F();var Ot=128,_t=8,Nt=1e4,ge=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Ot,this.beta=e?.beta??_t,this.maxPatterns=e?.maxPatterns??Nt,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 u=0;u<this.patterns.length;u++)r[u]=this.beta*this.dotProduct(this.patterns[u].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let u=1;u<i.length;u++)i[u]>a&&(a=i[u],s=u);let c=this.patterns[s],l=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:l,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)),l=this.dotProduct(t,t);return-c+.5*l}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 Je(n){return new ge(n)}F();var Ht={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,Be=1-_;function Mt(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 Lt(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 A=class n{static poincareDistance(e,t){let r=R(Lt(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=Mt(e,t),i=R(e),s=R(t),a=Math.max(_,1+2*r+i*s),c=1+2*r+s,l=1-i,o=new Float32Array(e.length);for(let u=0;u<e.length;u++)o[u]=(c*e[u]+l*t[u])/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<=Be)return new Float32Array(e);let r=Be/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={...Ht,...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:A.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=A.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:A.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 l of e)if(s.set(l.id,l),!l.parentId)a.push(l.id);else{let o=i.get(l.parentId);o||(o=[],i.set(l.parentId,o)),o.push(l.id)}let c=a.map((l,o)=>({id:l,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:l,depth:o,angOff:u,angSpan:h}=c.shift(),f=Math.tanh(.3*(o+.1)),d=u+h/2,m=new Float32Array(r);m[0]=f*Math.cos(d),m[1]=f*Math.sin(d);let g=s.get(l);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=A.project(m);t.set(l,E),this.points.set(l,{id:l,coordinates:E,metadata:{depth:o,parentId:g?.parentId}});let T=i.get(l)??[];for(let N=0;N<T.length;N++){let x=h/Math.max(1,T.length);c.push({id:T[N],depth:o+1,angOff:u+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function je(n){return kt()?new ye(n):null}function kt(){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=je(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=A.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=A.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 We(n){return new ve(n)}var Pe=null;function Xe(){return Pe||(Pe=_e({dimensions:1e4})),Pe}var we;function Ut(){return we===void 0&&(we=Ne()),we}var U=null,Se=0;function Ge(n){return(!U||Se!==n)&&(U=Je({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}}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-AYTRT54U.js"),{HnswAdapter:c}=await import("./hnsw-adapter-BASJNTEV.js"),l=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(l),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)");return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-NFN2AUIX.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));if(await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),this.sqliteStore)try{let a=this.sqliteStore.getAllEmbeddings(),c=this.config.hnsw.maxElements,l=0;for(let{patternId:o,embedding:u}of a){if(l>=c)break;if(!u||u.length!==this.config.embeddingDimension)continue;let h=this.patternCache.get(o);if(h)try{await this.hnswIndex.insert(o,u,{filePath:h.patternType,lineCoverage:h.confidence*100,branchCoverage:h.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-h.confidence,lastUpdated:Date.now(),totalLines:0}),l++}catch{}}l>0&&console.log(`[PatternStore] Loaded ${l} embeddings from SQLite into HNSW`)}catch(a){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",y(a))}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}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=$e()),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 P(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return P(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=Xe().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=Ut();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{Ge(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):P(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=Ge(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 l=s;t.filter&&(l=Ce(s,t.filter));let o=l.slice(0,i),u=performance.now()-r;return this.recordSearchLatency(u),v(o)}catch(a){return P(Te(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 l=Xe(),o=l.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),u=c.filter(d=>this.hdcCache.has(d)).map(d=>({id:d,similarity:l.similarity(o.vector,this.hdcCache.get(d))}));u.sort((d,m)=>m.similarity-d.similarity);let h=u.map(d=>d.id),f=c.filter(d=>!this.hdcCache.has(d));c=[...h,...f]}catch{}for(let l of c){if(i.length>=r)break;let o=this.patternCache.get(l);if(!o||!this.matchesFilters(o,t))continue;let u=0;if(s){let h=o.name.toLowerCase(),f=o.description.toLowerCase();h.includes(s)&&(u+=.5),f.includes(s)&&(s.length/f.length>.3?u+=.5:u+=.3);for(let d of o.context.tags)if(d.toLowerCase().includes(s)){u+=.2;break}u=Math.min(u,1)}else u=o.qualityScore;if(u>0||!s){let h=this.calculateReuseInfo(o,u);i.push({pattern:o,score:u||o.qualityScore,matchType:s?"exact":"context",similarity:u||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(),l=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&l,u=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:u,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 P(new Error(`Pattern not found: ${e}`));let i=new Date,s=r.usageCount+1,a=r.successfulUses+(t?1:0),c=a/s,l=t?.02:-.01,o=Math.max(.1,Math.min(1,r.confidence+l)),u=B({confidence:o,usageCount:s,successRate:c}),h={...r,usageCount:s,successfulUses:a,successRate:c,confidence:o,qualityScore:u,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 P(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 P(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[l,o]of this.domainIndex)e[l]=o.size;for(let[l,o]of this.typeIndex)t[l]=o.size;let r=0,i=0,s=0,a=0;for(let l of this.patternCache.values())r+=l.confidence,i+=l.qualityScore,s+=l.successRate,a++;let c=this.hnswIndex!==null?await this.hnswIndex.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:c.nativeHNSW,vectorCount:c.vectorCount,indexSizeBytes:c.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 l=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-l,u=o>10080*60*1e3,h=s.qualityScore<.2,f=s.usageCount===0&&o>1440*60*1e3;(u&&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=We({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),l=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.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&&xe()){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:l}=(et(),Ke(Ze)),o=l(s,a.embeddingDimension);if(o){c=!0;let u=new z(()=>o,{rvfPath:i,base:a,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),u}}catch{}if(!c){let l=new z((o,u)=>Ae(o,u),{rvfPath:i,base:a});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{Lr as a};
|
|
49
|
+
)`).run(e,e,s)}}};F();var It={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={...It,...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),l={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(l),this.buffer.push(l),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:l.timestamp}),this.enforceRetention(e),l}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],l=a.version+1;for(let o of r)if(!(o.version<l)){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),l=a.findIndex(h=>h.deltaType==="genesis");l>=0&&(c.unshift(a[l]),a.splice(l,1)),this.history.set(e,c);let o=c[0]?.version??0,u=this.snapshots.get(e);return u&&this.snapshots.set(e,u.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 $e(n){return H()?new pe(n):null}F();var Ot=128,_t=8,Nt=1e4,ge=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Ot,this.beta=e?.beta??_t,this.maxPatterns=e?.maxPatterns??Nt,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 u=0;u<this.patterns.length;u++)r[u]=this.beta*this.dotProduct(this.patterns[u].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let u=1;u<i.length;u++)i[u]>a&&(a=i[u],s=u);let c=this.patterns[s],l=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:l,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)),l=this.dotProduct(t,t);return-c+.5*l}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 Je(n){return new ge(n)}F();var Ht={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,Be=1-_;function Mt(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 Lt(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 A=class n{static poincareDistance(e,t){let r=R(Lt(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=Mt(e,t),i=R(e),s=R(t),a=Math.max(_,1+2*r+i*s),c=1+2*r+s,l=1-i,o=new Float32Array(e.length);for(let u=0;u<e.length;u++)o[u]=(c*e[u]+l*t[u])/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<=Be)return new Float32Array(e);let r=Be/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={...Ht,...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:A.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=A.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:A.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 l of e)if(s.set(l.id,l),!l.parentId)a.push(l.id);else{let o=i.get(l.parentId);o||(o=[],i.set(l.parentId,o)),o.push(l.id)}let c=a.map((l,o)=>({id:l,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:l,depth:o,angOff:u,angSpan:h}=c.shift(),f=Math.tanh(.3*(o+.1)),d=u+h/2,m=new Float32Array(r);m[0]=f*Math.cos(d),m[1]=f*Math.sin(d);let g=s.get(l);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=A.project(m);t.set(l,E),this.points.set(l,{id:l,coordinates:E,metadata:{depth:o,parentId:g?.parentId}});let T=i.get(l)??[];for(let N=0;N<T.length;N++){let x=h/Math.max(1,T.length);c.push({id:T[N],depth:o+1,angOff:u+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function je(n){return kt()?new ye(n):null}function kt(){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=je(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=A.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=A.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 We(n){return new ve(n)}var Pe=null;function Xe(){return Pe||(Pe=_e({dimensions:1e4})),Pe}var we;function Ut(){return we===void 0&&(we=Ne()),we}var U=null,Se=0;function Ge(n){return(!U||Se!==n)&&(U=Je({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}}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-5BYAJDVC.js"),{HnswAdapter:c}=await import("./hnsw-adapter-2SFTC2VH.js"),l=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(l),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)");return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-OBEYJRMU.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));if(await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),this.sqliteStore)try{let a=this.sqliteStore.getAllEmbeddings(),c=this.config.hnsw.maxElements,l=0;for(let{patternId:o,embedding:u}of a){if(l>=c)break;if(!u||u.length!==this.config.embeddingDimension)continue;let h=this.patternCache.get(o);if(h)try{await this.hnswIndex.insert(o,u,{filePath:h.patternType,lineCoverage:h.confidence*100,branchCoverage:h.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-h.confidence,lastUpdated:Date.now(),totalLines:0}),l++}catch{}}l>0&&console.log(`[PatternStore] Loaded ${l} embeddings from SQLite into HNSW`)}catch(a){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",y(a))}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}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=$e()),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 P(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return P(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=Xe().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=Ut();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{Ge(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):P(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=Ge(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 l=s;t.filter&&(l=Ce(s,t.filter));let o=l.slice(0,i),u=performance.now()-r;return this.recordSearchLatency(u),v(o)}catch(a){return P(Te(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 l=Xe(),o=l.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),u=c.filter(d=>this.hdcCache.has(d)).map(d=>({id:d,similarity:l.similarity(o.vector,this.hdcCache.get(d))}));u.sort((d,m)=>m.similarity-d.similarity);let h=u.map(d=>d.id),f=c.filter(d=>!this.hdcCache.has(d));c=[...h,...f]}catch{}for(let l of c){if(i.length>=r)break;let o=this.patternCache.get(l);if(!o||!this.matchesFilters(o,t))continue;let u=0;if(s){let h=o.name.toLowerCase(),f=o.description.toLowerCase();h.includes(s)&&(u+=.5),f.includes(s)&&(s.length/f.length>.3?u+=.5:u+=.3);for(let d of o.context.tags)if(d.toLowerCase().includes(s)){u+=.2;break}u=Math.min(u,1)}else u=o.qualityScore;if(u>0||!s){let h=this.calculateReuseInfo(o,u);i.push({pattern:o,score:u||o.qualityScore,matchType:s?"exact":"context",similarity:u||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(),l=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&l,u=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:u,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 P(new Error(`Pattern not found: ${e}`));let i=new Date,s=r.usageCount+1,a=r.successfulUses+(t?1:0),c=a/s,l=t?.02:-.01,o=Math.max(.1,Math.min(1,r.confidence+l)),u=B({confidence:o,usageCount:s,successRate:c}),h={...r,usageCount:s,successfulUses:a,successRate:c,confidence:o,qualityScore:u,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 P(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 P(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[l,o]of this.domainIndex)e[l]=o.size;for(let[l,o]of this.typeIndex)t[l]=o.size;let r=0,i=0,s=0,a=0;for(let l of this.patternCache.values())r+=l.confidence,i+=l.qualityScore,s+=l.successRate,a++;let c=this.hnswIndex!==null?await this.hnswIndex.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:c.nativeHNSW,vectorCount:c.vectorCount,indexSizeBytes:c.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 l=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-l,u=o>10080*60*1e3,h=s.qualityScore<.2,f=s.usageCount===0&&o>1440*60*1e3;(u&&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=We({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),l=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.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&&xe()){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:l}=(et(),Ke(Ze)),o=l(s,a.embeddingDimension);if(o){c=!0;let u=new z(()=>o,{rvfPath:i,base:a,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),u}}catch{}if(!c){let l=new z((o,u)=>Ae(o,u),{rvfPath:i,base:a});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{Lr as a};
|
|
50
50
|
/*! Bundled license information:
|
|
51
51
|
|
|
52
52
|
fast-json-patch/commonjs/helpers.js:
|