agentic-qe 3.11.3 → 3.11.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/hooks/aqe-hook.cjs +44 -10
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +106 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/audit/witness-chain.d.ts +25 -0
- package/dist/audit/witness-chain.js +69 -22
- package/dist/audit/witness-key-manager.d.ts +11 -0
- package/dist/audit/witness-key-manager.js +24 -0
- package/dist/cli/brain-commands.js +2 -1
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-KNM5R47J.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-BFRW7HEU.js → agent-booster-wasm-CSTBLNYZ.js} +2 -2
- package/dist/cli/chunks/{agent-handler-ZVC3VFPC.js → agent-handler-M4W4GTXN.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-3WU3CVSX.js → agent-memory-branch-VGXFYLSQ.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-MXPJLVR3.js +2 -0
- package/dist/cli/chunks/{arena-QMRLNQUC.js → arena-FKSD3LLM.js} +4 -4
- package/dist/cli/chunks/{arena-JMVTWWG5.js → arena-IQBRGWAG.js} +2 -2
- package/dist/cli/chunks/audit-7NSGRR4Z.js +3 -0
- package/dist/cli/chunks/base-X4EXQ2AS.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-EBRXKEX5.js → better-sqlite3-2KR4LQRU.js} +2 -2
- package/dist/cli/chunks/brain-handler-M6A3UB66.js +89 -0
- package/dist/cli/chunks/{branch-enumerator-CJJG6X3I.js → branch-enumerator-2JGKY4BB.js} +2 -2
- package/dist/cli/chunks/{browser-LI2CDWVR.js → browser-J43WQPJL.js} +2 -2
- package/dist/cli/chunks/browser-workflow-4HX6RP5F.js +2 -0
- package/dist/cli/chunks/{chunk-DS7AZD26.js → chunk-26WEI3P4.js} +2 -2
- package/dist/cli/chunks/{chunk-OVEG5MEL.js → chunk-2XPMATEK.js} +2 -2
- package/dist/cli/chunks/{chunk-36HTS4EP.js → chunk-2XQHG56O.js} +2 -2
- package/dist/cli/chunks/{chunk-CGKHG46K.js → chunk-354367AP.js} +2 -2
- package/dist/cli/chunks/{chunk-FPKKKUWF.js → chunk-37ZUF5NX.js} +1 -1
- package/dist/cli/chunks/{chunk-H7Y43HBQ.js → chunk-3I4TCMOJ.js} +1 -1
- package/dist/cli/chunks/{chunk-WV66MXJI.js → chunk-3JF5A72M.js} +2 -2
- package/dist/cli/chunks/{chunk-MX5FMAY5.js → chunk-3LY7OCSO.js} +1 -1
- package/dist/cli/chunks/{chunk-KHUN65Q3.js → chunk-3V36WMIO.js} +1 -1
- package/dist/cli/chunks/{chunk-VFEU4JM4.js → chunk-3WR35GFF.js} +2 -2
- package/dist/cli/chunks/{chunk-A43MKBSX.js → chunk-4LODYRNV.js} +2 -2
- package/dist/cli/chunks/{chunk-3E3PSEC5.js → chunk-4MHN7JWC.js} +3 -3
- package/dist/cli/chunks/chunk-4QOI5JS7.js +14 -0
- package/dist/cli/chunks/{chunk-LKLWIP4Z.js → chunk-4RTWPR3X.js} +1 -1
- package/dist/cli/chunks/chunk-4XJ2A3HY.js +65 -0
- package/dist/cli/chunks/{chunk-PMHSTMHV.js → chunk-4Y3LGBKJ.js} +3 -3
- package/dist/cli/chunks/{chunk-SFDBIO64.js → chunk-52U5BFZP.js} +2 -2
- package/dist/cli/chunks/{chunk-YPRM6ZFL.js → chunk-53YOYZW5.js} +2 -2
- package/dist/cli/chunks/{chunk-REZ2GZQ3.js → chunk-5WMU7XCF.js} +1 -1
- package/dist/cli/chunks/{chunk-VUEYLW5P.js → chunk-62OTU2AP.js} +2 -2
- package/dist/cli/chunks/{chunk-3XLGXCSX.js → chunk-62UM7Q5N.js} +1 -1
- package/dist/cli/chunks/{chunk-DZZ4AJQI.js → chunk-6Q57K4YD.js} +2 -2
- package/dist/cli/chunks/chunk-6R3YOAKO.js +2 -0
- package/dist/cli/chunks/chunk-6T65OKUM.js +2 -0
- package/dist/cli/chunks/{chunk-VTDWQ7WI.js → chunk-7BCRULCP.js} +2 -2
- package/dist/cli/chunks/{chunk-XCSEJQXR.js → chunk-7DTMENY6.js} +2 -2
- package/dist/cli/chunks/{chunk-N2K2EQFH.js → chunk-7KXPNNMR.js} +2 -2
- package/dist/cli/chunks/{chunk-XKUN5PDH.js → chunk-7P6X4BFO.js} +3 -3
- package/dist/cli/chunks/{chunk-3CBYKKRW.js → chunk-7YSBATSN.js} +2 -2
- package/dist/cli/chunks/{chunk-ZDPQB67L.js → chunk-ABU64UWB.js} +1 -1
- package/dist/cli/chunks/{chunk-IJHPZMEQ.js → chunk-AF6P5RWY.js} +2 -2
- package/dist/cli/chunks/{chunk-7S7QF4HJ.js → chunk-AGJOGUP5.js} +1 -1
- package/dist/cli/chunks/{chunk-EHEFI6LR.js → chunk-AL5VJJN4.js} +1 -1
- package/dist/cli/chunks/{chunk-Q2A2XQGF.js → chunk-AOQYORVA.js} +2 -2
- package/dist/cli/chunks/{chunk-6WWNK67C.js → chunk-AOXJFDH5.js} +180 -176
- package/dist/cli/chunks/{chunk-SWRGPCZ2.js → chunk-AXKWV5NF.js} +4 -4
- package/dist/cli/chunks/{chunk-3BREKEL5.js → chunk-B2VBDMDI.js} +2 -2
- package/dist/cli/chunks/{chunk-RXN5DWVM.js → chunk-BJLA2IX7.js} +2 -2
- package/dist/cli/chunks/{chunk-DPYNXEBC.js → chunk-BLPWJQTY.js} +2 -2
- package/dist/cli/chunks/{chunk-SMHYPPO6.js → chunk-BTLUWH4R.js} +2 -2
- package/dist/cli/chunks/{chunk-PUK5NE47.js → chunk-C4EZNOWK.js} +1 -1
- package/dist/cli/chunks/{chunk-ATFADWGD.js → chunk-C5C4W572.js} +2 -2
- package/dist/cli/chunks/{chunk-WTKT2AD3.js → chunk-CDJP6COA.js} +2 -2
- package/dist/cli/chunks/{chunk-G6MPXBCD.js → chunk-CKOF27L7.js} +2 -2
- package/dist/cli/chunks/{chunk-BQ5EJPK3.js → chunk-D45QLJEL.js} +1 -1
- package/dist/cli/chunks/{chunk-WCVZHXWL.js → chunk-DFRRWOEX.js} +2 -2
- package/dist/cli/chunks/{chunk-PSL53AQ4.js → chunk-DLBVADWQ.js} +92 -92
- package/dist/cli/chunks/{chunk-HRD5I7ES.js → chunk-DPL762HU.js} +1 -1
- package/dist/cli/chunks/{chunk-7QIYYYUE.js → chunk-DVW66FPU.js} +1 -1
- package/dist/cli/chunks/{chunk-ABD6JBNO.js → chunk-EDOGRFAG.js} +1 -1
- package/dist/cli/chunks/{chunk-7SBMTSGY.js → chunk-EEKG35K5.js} +5 -5
- package/dist/cli/chunks/{chunk-PW4GGJMP.js → chunk-EK3HPH6A.js} +1 -1
- package/dist/cli/chunks/{chunk-QPMISAWB.js → chunk-FGD6HINU.js} +1 -1
- package/dist/cli/chunks/{chunk-SLU35IDJ.js → chunk-FGSIID5C.js} +2 -2
- package/dist/cli/chunks/{chunk-DNOBN3IR.js → chunk-FHTYEAQ3.js} +2 -2
- package/dist/cli/chunks/{chunk-S2T2BXUL.js → chunk-FII3WCCY.js} +2 -2
- package/dist/cli/chunks/{chunk-77QJQRL2.js → chunk-FIPKIIMS.js} +2 -2
- package/dist/cli/chunks/{chunk-WYJFVSEB.js → chunk-FMNXHVIN.js} +2 -2
- package/dist/cli/chunks/{chunk-FZLCKIPP.js → chunk-G2ZIJZJ7.js} +2 -2
- package/dist/cli/chunks/{chunk-L6PH7JIE.js → chunk-GODAWJMZ.js} +2 -2
- package/dist/cli/chunks/{chunk-KTYESESI.js → chunk-GW6XWMX2.js} +2 -2
- package/dist/cli/chunks/{chunk-AC6OZTY4.js → chunk-HC6KTVFR.js} +2 -2
- package/dist/cli/chunks/{chunk-EXCU4J7T.js → chunk-HJWT4KME.js} +1 -1
- package/dist/cli/chunks/{chunk-GBCDJJWH.js → chunk-I3ANRYQ6.js} +2 -2
- package/dist/cli/chunks/{chunk-KXRI4MR3.js → chunk-I3NWKPXJ.js} +2 -2
- package/dist/cli/chunks/chunk-IBDQWKI3.js +2 -0
- package/dist/cli/chunks/{chunk-7FVWETN4.js → chunk-IU5RSN6M.js} +2 -2
- package/dist/cli/chunks/{chunk-L44XXD3X.js → chunk-J5XDKVI7.js} +2 -2
- package/dist/cli/chunks/{chunk-NJ2RY4OL.js → chunk-J6PFPY7V.js} +2 -2
- package/dist/cli/chunks/{chunk-27MMZQ7X.js → chunk-JATLFS6A.js} +1 -1
- package/dist/cli/chunks/{chunk-SIAJP3YA.js → chunk-JBKZ5TUM.js} +2 -2
- package/dist/cli/chunks/{chunk-PLQADRA6.js → chunk-JDSHUECG.js} +2 -2
- package/dist/cli/chunks/chunk-K4C25BWV.js +24 -0
- package/dist/cli/chunks/{chunk-UFZCHVLH.js → chunk-K4I7UIU5.js} +1 -1
- package/dist/cli/chunks/{chunk-6F43POT6.js → chunk-KP3R2M2G.js} +1 -1
- package/dist/cli/chunks/chunk-KQVIWE3W.js +2 -0
- package/dist/cli/chunks/{chunk-JWTMVC6E.js → chunk-KVVJVMDM.js} +2 -2
- package/dist/cli/chunks/{chunk-EZ4GKHSI.js → chunk-LOE2JETO.js} +2 -2
- package/dist/cli/chunks/{chunk-O7ZDQ5FF.js → chunk-LPR2R3AN.js} +3 -3
- package/dist/cli/chunks/{chunk-AKOGQT3A.js → chunk-M6FW56MV.js} +2 -2
- package/dist/cli/chunks/{chunk-NBOEXSV2.js → chunk-MCHEUSY4.js} +1 -1
- package/dist/cli/chunks/{chunk-B7XPSXK6.js → chunk-MEIU7457.js} +2 -2
- package/dist/cli/chunks/{chunk-3FOFPGHH.js → chunk-MHMQ6MCT.js} +2 -2
- package/dist/cli/chunks/{chunk-6JR2RSY2.js → chunk-MIU5RUBJ.js} +2 -2
- package/dist/cli/chunks/{chunk-QCCXH5DK.js → chunk-MMEXHZUC.js} +37 -12
- package/dist/cli/chunks/{chunk-LW5TUN5F.js → chunk-MTBGOWJA.js} +2 -2
- package/dist/cli/chunks/{chunk-JVXPKHND.js → chunk-NCSXLMDL.js} +77 -27
- package/dist/cli/chunks/{chunk-WLLGPGQY.js → chunk-O7J54OHN.js} +1 -1
- package/dist/cli/chunks/{chunk-ZM7WOA3K.js → chunk-OGNTCZKK.js} +1 -1
- package/dist/cli/chunks/{chunk-CYJ6O5VZ.js → chunk-OS2HHJTM.js} +2 -2
- package/dist/cli/chunks/{chunk-242B625Q.js → chunk-OS62Y77J.js} +2 -2
- package/dist/cli/chunks/{chunk-CLZ5RQVA.js → chunk-PVDXNQPL.js} +2 -2
- package/dist/cli/chunks/{chunk-PUUGIBFF.js → chunk-PW72M2FE.js} +2 -2
- package/dist/cli/chunks/{chunk-RWUGXU2K.js → chunk-Q5TR6ETB.js} +22 -22
- package/dist/cli/chunks/{chunk-CCDGNJZX.js → chunk-QKK7VBVB.js} +2 -2
- package/dist/cli/chunks/{chunk-BHZI6PDR.js → chunk-RFLHPLET.js} +1 -1
- package/dist/cli/chunks/{chunk-KULBMV6K.js → chunk-RJN2RM76.js} +2 -2
- package/dist/cli/chunks/{chunk-LGEZ3ZJX.js → chunk-RKXZLTWR.js} +2 -2
- package/dist/cli/chunks/{chunk-OFMVC6P3.js → chunk-SE3JFUKP.js} +1 -1
- package/dist/cli/chunks/{chunk-S7KDHA6P.js → chunk-SK754ZSH.js} +4 -4
- package/dist/cli/chunks/{chunk-OQGELUM2.js → chunk-SO6G4IX3.js} +2 -2
- package/dist/cli/chunks/{chunk-5746QYRF.js → chunk-SUL3I6QZ.js} +2 -2
- package/dist/cli/chunks/{chunk-22CUJA33.js → chunk-TBT3OFRW.js} +2 -2
- package/dist/cli/chunks/{chunk-26KHL4VO.js → chunk-TEIWJ3GJ.js} +1 -1
- package/dist/cli/chunks/{chunk-SFGBC5RP.js → chunk-TRNBQFFG.js} +8 -20
- package/dist/cli/chunks/{chunk-UTGW75AZ.js → chunk-TTJJ4DQE.js} +2 -2
- package/dist/cli/chunks/{chunk-H6YFMUFG.js → chunk-UBI2EOS3.js} +1 -1
- package/dist/cli/chunks/{chunk-GCIL7PK7.js → chunk-UBY322ED.js} +2 -2
- package/dist/cli/chunks/{chunk-P4UGVVVX.js → chunk-UORTQXJ2.js} +1 -1
- package/dist/cli/chunks/{chunk-BFBZFUBP.js → chunk-URP75DL4.js} +1 -1
- package/dist/cli/chunks/chunk-V6NAB5UZ.js +2 -0
- package/dist/cli/chunks/{chunk-DZ7PWB6E.js → chunk-VMFAANWX.js} +2 -2
- package/dist/cli/chunks/{chunk-6KKKPVOF.js → chunk-VMWRMINE.js} +1 -1
- package/dist/cli/chunks/{chunk-ECGASTG7.js → chunk-VN2HHBZN.js} +2 -2
- package/dist/cli/chunks/{chunk-6GVRP64A.js → chunk-W72FJA2H.js} +2 -2
- package/dist/cli/chunks/chunk-W7TYKPLY.js +27 -0
- package/dist/cli/chunks/{chunk-2OUXYSQV.js → chunk-WHHQIL4F.js} +2 -2
- package/dist/cli/chunks/{chunk-RRSUW2TK.js → chunk-WMZ2QGGS.js} +2 -2
- package/dist/cli/chunks/{chunk-54TDOQAH.js → chunk-WPSK237F.js} +3 -3
- package/dist/cli/chunks/{chunk-LMA6KEZH.js → chunk-XKQY2Z3Q.js} +1 -1
- package/dist/cli/chunks/{chunk-UMWYL37S.js → chunk-XLT3FYS7.js} +2 -2
- package/dist/cli/chunks/{chunk-5EW36WTI.js → chunk-XT4TDLOB.js} +2 -2
- package/dist/cli/chunks/{chunk-7UOH55UT.js → chunk-Y25PO65W.js} +2 -2
- package/dist/cli/chunks/{chunk-ED7MD6OI.js → chunk-Y6DWJKHU.js} +3 -3
- package/dist/cli/chunks/{chunk-A4NYOH7P.js → chunk-YBPLJRVT.js} +2 -2
- package/dist/cli/chunks/{chunk-BA7PJS3Y.js → chunk-YFCULQBP.js} +2 -2
- package/dist/cli/chunks/{chunk-B65CRJN6.js → chunk-YGVDP6X7.js} +1 -1
- package/dist/cli/chunks/chunk-YR2JKBZO.js +2 -0
- package/dist/cli/chunks/{chunk-FJRRXCIS.js → chunk-YZSTZUGJ.js} +1 -1
- package/dist/cli/chunks/{chunk-H2YOWAEB.js → chunk-ZG5UAEEO.js} +2 -2
- package/dist/cli/chunks/{chunk-MU36VPXV.js → chunk-ZLBY25MB.js} +1 -1
- package/dist/cli/chunks/chunk-ZMPAM4DY.js +2 -0
- package/dist/cli/chunks/{chunk-4ITHKHR5.js → chunk-ZPP57WQU.js} +2 -2
- package/dist/cli/chunks/{chunk-B6USJW5E.js → chunk-ZXEWTZFR.js} +1 -1
- package/dist/cli/chunks/{ci-JW4O2J3W.js → ci-CBNVLOOQ.js} +2 -2
- package/dist/cli/chunks/{ci-output-JNXJV4B2.js → ci-output-I4HY2FYJ.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-XDD4KUGR.js → circuit-breaker-5VRBKGWL.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-L6IZOGYZ.js → claude-flow-setup-XPJPKHIO.js} +2 -2
- package/dist/cli/chunks/client-AHXNCOHK.js +2 -0
- package/dist/cli/chunks/{cline-installer-PK5SMN2B.js → cline-installer-OFRDUUWZ.js} +2 -2
- package/dist/cli/chunks/{code-ZDVX3SQH.js → code-QIZQVB3E.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-VXZNKEU5.js → code-index-extractor-LMUUWEX4.js} +2 -2
- package/dist/cli/chunks/{codex-installer-OXKSIX7H.js → codex-installer-N2MKIZ2S.js} +2 -2
- package/dist/cli/chunks/{completions-VRFFK223.js → completions-Y36S3C5J.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-FTIMV74J.js → complexity-analyzer-73YS3WUD.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-KTYBBPN4.js → continuedev-installer-SAOTP6J3.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-WDC3YNUR.js → copilot-installer-A4HXF6HE.js} +2 -2
- package/dist/cli/chunks/core-handlers-EEFLLMAZ.js +2 -0
- package/dist/cli/chunks/{cost-tracker-6MH4H33B.js → cost-tracker-P26XUVZS.js} +2 -2
- package/dist/cli/chunks/{coverage-NHATLNS4.js → coverage-HVNHSMVJ.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-LT3H4SNJ.js +2 -0
- package/dist/cli/chunks/{cursor-installer-VQSUJDFB.js → cursor-installer-46BQFTYZ.js} +2 -2
- package/dist/cli/chunks/{daemon-3VAOEKQW.js → daemon-Y54O3FLT.js} +3 -3
- package/dist/cli/chunks/daemon-YE7K2AZF.js +10 -0
- package/dist/cli/chunks/{dag-attention-scheduler-HZ6OGYIH.js → dag-attention-scheduler-ETA7YY52.js} +2 -2
- package/dist/cli/chunks/{detect-CGU3SC63.js → detect-5WLQ2J3E.js} +2 -2
- package/dist/cli/chunks/{dist-node-DIBQ7PTA.js → dist-node-45WW6I7J.js} +2 -2
- package/dist/cli/chunks/{domain-handler-DCMGAYXS.js → domain-handler-J7DQV74M.js} +2 -2
- package/dist/cli/chunks/domain-transfer-GD2EGQVR.js +2 -0
- package/dist/cli/chunks/dream-4K3BK4IG.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-7247LAU3.js → embed-and-insert-pattern-JELNEA2D.js} +2 -2
- package/dist/cli/chunks/{eval-6KR7TFOK.js → eval-A4PA5G2U.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-IIOR6RVV.js → experience-capture-middleware-MLHTYWTA.js} +3 -3
- package/dist/cli/chunks/{fast-paths-M7OGD4ZI.js → fast-paths-QYDTITRV.js} +2 -2
- package/dist/cli/chunks/{feature-flags-U75KFIGH.js → feature-flags-H4MSY26Z.js} +2 -2
- package/dist/cli/chunks/{feature-flags-GGUXHRJI.js → feature-flags-MQYYRHIK.js} +2 -2
- package/dist/cli/chunks/{file-discovery-V52AYEB7.js → file-discovery-RMFVJNGL.js} +2 -2
- package/dist/cli/chunks/{fleet-2UH72CK4.js → fleet-7KZQOTAC.js} +4 -4
- package/dist/cli/chunks/{gnn-wrapper-J2GDLT3P.js → gnn-wrapper-NMZFTGVH.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-QIDQHRXT.js → heartbeat-handler-7BQDK7MG.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-IMPPGQUK.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-EIAA6R2L.js +2 -0
- package/dist/cli/chunks/hnsw-index-ZXXP6AXZ.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-IU62PIY5.js → hnsw-legacy-bridge-TPPGBPKF.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-QNZJOJAB.js → hnswlib-node-E6NSZPP2.js} +2 -2
- package/dist/cli/chunks/{hooks-ZI4D3ATS.js → hooks-CYZIUYSH.js} +48 -52
- package/dist/cli/chunks/hybrid-router-LXWG4MLH.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-6JEERAGA.js → hypergraph-engine-WC6DMTYQ.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-YMDGYCB6.js → hypergraph-handler-GTGA3TXJ.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-TP5LRFYH.js +2 -0
- package/dist/cli/chunks/{init-handler-N57NW3QI.js → init-handler-N3Z72JNI.js} +6 -6
- package/dist/cli/chunks/init-wizard-AIOA5KOY.js +2 -0
- package/dist/cli/chunks/kernel-SQALRU6Q.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-7ABTGXJ5.js → kilocode-installer-FUX4V6II.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-2JFOHLVI.js → kiro-installer-ZSNZT7ZR.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-JFVT6SNN.js +2 -0
- package/dist/cli/chunks/{learning-3P3ZXRGD.js → learning-UQY64COU.js} +3 -3
- package/dist/cli/chunks/{llm-router-AWB2KHDW.js → llm-router-CMHGGX6N.js} +4 -4
- package/dist/cli/chunks/llm-router-service-XHFKTH3I.js +2 -0
- package/dist/cli/chunks/{load-GGVBCBGX.js → load-E6WH4QN2.js} +2 -2
- package/dist/cli/chunks/load-test-JEIFJKNN.js +2 -0
- package/dist/cli/chunks/{mcp-33NHIBN3.js → mcp-UM5VTW6N.js} +2 -2
- package/dist/cli/chunks/{memory-IVAQS4OW.js → memory-7Q3XDUE5.js} +5 -5
- package/dist/cli/chunks/memory-backend-NT7I37CP.js +2 -0
- package/dist/cli/chunks/memory-handlers-746D7NE7.js +2 -0
- package/dist/cli/chunks/{multi-model-executor-NWQY6IN2.js → multi-model-executor-LZENWVRR.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-FBB4JOEV.js → opencode-installer-O2JAIPLF.js} +2 -2
- package/dist/cli/chunks/{orchestrator-GDAXR7DH.js → orchestrator-DKZWXDRI.js} +5 -5
- package/dist/cli/chunks/pattern-null-store-6QU6WHDW.js +2 -0
- package/dist/cli/chunks/pattern-usage-recorder-CLUL4M55.js +2 -0
- package/dist/cli/chunks/{pipeline-VIKAOIBE.js → pipeline-2VDLTR5J.js} +2 -2
- package/dist/cli/chunks/{platform-FFVP36LH.js → platform-4N4Q5XYX.js} +2 -2
- package/dist/cli/chunks/{plugin-TI6QOLXH.js → plugin-GY5AU5CS.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-AZRNI2OL.js → prime-radiant-advanced-wasm-TQ4DKDZS.js} +2 -2
- package/dist/cli/chunks/protocol-executor-GT2MZYUU.js +2 -0
- package/dist/cli/chunks/{protocol-handler-J4EA34B3.js → protocol-handler-T3LZ3WRG.js} +2 -2
- package/dist/cli/chunks/{prove-ADVRMAWS.js → prove-OV7S5J4W.js} +2 -2
- package/dist/cli/chunks/provider-manager-OATJ7R3D.js +2 -0
- package/dist/cli/chunks/qe-reasoning-bank-IJXNQ67O.js +2 -0
- package/dist/cli/chunks/{quality-GB5SJFSD.js → quality-AXD4NLQA.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-6RBHWCUG.js +2 -0
- package/dist/cli/chunks/{real-embeddings-GDRJ4XSH.js → real-embeddings-2PUCC7FG.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-Q6EISUDV.js → roocode-installer-WJ5ARGLW.js} +2 -2
- package/dist/cli/chunks/router-XKQRT5JK.js +2 -0
- package/dist/cli/chunks/routing-feedback-ACPSD4LW.js +2 -0
- package/dist/cli/chunks/{routing-handler-RO4RTRAG.js → routing-handler-CU6657SZ.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-FFIHCGVQ.js → ruvector-commands-IIF6VSFW.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-JGEK3A5Y.js → rvf-dual-writer-YMQI7XO2.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-OVYC4QM6.js → rvf-migration-adapter-HDE3PR2W.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-U6L77QTS.js → rvf-migration-coordinator-MQV5OA7K.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-SIWRKE33.js +2 -0
- package/dist/cli/chunks/safe-db-LCPUYMX4.js +2 -0
- package/dist/cli/chunks/schedule-HIQJCWXG.js +2 -0
- package/dist/cli/chunks/scheduler-QE5EJ5LE.js +2 -0
- package/dist/cli/chunks/{security-QPQIDAIL.js → security-UM3IGDSM.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-JRJTI4UD.js → shared-rvf-adapter-I3SOJ6M4.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-DSHGURDA.js → shared-rvf-dual-writer-KQGC2UO7.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-EU54UTMH.js +2 -0
- package/dist/cli/chunks/status-handler-OX4CJZME.js +46 -0
- package/dist/cli/chunks/{structural-health-UVECCN7U.js → structural-health-PYUMVBXJ.js} +2 -2
- package/dist/cli/chunks/{sync-XXIGTGCG.js → sync-2TED3YTY.js} +2 -2
- package/dist/cli/chunks/{sync-ZLZ4CZFJ.js → sync-VALFNTA6.js} +2 -2
- package/dist/cli/chunks/{task-handler-73YAVOKJ.js → task-handler-VPGAJVPC.js} +2 -2
- package/dist/cli/chunks/{task-handlers-PKECV27D.js → task-handlers-IB4UAMU6.js} +3 -3
- package/dist/cli/chunks/{test-U3SXW4SV.js → test-OMRJOZB6.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-POJND3GV.js → test-scheduling-ZL3YFPBU.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-ICX6SIXJ.js → token-bootstrap-DNWZI7SH.js} +2 -2
- package/dist/cli/chunks/{token-usage-WCHJUVGT.js → token-usage-IYO7RGFF.js} +2 -2
- package/dist/cli/chunks/{transformers-L77UIHIY.js → transformers-53ALC34T.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-CVAXURQP.js → tree-sitter-wasm-parser-WUKJ2I2Q.js} +2 -2
- package/dist/cli/chunks/{types-LNVJBDM2.js → types-47FTEPMV.js} +2 -2
- package/dist/cli/chunks/unified-memory-CJLMC2I4.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-FDGR4D2J.js +2 -0
- package/dist/cli/chunks/unified-persistence-UFH5GLDN.js +2 -0
- package/dist/cli/chunks/{upgrade-4ND5RQFY.js → upgrade-QPLMJA5Z.js} +2 -2
- package/dist/cli/chunks/{validate-ZA4XT6K2.js → validate-3GVKZOVF.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-FNK3GCJ4.js → validate-swarm-XCRTLVM6.js} +2 -2
- package/dist/cli/chunks/{vibium-E2CK2GBQ.js → vibium-CH4VPKVZ.js} +2 -2
- package/dist/cli/chunks/visual-security-4ARJ7J2Y.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-63VRNKZV.js → web-tree-sitter-JDBNAZTV.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-5BTCVOLH.js → windsurf-installer-3MNPVJBP.js} +2 -2
- package/dist/cli/chunks/witness-chain-73QC33ED.js +2 -0
- package/dist/cli/chunks/{witness-chain-6CUUGISD.js → witness-chain-HR5UBV5J.js} +2 -2
- package/dist/cli/chunks/witness-key-manager-G5SQTIBZ.js +2 -0
- package/dist/cli/chunks/{workflow-V7ED22XT.js → workflow-43EMD5FY.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-RKMMPXNA.js +2 -0
- package/dist/cli/chunks/{wrappers-7S3NTTLW.js → wrappers-3N7AYNM3.js} +2 -2
- package/dist/cli/commands/audit.d.ts +12 -0
- package/dist/cli/commands/audit.js +64 -4
- package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +45 -19
- package/dist/cli/commands/hooks-handlers/hooks-shared.d.ts +13 -0
- package/dist/cli/commands/hooks-handlers/hooks-shared.js +38 -0
- package/dist/cli/commands/hooks-handlers/task-hooks.js +19 -1
- package/dist/cli/handlers/status-handler.d.ts +18 -0
- package/dist/cli/handlers/status-handler.js +47 -0
- package/dist/coordination/consensus/providers/ollama-provider.js +3 -2
- package/dist/coordination/mincut/queen-integration.js +24 -7
- package/dist/coordination/protocol-executor.js +2 -1
- package/dist/coordination/queen-lifecycle.js +4 -1
- package/dist/domains/code-intelligence/coordinator.js +10 -6
- package/dist/domains/code-intelligence/services/product-factors-bridge.js +3 -1
- package/dist/domains/defect-intelligence/services/defect-predictor.d.ts +6 -0
- package/dist/domains/defect-intelligence/services/defect-predictor.js +21 -0
- package/dist/domains/learning-optimization/interfaces.d.ts +7 -0
- package/dist/domains/learning-optimization/plugin.js +5 -0
- package/dist/domains/learning-optimization/services/learning-coordinator.d.ts +10 -0
- package/dist/domains/learning-optimization/services/learning-coordinator.js +57 -0
- package/dist/domains/test-execution/plugin.js +2 -2
- package/dist/domains/test-execution/services/flaky-detector.js +1 -1
- package/dist/domains/test-generation/coordinator.js +22 -8
- package/dist/domains/test-generation/interfaces.d.ts +3 -0
- package/dist/domains/test-generation/services/test-generator.js +9 -1
- package/dist/integrations/ruvector/delta-tracker.js +10 -1
- package/dist/integrations/ruvector/proof-gate.d.ts +68 -0
- package/dist/integrations/ruvector/proof-gate.js +135 -0
- package/dist/integrations/ruvector/sona-persistence.d.ts +24 -0
- package/dist/integrations/ruvector/sona-persistence.js +76 -0
- package/dist/integrations/ruvector/sona-three-loop.d.ts +15 -0
- package/dist/integrations/ruvector/sona-three-loop.js +17 -0
- package/dist/kernel/unified-memory-schemas.d.ts +2 -2
- package/dist/kernel/unified-memory-schemas.js +48 -2
- package/dist/kernel/unified-memory.d.ts +57 -0
- package/dist/kernel/unified-memory.js +148 -0
- package/dist/learning/aqe-learning-engine.js +3 -1
- package/dist/learning/dream/concept-graph.d.ts +31 -1
- package/dist/learning/dream/concept-graph.js +109 -3
- package/dist/learning/dream/dream-engine.d.ts +13 -1
- package/dist/learning/dream/dream-engine.js +146 -10
- package/dist/learning/dream/index.d.ts +1 -1
- package/dist/learning/dream/types.d.ts +23 -0
- package/dist/learning/local-judge-client.js +2 -1
- package/dist/learning/pattern-store.d.ts +2 -2
- package/dist/learning/pattern-store.js +14 -3
- package/dist/learning/qe-reasoning-bank.js +34 -31
- package/dist/learning/routing-topology-gate.d.ts +12 -2
- package/dist/learning/routing-topology-gate.js +15 -3
- package/dist/learning/rvf-pattern-store.d.ts +1 -1
- package/dist/learning/rvf-pattern-store.js +21 -8
- package/dist/learning/sqlite-persistence.js +12 -9
- package/dist/mcp/bundle.js +524 -445
- package/dist/mcp/qe-tool-bridge.js +7 -2
- package/dist/mcp/tools/base.d.ts +29 -0
- package/dist/mcp/tools/base.js +25 -0
- package/dist/mcp/tools/coverage-analysis/index.js +6 -4
- package/dist/mcp/tools/learning-optimization/dream.d.ts +4 -13
- package/dist/mcp/tools/learning-optimization/dream.js +10 -96
- package/dist/mcp/tools/planning/goap-execute.d.ts +13 -1
- package/dist/mcp/tools/planning/goap-execute.js +33 -18
- package/dist/mcp/tools/registry.js +7 -2
- package/dist/persistence/rvf-migration-coordinator.js +2 -1
- package/dist/planning/actions/qe-action-library.js +124 -1
- package/dist/planning/goap-planner.d.ts +14 -2
- package/dist/planning/goap-planner.js +51 -9
- package/dist/planning/index.d.ts +1 -1
- package/dist/planning/plan-executor.d.ts +84 -4
- package/dist/planning/plan-executor.js +221 -56
- package/dist/planning/types.d.ts +27 -0
- package/dist/routing/free-tier/coordinator-support.d.ts +6 -3
- package/dist/routing/free-tier/coordinator-support.js +6 -3
- package/dist/routing/free-tier/executor.d.ts +14 -0
- package/dist/routing/free-tier/executor.js +21 -0
- package/dist/routing/free-tier/index.d.ts +1 -0
- package/dist/routing/free-tier/index.js +1 -0
- package/dist/routing/free-tier/pattern-cache.d.ts +57 -0
- package/dist/routing/free-tier/pattern-cache.js +148 -0
- package/dist/routing/free-tier/provider.js +9 -1
- package/dist/routing/value-score.js +3 -0
- package/dist/shared/embeddings/ollama-client.js +2 -1
- package/dist/shared/events/domain-events.d.ts +2 -0
- package/dist/shared/llm/model-mapping.js +26 -0
- package/dist/shared/llm/model-registry.d.ts +10 -0
- package/dist/shared/llm/model-registry.js +92 -0
- package/dist/shared/llm/ollama-url.d.ts +17 -0
- package/dist/shared/llm/ollama-url.js +25 -0
- package/dist/shared/llm/providers/ollama-timeout.d.ts +26 -0
- package/dist/shared/llm/providers/ollama-timeout.js +31 -0
- package/dist/shared/llm/providers/ollama.d.ts +10 -0
- package/dist/shared/llm/providers/ollama.js +31 -4
- package/dist/shared/llm/router/hybrid-router.js +18 -1
- package/dist/workers/workers/learning-consolidation.js +21 -1
- package/package.json +5 -1
- package/dist/cli/chunks/adapter-IU3H3MD7.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-BGOC63IN.js +0 -2
- package/dist/cli/chunks/audit-TTWAAV7P.js +0 -3
- package/dist/cli/chunks/base-DVPRE3WO.js +0 -2
- package/dist/cli/chunks/brain-handler-FXPLJCPV.js +0 -89
- package/dist/cli/chunks/browser-workflow-MP5P7KZF.js +0 -2
- package/dist/cli/chunks/chunk-2SZQDTI5.js +0 -2
- package/dist/cli/chunks/chunk-6IHB3T6M.js +0 -2
- package/dist/cli/chunks/chunk-7PDUD7FF.js +0 -2
- package/dist/cli/chunks/chunk-EBCUWMLX.js +0 -27
- package/dist/cli/chunks/chunk-NWUVXLBB.js +0 -65
- package/dist/cli/chunks/chunk-OCACCUFO.js +0 -2
- package/dist/cli/chunks/chunk-PY2Q6MN3.js +0 -24
- package/dist/cli/chunks/chunk-UNH2DE2G.js +0 -2
- package/dist/cli/chunks/client-ADCDBTEE.js +0 -2
- package/dist/cli/chunks/core-handlers-HCACMLUW.js +0 -2
- package/dist/cli/chunks/cross-domain-router-HXFQAU4M.js +0 -2
- package/dist/cli/chunks/daemon-ZSK6CLQR.js +0 -10
- package/dist/cli/chunks/domain-transfer-UWFKBZTJ.js +0 -2
- package/dist/cli/chunks/dream-SVWQH62A.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-QW5TW5QS.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-D6EJWYAL.js +0 -2
- package/dist/cli/chunks/hnsw-index-4MWR4U5W.js +0 -2
- package/dist/cli/chunks/hybrid-router-BYVUBHER.js +0 -2
- package/dist/cli/chunks/impact-analyzer-OK2UIMSG.js +0 -2
- package/dist/cli/chunks/init-wizard-6NNPNS6J.js +0 -2
- package/dist/cli/chunks/kernel-F4A4GRNO.js +0 -2
- package/dist/cli/chunks/knowledge-graph-MSJDEZCF.js +0 -2
- package/dist/cli/chunks/llm-router-service-27IQAO7G.js +0 -2
- package/dist/cli/chunks/load-test-TT5VLAN7.js +0 -2
- package/dist/cli/chunks/memory-backend-FVSK53IM.js +0 -2
- package/dist/cli/chunks/memory-handlers-OPUDOZNT.js +0 -2
- package/dist/cli/chunks/pattern-null-store-7MVEDWCY.js +0 -2
- package/dist/cli/chunks/protocol-executor-BLDDYEJ4.js +0 -2
- package/dist/cli/chunks/provider-manager-ZYCFRYZQ.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-P66CCPHM.js +0 -2
- package/dist/cli/chunks/queen-coordinator-LPHT3SX5.js +0 -2
- package/dist/cli/chunks/router-XQ2TERUT.js +0 -2
- package/dist/cli/chunks/routing-feedback-K52O752B.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-G4DV7FK3.js +0 -2
- package/dist/cli/chunks/safe-db-TMSEITES.js +0 -2
- package/dist/cli/chunks/schedule-RWFLA43O.js +0 -2
- package/dist/cli/chunks/scheduler-2V55MJJR.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-L7QM6IWF.js +0 -2
- package/dist/cli/chunks/status-handler-SBT3MZTX.js +0 -45
- package/dist/cli/chunks/unified-memory-ZSULA46X.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-SQEWFUBN.js +0 -2
- package/dist/cli/chunks/unified-persistence-EDCTT6SE.js +0 -2
- package/dist/cli/chunks/visual-security-SOGAETFP.js +0 -2
- package/dist/cli/chunks/witness-chain-AJCECBH5.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-UXRUCOZR.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.11.
|
|
2
|
-
import{a as
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.5");process.exit(0)}
|
|
2
|
+
import{a as q}from"./chunk-7KXPNNMR.js";import{c as V,d as W}from"./chunk-Y6DWJKHU.js";import{c as x}from"./chunk-52U5BFZP.js";import{a as G}from"./chunk-ZMPAM4DY.js";import{c as R}from"./chunk-Y25PO65W.js";import{b as E,d as $}from"./chunk-CKOF27L7.js";import{a as C,c as H}from"./chunk-RKXZLTWR.js";import{i as v}from"./chunk-K4I7UIU5.js";import{a as M,b as U,d as ee}from"./chunk-CDJP6COA.js";var P={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};$();H();var T=class p{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=x(),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: ${C(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 (?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -37,11 +37,15 @@ import{a as W}from"./chunk-N2K2EQFH.js";import{c as V,d as q}from"./chunk-ED7MD6
|
|
|
37
37
|
SELECT COUNT(*) as count FROM concept_edges
|
|
38
38
|
`)),this.prepared.set("countByType",this.db.prepare(`
|
|
39
39
|
SELECT concept_type, COUNT(*) as count FROM concept_nodes GROUP BY concept_type
|
|
40
|
-
`))}async addNode(e){this.ensureInitialized();let t=
|
|
40
|
+
`))}async addNode(e){this.ensureInitialized();let t=v(),n=new Date().toISOString(),i=this.prepared.get("insertNode");if(!i)throw new Error("Prepared statement not found: insertNode");let r=e.embedding?Buffer.from(new Float32Array(e.embedding).buffer):null;return i.run(t,e.conceptType,e.content,r,0,n,e.patternId||null,e.metadata?JSON.stringify(e.metadata):null),this.config.debug&&console.log(`[ConceptGraph] Added node: ${t} (${e.conceptType})`),t}async getNode(e){this.ensureInitialized();let t=this.prepared.get("getNode");if(!t)throw new Error("Prepared statement not found: getNode");let n=t.get(e);return n?this.rowToNode(n):null}async updateActivation(e,t){this.ensureInitialized();let n=this.prepared.get("updateActivation");if(!n)throw new Error("Prepared statement not found: updateActivation");let i=Math.max(0,Math.min(1,t));n.run(i,e)}async getActiveNodes(e=.1){this.ensureInitialized();let t=this.prepared.get("getActiveNodes");if(!t)throw new Error("Prepared statement not found: getActiveNodes");return t.all(e).map(i=>this.rowToNode(i))}async getNodesByType(e){this.ensureInitialized();let t=this.prepared.get("getNodesByType");if(!t)throw new Error("Prepared statement not found: getNodesByType");return t.all(e).map(i=>this.rowToNode(i))}async addEdge(e,t,n,i=1){this.ensureInitialized();let r=await this.getEdgeBetween(e,t);if(r)return await this.strengthenEdge(e,t,.1),r.id;let a=v(),o=this.prepared.get("insertEdge");if(!o)throw new Error("Prepared statement not found: insertEdge");return o.run(a,e,t,n,Math.max(0,Math.min(1,i)),1),this.config.debug&&console.log(`[ConceptGraph] Added edge: ${e} -> ${t} (${n})`),a}async strengthenEdge(e,t,n=.1){this.ensureInitialized();let i=await this.getEdgeBetween(e,t);if(!i)return;let r=Math.min(1,i.weight+n),a=this.prepared.get("updateEdge");if(!a)throw new Error("Prepared statement not found: updateEdge");a.run(r,e,t)}async getNeighbors(e){this.ensureInitialized();let t=[],n=this.prepared.get("getOutgoingEdges");if(!n)throw new Error("Prepared statement not found: getOutgoingEdges");let i=n.all(e);for(let o of i){let s=await this.getNode(o.target);s&&t.push({node:s,edge:this.rowToEdge(o)})}let r=this.prepared.get("getIncomingEdges");if(!r)throw new Error("Prepared statement not found: getIncomingEdges");let a=r.all(e);for(let o of a){let s=await this.getNode(o.source);s&&t.push({node:s,edge:this.rowToEdge(o)})}return t}async findPath(e,t,n=5){this.ensureInitialized();let i=new Set,r=[{nodeId:e,path:[e]}];for(;r.length>0;){let a=r.shift();if(a.nodeId===t){let s=[];for(let c of a.path){let l=await this.getNode(c);l&&s.push(l)}return s}if(a.path.length>n||i.has(a.nodeId))continue;i.add(a.nodeId);let o=await this.getNeighbors(a.nodeId);for(let{node:s}of o)i.has(s.id)||r.push({nodeId:s.id,path:[...a.path,s.id]})}return[]}async getCluster(e,t=2){this.ensureInitialized();let n=new Set,i=[],r=async(a,o)=>{if(n.has(a)||o>t)return;n.add(a);let s=await this.getNode(a);if(s&&(i.push(s),o<t)){let c=await this.getNeighbors(a);for(let{node:l}of c)await r(l.id,o+1)}};return await r(e,0),i}static TECHNIQUE_PATTERN_TYPES=new Set(["coverage-strategy","mutation-strategy","refactor-safe","error-handling","meta-optimization"]);async loadFromPatterns(e){this.ensureInitialized();let t=0,n=[],i=new Map;for(let r of e)try{if(await this.findNodeByPatternId(r.id))continue;let o=r.patternType&&p.TECHNIQUE_PATTERN_TYPES.has(r.patternType)?"technique":"pattern",s=await this.addNode({conceptType:o,content:`${r.name}: ${r.description}`,patternId:r.id,metadata:{domain:r.domain,patternType:r.patternType,confidence:r.confidence,successRate:r.successRate}});t++,n.push(s);let c=r.domain||"unknown";i.has(c)||i.set(c,[]),i.get(c).push(s);let l=await this.findDomainNode(r.domain);if(!l){let d=await this.addNode({conceptType:"domain",content:r.domain,metadata:{patternCount:1}});l=await this.getNode(d)}l&&await this.addEdge(s,l.id,"co_occurrence",.8)}catch(a){this.config.debug&&console.error(`[ConceptGraph] Failed to load pattern: ${r.id}`,a)}if(t>0){let r=await this.discoverSameDomainEdges(i),a=await this.pruneEdges();this.config.debug&&console.log(`[ConceptGraph] Discovered ${r} same-domain edges, pruned ${a}`)}return console.log(`[ConceptGraph] Loaded ${t} new patterns (${e.length-t} already existed)`),t}async discoverSameDomainEdges(e){if(this.ensureInitialized(),!this.db)return 0;let t=15,n=5e3,i=0;if(e&&e.size>0)for(let[r,a]of e){let o=this.countDomainSimilarityEdges(r);if(o>=n){console.log(`[ConceptGraph] Domain '${r}' already at edge cap (${o}/${n}), skipping`);continue}let s=new Set(a),c=n-o,d=this.db.prepare("SELECT id, metadata FROM concept_nodes WHERE concept_type IN ('pattern', 'technique')").all().filter(g=>{if(s.has(g.id))return!1;let m=g.metadata?E(g.metadata):{};return String(m.domain||"unknown")===r}),h=this.db.transaction(()=>{let g=0;for(let m of a){let y=0;for(let f of d){if(y>=t||g>=c)break;if(!this.prepared.get("getEdge")?.get(m,f.id)){let I=v();this.prepared.get("insertEdge").run(I,m,f.id,"similarity",.6,1),g++,y++}}if(g>=c)break}for(let m=0;m<a.length&&g<c;m++){let y=0;for(let f=m+1;f<a.length&&g<c&&!(y>=t);f++)if(!this.prepared.get("getEdge")?.get(a[m],a[f])){let I=v();this.prepared.get("insertEdge").run(I,a[m],a[f],"similarity",.6,1),g++,y++}}return g});i+=h()}else{let r=this.db.prepare("SELECT id, metadata FROM concept_nodes WHERE concept_type = 'pattern'").all(),a=new Map;for(let s of r){let c=s.metadata?E(s.metadata):{},l=String(c.domain||"unknown");a.has(l)||a.set(l,[]),a.get(l).push(s)}let o=this.db.transaction(()=>{let s=0;for(let[c,l]of a){let d=this.countDomainSimilarityEdges(c);if(d>=n)continue;let h=0,g=n-d;for(let m=0;m<l.length&&h<g;m++){let y=0;for(let f=m+1;f<l.length&&h<g&&!(y>=t);f++)if(!this.prepared.get("getEdge")?.get(l[m].id,l[f].id)){let I=v();this.prepared.get("insertEdge").run(I,l[m].id,l[f].id,"similarity",.6,1),s++,h++,y++}}}return s});i+=o()}return i}connectToDomainMates(e,t,n,i=10){if(!this.db)return;let r=this.db.prepare(`SELECT id FROM concept_nodes
|
|
41
|
+
WHERE concept_type IN ('pattern', 'technique')
|
|
42
|
+
AND json_extract(metadata, '$.domain') = ?
|
|
43
|
+
AND (pattern_id IS NULL OR pattern_id != ?)
|
|
44
|
+
LIMIT ?`).all(t,n,i);for(let a of r)this.prepared.get("getEdge")?.get(e,a.id)||this.prepared.get("insertEdge").run(v(),e,a.id,"co_occurrence",.4,1)}async loadFailuresAsErrors(e){this.ensureInitialized();let t=0;for(let n of e)try{let i=`error:${n.id}`;if(await this.findNodeByPatternId(i))continue;let a=await this.addNode({conceptType:"error",content:n.failureMode,patternId:i,metadata:{domain:n.domain,sourcePatternId:n.sourcePatternId}});t++,this.connectToDomainMates(a,n.domain,n.sourcePatternId)}catch(i){this.config.debug&&console.error(`[ConceptGraph] Failed to load failure: ${n.id}`,i)}return t}async loadSuccessesAsOutcomes(e){this.ensureInitialized();let t=0;for(let n of e)try{let i=`outcome:${n.id}`;if(await this.findNodeByPatternId(i))continue;let a=await this.addNode({conceptType:"outcome",content:n.description,patternId:i,metadata:{domain:n.domain,sourcePatternId:n.sourcePatternId}});t++,this.connectToDomainMates(a,n.domain,n.sourcePatternId)}catch(i){this.config.debug&&console.error(`[ConceptGraph] Failed to load success: ${n.id}`,i)}return t}countDomainSimilarityEdges(e){return this.db?this.db.prepare(`
|
|
41
45
|
SELECT COUNT(*) as count FROM concept_edges e
|
|
42
46
|
JOIN concept_nodes n ON e.source = n.id
|
|
43
47
|
WHERE e.edge_type = 'similarity'
|
|
44
|
-
AND n.concept_type
|
|
48
|
+
AND n.concept_type IN ('pattern', 'technique')
|
|
45
49
|
AND json_extract(n.metadata, '$.domain') = ?
|
|
46
50
|
`).get(e).count:0}async pruneEdges(e=15,t=.3){if(this.ensureInitialized(),!this.db)return 0;let n=0;return n=this.db.transaction(()=>{let r=0,a=this.db.prepare(`
|
|
47
51
|
DELETE FROM concept_edges
|
|
@@ -59,16 +63,37 @@ import{a as W}from"./chunk-N2K2EQFH.js";import{c as V,d as q}from"./chunk-ED7MD6
|
|
|
59
63
|
ORDER BY weight DESC
|
|
60
64
|
LIMIT -1 OFFSET ?
|
|
61
65
|
)
|
|
62
|
-
`).run(s,e);r+=c.changes}return r})(),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,r=t.get().count,a={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)a[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:r,byType:a,avgEdgesPerNode:i>0?r/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 te(d){return new A(d)}ee();function ne(d,e){if(e<0||e>=d.length)return d[0]??0;let t=0,n=d.length-1;for(;t<n;){let i=t+n>>1;if(d[i]<d[t]){let s=d[t];d[t]=d[i],d[i]=s}if(d[n]<d[t]){let s=d[t];d[t]=d[n],d[n]=s}if(d[i]<d[n]){let s=d[i];d[i]=d[n],d[n]=s}let r=d[n],a=t;for(let s=t;s<n;s++)if(d[s]<=r){let c=d[a];d[a]=d[s],d[s]=c,a++}let o=d[a];if(d[a]=d[n],d[n]=o,a===e)return d[a];a<e?t=a+1:n=a-1}return d[t]}var P=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},w=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(p=>this.graph.getConcept(p)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let p of i)this.graph.setActivation(p,t),this.recordActivation(p,t);let r=0,a=t,o=0,s=0;for(;r<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let p=await this.spreadIteration(),l=this.graph.getActiveNodes(this.config.threshold);for(let u of l)u.activationLevel>a&&(a=u.activationLevel);if(l.length===o&&p===0){if(s++,s>=3)break}else s=0;o=l.length,r++}let c=this.graph.getActiveNodes(this.config.threshold).map(p=>({nodeId:p.id,activation:p.activationLevel})).sort((p,l)=>l.activation-p.activation),h=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:r,nodesActivated:c.length,peakActivation:a,activatedNodes:c,novelAssociations:h.map(p=>({source:p.source.id,target:p.target.id,strength:p.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,r=0,a=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 p=U(0,o.length),l=o[p];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>r&&(r=f.peakActivation);for(let b of f.activatedNodes)a.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),h=Array.from(a).map(p=>{let l=this.graph.getConcept(p);return{nodeId:p,activation:l?.activationLevel??0}}).filter(p=>p.activation>0).sort((p,l)=>l.activation-p.activation);return this.trimHistory(),{iterations:i,nodesActivated:h.length,peakActivation:r,activatedNodes:h,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((a,o)=>o.activationLevel-a.activationLevel).slice(0,i));let r=[];for(let a=0;a<n.length;a++)for(let o=a+1;o<n.length;o++){let s=n[a],c=n[o],h=Math.sqrt(s.activationLevel*c.activationLevel),p=this.graph.getEdge(s.id,c.id),l=this.graph.getEdge(c.id,s.id),u=p!==void 0||l!==void 0,m=p?.weight??l?.weight??0,v=!u||m<.3;h>.3&&(r.push({source:s,target:c,coActivation:h,isNovel:v}),this.trackCoActivation(s.id,c.id))}return r.sort((a,o)=>a.isNovel!==o.isNovel?a.isNovel?-1:1:o.coActivation-a.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<=P)return;let e=Math.floor(P*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=ne(n,t-1),r=[];for(let[a,o]of this.coActivationCounts){if(r.length>=t)break;o<=i&&r.push(a)}for(let a of r)this.coActivationCounts.delete(a)}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 r=this.graph.getEdges(i.id);for(let a of r){let o=this.graph.getConcept(a.target);if(!o)continue;let s=i.activationLevel*a.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,h=Math.min(1,c+s);n.push({nodeId:a.target,newActivation:h})}}}for(let i of n){let r=this.graph.getConcept(i.nodeId);r&&i.newActivation>r.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(":"),r=t.get(i);(!r||n.strength>r.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 ie}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 r=await this.detectPatternMerges(i);for(let c of r)c.cycleId=e,n.push(c);let a=await this.detectNovelAssociations(t.novelAssociations);for(let c of a)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,h)=>h.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 r=i+1;r<n.length;r++){let a=n[i],o=n[r],s=this.graph.getEdge(a.id,o.id),c=this.graph.getEdge(o.id,a.id),h=Math.max(s?.weight??0,c?.weight??0),p=this.calculateContentSimilarity(a.content,o.content),l=Math.sqrt(a.activationLevel*o.activationLevel),u=h*.4+p*.3+l*.3;if(u>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[a.id,o.id]}),v=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[a.id,o.id],edgeWeight:h,contentSimilarity:p,coActivation:l});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[a.id,o.id],description:this.generatePatternMergeDescription(a,o,u),noveltyScore:m,confidenceScore:v,actionable:v>=this.config.minConfidence,applied:!1,suggestedAction:v>=this.config.minConfidence?`Merge "${this.truncate(a.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),r=this.graph.getConcept(n.target);if(!i||!r)continue;let a=this.graph.getEdge(n.source,n.target);if(a&&a.weight>.5)continue;let o=i.conceptType!==r.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,r,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(r.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??{},r=i.successRate,a=i.executionCount,o=i.confidence,s=r!==void 0&&r<.7,c=a!==void 0&&a>10,h=o!==void 0&&o<.6;if(s||c&&h){let p=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,r,a),noveltyScore:p,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 r=i.conceptType??"pattern";n[r]||(n[r]=[]),n[r].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(r=>r.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=ie().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),r=new Set(n),a=new Set(i),o=n.filter(c=>a.has(c)),s=r.size+a.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 r=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 ${r}% 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();G();import{existsSync as re,unlinkSync as ae}from"fs";var T={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},C=class{constructor(e,t=T){this.db=e;this.thresholds=t}db;thresholds;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-GGUXHRJI.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 r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}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(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let p=-r/n.patternCount;p>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(p*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let p=o/n.highConfidenceCount;p>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(p*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let p=this.rvfAdapter.dimension?.()??384,l=new Float32Array(p);for(let m=0;m<p;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 h=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:h,patternCountDelta:r,avgConfidenceDelta:a,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&&re(n)&&ae(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}},k=class{constructor(e){this.graph=e}graph;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 r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}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 a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.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();try{this.db.pragma("busy_timeout = 60000")}catch{}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(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)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 r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new k(this.graph);await a.loadIntoMemory(30);let s=await new w(a,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 a.persistActivations();let h=await new I(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=h.length;for(let l of h)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 p={cycle:{...this.currentCycle},insights:h,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,p}catch(r){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(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}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
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
66
|
+
`).run(s,e);r+=c.changes}return r})(),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,r=t.get().count,a={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)a[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:r,byType:a,avgEdgesPerNode:i>0?r/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?E(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 te(p){return new T(p)}ee();function ne(p,e){if(e<0||e>=p.length)return p[0]??0;let t=0,n=p.length-1;for(;t<n;){let i=t+n>>1;if(p[i]<p[t]){let s=p[t];p[t]=p[i],p[i]=s}if(p[n]<p[t]){let s=p[t];p[t]=p[n],p[n]=s}if(p[i]<p[n]){let s=p[i];p[i]=p[n],p[n]=s}let r=p[n],a=t;for(let s=t;s<n;s++)if(p[s]<=r){let c=p[a];p[a]=p[s],p[s]=c,a++}let o=p[a];if(p[a]=p[n],p[n]=o,a===e)return p[a];a<e?t=a+1:n=a-1}return p[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},w=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 r=0,a=t,o=0,s=0;for(;r<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),h=this.graph.getActiveNodes(this.config.threshold);for(let g of h)g.activationLevel>a&&(a=g.activationLevel);if(h.length===o&&d===0){if(s++,s>=3)break}else s=0;o=h.length,r++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,h)=>h.activation-d.activation),l=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:r,nodesActivated:c.length,peakActivation:a,activatedNodes:c,novelAssociations:l.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,r=0,a=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),h=o[d];if(h){let g=this.config.noiseLevel+M()*this.config.noiseLevel*2,m=h.activationLevel,y=Math.min(1,m+g+.3);this.graph.setActivation(h.id,y);let f=await this.spread([h.id],y,s);i+=f.iterations,f.peakActivation>r&&(r=f.peakActivation);for(let D of f.activatedNodes)a.add(D.nodeId);for(let D of f.novelAssociations)n.push(D)}if(Date.now()>=s)break;await this.sleep(50+M()*50)}let c=this.deduplicateAssociations(n),l=Array.from(a).map(d=>{let h=this.graph.getConcept(d);return{nodeId:d,activation:h?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,h)=>h.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:l.length,peakActivation:r,activatedNodes:l,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((a,o)=>o.activationLevel-a.activationLevel).slice(0,i));let r=[];for(let a=0;a<n.length;a++)for(let o=a+1;o<n.length;o++){let s=n[a],c=n[o],l=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),h=this.graph.getEdge(c.id,s.id),g=d!==void 0||h!==void 0,m=d?.weight??h?.weight??0,y=!g||m<.3;l>.3&&(r.push({source:s,target:c,coActivation:l,isNovel:y}),this.trackCoActivation(s.id,c.id))}return r.sort((a,o)=>a.isNovel!==o.isNovel?a.isNovel?-1:1:o.coActivation-a.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=ne(n,t-1),r=[];for(let[a,o]of this.coActivationCounts){if(r.length>=t)break;o<=i&&r.push(a)}for(let a of r)this.coActivationCounts.delete(a)}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 r=this.graph.getEdges(i.id);for(let a of r){let o=this.graph.getConcept(a.target);if(!o)continue;let s=i.activationLevel*a.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,l=Math.min(1,c+s);n.push({nodeId:a.target,newActivation:l})}}}for(let i of n){let r=this.graph.getConcept(i.nodeId);r&&i.newActivation>r.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=(M()-.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(":"),r=t.get(i);(!r||n.strength>r.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 ie}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},_=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 r=await this.detectPatternMerges(i);for(let c of r)c.cycleId=e,n.push(c);let a=await this.detectNovelAssociations(t.novelAssociations);for(let c of a)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,l)=>l.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 r=i+1;r<n.length;r++){let a=n[i],o=n[r],s=this.graph.getEdge(a.id,o.id),c=this.graph.getEdge(o.id,a.id),l=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(a.content,o.content),h=Math.sqrt(a.activationLevel*o.activationLevel),g=l*.4+d*.3+h*.3;if(g>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[a.id,o.id]}),y=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[a.id,o.id],edgeWeight:l,contentSimilarity:d,coActivation:h});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[a.id,o.id],description:this.generatePatternMergeDescription(a,o,g),noveltyScore:m,confidenceScore:y,actionable:y>=this.config.minConfidence,applied:!1,suggestedAction:y>=this.config.minConfidence?`Merge "${this.truncate(a.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),r=this.graph.getConcept(n.target);if(!i||!r)continue;let a=this.graph.getEdge(n.source,n.target);if(a&&a.weight>.5)continue;let o=i.conceptType!==r.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,r,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(r.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??{},r=i.successRate,a=i.executionCount,o=i.confidence,s=r!==void 0&&r<.7,c=a!==void 0&&a>10,l=o!==void 0&&o<.6;if(s||c&&l){let d=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),h=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,r,a),noveltyScore:d,confidenceScore:h,actionable:h>=this.config.minConfidence,applied:!1,suggestedAction:h>=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 r=i.conceptType??"pattern";n[r]||(n[r]=[]),n[r].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(r=>r.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=ie().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),r=new Set(n),a=new Set(i),o=n.filter(c=>a.has(c)),s=r.size+a.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 r=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 ${r}% 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();G();import{existsSync as re,unlinkSync as ae}from"fs";var A={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},b=class{constructor(e,t=A){this.db=e;this.thresholds=t}db;thresholds;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-MQYYRHIK.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 r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}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(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-r/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(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).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,h=new Float32Array(d);for(let m=0;m<d;m++)h[m]=Math.sin(m*.1);let g=this.rvfAdapter.search?.(h,10)??[];g.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${g.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let l=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:l,patternCountDelta:r,avgConfidenceDelta:a,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&&re(n)&&ae(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 S=R.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:{...A}},k=class{constructor(e){this.graph=e}graph;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 r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}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 a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.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}}},N=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=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase();try{this.db.pragma("busy_timeout = 60000")}catch{}this.migrateSchema(),this.graph=new T,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new b(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: ${C(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(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),S.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 '[]'"),S.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){S.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:v(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new k(this.graph);await a.loadIntoMemory(30);let s=await new w(a,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 a.persistActivations();let l=await new _(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=l.length;for(let h of l)await this.saveInsight(h);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 h=this.branchManager.validateBranch(i);if(h.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,h);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,h);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:h.reason},"dream-engine")}catch{}S.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:h.reason})}i=null}let d={cycle:{...this.currentCycle},insights:l,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(r){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=C(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async loadFailuresAsConcepts(e){return this.ensureInitialized(),this.graph.loadFailuresAsErrors(e)}async loadSuccessesAsConcepts(e){return this.ensureInitialized(),this.graph.loadSuccessesAsOutcomes(e)}async ensureConceptsLoaded(){this.ensureInitialized();try{let n=this.db.prepare(`SELECT n.id as id, n.pattern_id as sourcePatternId, p.qe_domain as domain, n.failure_mode as failureMode
|
|
67
|
+
FROM qe_pattern_nulls n
|
|
68
|
+
JOIN qe_patterns p ON p.id = n.pattern_id
|
|
69
|
+
ORDER BY n.updated_at DESC
|
|
70
|
+
LIMIT 100`).all();n.length>0&&await this.graph.loadFailuresAsErrors(n);let i=this.db.prepare(`SELECT u.id as id, u.pattern_id as sourcePatternId, p.qe_domain as domain,
|
|
71
|
+
('Pattern "' || p.name || '" applied successfully') as description
|
|
72
|
+
FROM qe_pattern_usage u
|
|
73
|
+
JOIN qe_patterns p ON p.id = u.pattern_id
|
|
74
|
+
WHERE u.success = 1
|
|
75
|
+
ORDER BY u.created_at DESC
|
|
76
|
+
LIMIT 100`).all();i.length>0&&await this.graph.loadSuccessesAsOutcomes(i)}catch(n){process.env.DEBUG&&S.debug("Error/outcome concept loading skipped",{error:C(n)})}if((await this.graph.getActiveNodes(0)).length>=this.config.minConceptsRequired)return 0;let t=this.db.prepare(`SELECT * FROM (
|
|
77
|
+
SELECT id, name, description, qe_domain as domain, pattern_type as patternType,
|
|
78
|
+
confidence, success_rate as successRate
|
|
79
|
+
FROM qe_patterns
|
|
80
|
+
WHERE confidence >= 0.3
|
|
81
|
+
ORDER BY quality_score DESC
|
|
82
|
+
LIMIT 160
|
|
83
|
+
)
|
|
84
|
+
UNION
|
|
85
|
+
SELECT * FROM (
|
|
86
|
+
SELECT id, name, description, qe_domain as domain, pattern_type as patternType,
|
|
87
|
+
confidence, success_rate as successRate
|
|
88
|
+
FROM qe_patterns
|
|
89
|
+
WHERE confidence >= 0.3 AND success_rate < 0.7
|
|
90
|
+
ORDER BY usage_count DESC
|
|
91
|
+
LIMIT 40
|
|
92
|
+
)`).all();return t.length===0?0:this.graph.loadFromPatterns(t)}async applyInsight(e){this.ensureInitialized();try{let t=await this.getInsightRowById(e);if(!t)return{success:!1,error:`Insight not found: ${e}`};if(t.actionable!==1)return{success:!1,error:"Insight is not actionable"};if(t.applied===1)return{success:!0,patternId:t.pattern_id??void 0,error:"Insight already applied"};let{getSharedMemoryBackend:n}=await import("./base-X4EXQ2AS.js"),{createQEReasoningBank:i}=await import("./qe-reasoning-bank-IJXNQ67O.js"),r=await n(),a=i(r);await a.initialize();try{let{getSharedRvfDualWriter:d}=await import("./shared-rvf-dual-writer-KQGC2UO7.js"),h=await d();h&&a.setRvfDualWriter(h)}catch(d){process.env.DEBUG&&S.debug("RVF wiring skipped",{error:C(d)})}let o=[];try{o=E(t.source_concepts)}catch{}let s=await a.storePattern({patternType:se(t.insight_type),name:`Dream Insight: ${t.insight_type}`,description:`${t.description} (confidence: ${t.confidence_score.toFixed(2)})`,template:{type:"workflow",content:t.suggested_action||t.description,variables:[]},context:{tags:["dream-generated",t.insight_type,...o.slice(0,3)],complexity:"medium"}});if(!s.success)return{success:!1,error:`Failed to create pattern: ${s.error?.message??"unknown error"}`};let c=s.value.id;return this.db.prepare(`
|
|
68
93
|
UPDATE dream_insights
|
|
69
94
|
SET applied = 1, pattern_id = ?
|
|
70
95
|
WHERE id = ?
|
|
71
|
-
`).run(
|
|
96
|
+
`).run(c,e),{success:!0,patternId:c}}catch(t){return{success:!1,error:C(t)}}}async getPendingInsights(e){this.ensureInitialized();let t=e??20;return this.db.prepare(`
|
|
72
97
|
SELECT * FROM dream_insights
|
|
73
98
|
WHERE applied = 0 AND actionable = 1
|
|
74
99
|
ORDER BY novelty_score DESC, confidence_score DESC
|
|
@@ -92,4 +117,4 @@ import{a as W}from"./chunk-N2K2EQFH.js";import{c as V,d as q}from"./chunk-ED7MD6
|
|
|
92
117
|
(id, cycle_id, insight_type, source_concepts, description, novelty_score,
|
|
93
118
|
confidence_score, actionable, applied, suggested_action, pattern_id)
|
|
94
119
|
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 se(d){let e=new _(d);return import("./feature-flags-GGUXHRJI.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-JRJTI4UD.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var oe=_;G();var Y="learning:loop-health";async function J(d,e,t){try{let n=new Date().toISOString(),i=await d.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await d.set(Y,i)}catch{}}var g=N.create("DreamScheduler"),Z={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},K="dream-scheduler:hook-state",L=class d{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={...Z,...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});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&g.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){g.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),g.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}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 maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-JRJTI4UD.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&g.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){g.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-DSHGURDA.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&g.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){g.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}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>d.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>d.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 reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(K),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(K,t)}catch(e){g.warn("Dream hook-state reconcile failed (non-critical)",{error:e instanceof Error?e.message:String(e)})}}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 ce(d,e){return new L(d,e)}var de=[{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}}],z=class{constructor(e,t){this.db=e;this.branchManager=new C(e,t??T)}db;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(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,h)=>{let p=this.scoreValidation(c.validation);return this.scoreValidation(h.validation)>p?h: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:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,Z as b,L as c,ce as d,B as e,A as f,te as g,P as h,O as i,F as j,j as k,w as l,Q as m,I as n,T as o,C as p,X as q,_ as r,se as s,oe as t,de as u,z as v};
|
|
120
|
+
`).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:E(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 se(p){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[p]||"test-template"}function oe(p){let e=new N(p);return import("./feature-flags-MQYYRHIK.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-I3SOJ6M4.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var ce=N;G();var Y="learning:loop-health";async function J(p,e,t){try{let n=new Date().toISOString(),i=await p.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await p.set(Y,i)}catch{}}var u=R.create("DreamScheduler"),Z={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},K="dream-scheduler:hook-state",L=class p{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={...Z,...t},this.metaLearningEngine=new W}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,u.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),u.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),u.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,u.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&&(u.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{u.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,u.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&u.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){u.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),u.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}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&&u.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){u.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-I3SOJ6M4.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&u.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){u.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-KQGC2UO7.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&u.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){u.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new q,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>p.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){u.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)u.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>p.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:v(),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{u.debug("Failed to publish meta-learning insight event")}}}else u.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){u.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),u.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){u.info("Quality gate failed but cannot start dream yet");return}u.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){u.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){u.info("Milestone reached but cannot start dream yet");return}u.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:v(),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){u.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(K),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(K,t)}catch(e){u.warn("Dream hook-state reconcile failed (non-critical)",{error:e instanceof Error?e.message:String(e)})}}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){u.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??[],u.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){u.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 de(p,e){return new L(p,e)}var pe=[{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}}],z=class{constructor(e,t){this.db=e;this.branchManager=new b(e,t??A)}db;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(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,l)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(l.validation)>d?l: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:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,P as b,T as c,te as d,B as e,O as f,F as g,j as h,w as i,Q as j,_ as k,A as l,b as m,X as n,N as o,oe as p,ce as q,pe as r,z as s,Z as t,L as u,de as v};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.
|
|
2
|
-
import{d as s}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.5");process.exit(0)}
|
|
2
|
+
import{d as s}from"./chunk-CKOF27L7.js";s();
|