agentic-qe 3.9.20 → 3.9.22

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.
Files changed (296) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +54 -0
  3. package/README.md +39 -0
  4. package/assets/skills/skills-manifest.json +1 -1
  5. package/dist/cli/bundle.js +5 -5
  6. package/dist/cli/chunks/adapter-4RFY4QQP.js +2 -0
  7. package/dist/cli/chunks/{agent-booster-wasm-T5JB3MOF.js → agent-booster-wasm-GUS4CPIF.js} +2 -2
  8. package/dist/cli/chunks/{agent-handler-EASMQSQO.js → agent-handler-X3JM3LAL.js} +2 -2
  9. package/dist/cli/chunks/{agent-memory-branch-7GWN2KCG.js → agent-memory-branch-DZVV32I2.js} +2 -2
  10. package/dist/cli/chunks/aqe-learning-engine-CJ5UDPJ6.js +2 -0
  11. package/dist/cli/chunks/{audit-VHV4GXPW.js → audit-LO2I2D4V.js} +2 -2
  12. package/dist/cli/chunks/base-EEBZKFSN.js +2 -0
  13. package/dist/cli/chunks/{better-sqlite3-GNK7MDXZ.js → better-sqlite3-MQACUCZV.js} +2 -2
  14. package/dist/cli/chunks/{brain-handler-ALXZKWO4.js → brain-handler-SW6BDUVF.js} +3 -3
  15. package/dist/cli/chunks/{branch-enumerator-JNYLOLMM.js → branch-enumerator-COUIEIXT.js} +2 -2
  16. package/dist/cli/chunks/{browser-FXRW6LID.js → browser-I3KE2PKR.js} +2 -2
  17. package/dist/cli/chunks/browser-workflow-KDNXNC7W.js +2 -0
  18. package/dist/cli/chunks/{chunk-7J34I3CI.js → chunk-2ABN34GT.js} +2 -2
  19. package/dist/cli/chunks/{chunk-CQSME43Z.js → chunk-2OQVDOCP.js} +24 -16
  20. package/dist/cli/chunks/{chunk-WALYYW6B.js → chunk-34V7MJEC.js} +4 -4
  21. package/dist/cli/chunks/{chunk-4PNLBMKY.js → chunk-3M7EAXED.js} +1 -1
  22. package/dist/cli/chunks/{chunk-7WXYQDML.js → chunk-3UPELJAD.js} +2 -2
  23. package/dist/cli/chunks/{chunk-EYSGJZ7Y.js → chunk-46X57677.js} +13 -13
  24. package/dist/cli/chunks/{chunk-DODH6CEQ.js → chunk-4KIDHFF3.js} +1 -1
  25. package/dist/cli/chunks/{chunk-YPVPWDKL.js → chunk-5D6UQZG6.js} +2 -2
  26. package/dist/cli/chunks/{chunk-QCLEA3CM.js → chunk-5HUFNSCO.js} +2 -2
  27. package/dist/cli/chunks/{chunk-4SBMTHTA.js → chunk-5Q4HS3PB.js} +2 -2
  28. package/dist/cli/chunks/{chunk-KNOZWD6E.js → chunk-5QP4OPZM.js} +2 -2
  29. package/dist/cli/chunks/{chunk-K2D5L7YV.js → chunk-5VE5R2B4.js} +1 -1
  30. package/dist/cli/chunks/{chunk-3GPNZPM4.js → chunk-5WE7JRVM.js} +1 -1
  31. package/dist/cli/chunks/{chunk-7R45TEY6.js → chunk-6EBWEMJJ.js} +2 -2
  32. package/dist/cli/chunks/chunk-6I6LXONA.js +2 -0
  33. package/dist/cli/chunks/{chunk-HCFRGEMK.js → chunk-6KHLLAFS.js} +1 -1
  34. package/dist/cli/chunks/{chunk-CPVGZYEP.js → chunk-75EXWLL2.js} +1 -1
  35. package/dist/cli/chunks/{chunk-H647PYXW.js → chunk-75EZBOLF.js} +1 -1
  36. package/dist/cli/chunks/{chunk-HW47UOFK.js → chunk-76JSNSX5.js} +2 -2
  37. package/dist/cli/chunks/{chunk-FHDYN73D.js → chunk-77CR3VJL.js} +2 -2
  38. package/dist/cli/chunks/{chunk-6R7SJ5FS.js → chunk-7BKQTKKO.js} +1 -1
  39. package/dist/cli/chunks/{chunk-MXAEZHW6.js → chunk-7TASYE2O.js} +2 -2
  40. package/dist/cli/chunks/{chunk-NQIOXSHW.js → chunk-7TWDEXR4.js} +1 -1
  41. package/dist/cli/chunks/{chunk-SH2UPGO7.js → chunk-7V2KGOFN.js} +2 -2
  42. package/dist/cli/chunks/{chunk-Y6U4CCPP.js → chunk-AKBYBOUV.js} +1 -1
  43. package/dist/cli/chunks/{chunk-TV5OVFKK.js → chunk-ASJWT2HO.js} +1 -1
  44. package/dist/cli/chunks/{chunk-ICLWWAGZ.js → chunk-BAIQZTBO.js} +2 -2
  45. package/dist/cli/chunks/{chunk-BIODM56C.js → chunk-BVFRL52U.js} +2 -2
  46. package/dist/cli/chunks/{chunk-4IUNBRKQ.js → chunk-C2ROCY2Y.js} +2 -2
  47. package/dist/cli/chunks/{chunk-NN6VRHNL.js → chunk-C32ZD3IM.js} +2 -2
  48. package/dist/cli/chunks/{chunk-UHWRRJBH.js → chunk-CWINAMA7.js} +1 -1
  49. package/dist/cli/chunks/{chunk-WF6MKBRI.js → chunk-CYHVGDGJ.js} +2 -2
  50. package/dist/cli/chunks/chunk-D4GHYV5T.js +2 -0
  51. package/dist/cli/chunks/{chunk-RXXKU3VP.js → chunk-D4RS57YM.js} +2 -2
  52. package/dist/cli/chunks/{chunk-G7HYTJDG.js → chunk-DLOY6QOK.js} +2 -2
  53. package/dist/cli/chunks/{chunk-AVVRA6FG.js → chunk-EAEF52EW.js} +2 -2
  54. package/dist/cli/chunks/{chunk-AFMLL2G3.js → chunk-EBFG55L3.js} +2 -2
  55. package/dist/cli/chunks/{chunk-5GA4BUQU.js → chunk-EHIS2X2O.js} +2 -2
  56. package/dist/cli/chunks/{chunk-S6SRHNJV.js → chunk-EIOC2ZBV.js} +2 -2
  57. package/dist/cli/chunks/{chunk-Z5MG54R4.js → chunk-ELYTUR3K.js} +1 -1
  58. package/dist/cli/chunks/{chunk-SMQ5OARZ.js → chunk-EP65OKY3.js} +1 -1
  59. package/dist/cli/chunks/{chunk-T3TEQH2H.js → chunk-F5PYXTN6.js} +1 -1
  60. package/dist/cli/chunks/{chunk-X3NADG4S.js → chunk-F6S2BURJ.js} +2 -2
  61. package/dist/cli/chunks/{chunk-VQI6JQQP.js → chunk-F76YPLIC.js} +1 -1
  62. package/dist/cli/chunks/{chunk-7I6ROJGF.js → chunk-FN33YLS4.js} +2 -2
  63. package/dist/cli/chunks/{chunk-FPBNTPCM.js → chunk-G35AFB22.js} +2 -2
  64. package/dist/cli/chunks/{chunk-EJQRDMON.js → chunk-GE4ABLTW.js} +1 -1
  65. package/dist/cli/chunks/{chunk-SGGY4QYU.js → chunk-H2CDS62D.js} +2 -2
  66. package/dist/cli/chunks/{chunk-QMUZMIV7.js → chunk-HHTTDWS2.js} +3 -3
  67. package/dist/cli/chunks/{chunk-4G6OH5LQ.js → chunk-IPWO26NP.js} +2 -2
  68. package/dist/cli/chunks/{chunk-3HQ4VKK6.js → chunk-J47LS6JI.js} +54 -58
  69. package/dist/cli/chunks/{chunk-FUTRX4ZT.js → chunk-J4DENED7.js} +2 -2
  70. package/dist/cli/chunks/{chunk-MXHJUAM7.js → chunk-JNRUY2BU.js} +2 -2
  71. package/dist/cli/chunks/{chunk-UABC2Z3S.js → chunk-JTTEDSP5.js} +2 -2
  72. package/dist/cli/chunks/{chunk-BJF77EFA.js → chunk-KA22YYYW.js} +2 -2
  73. package/dist/cli/chunks/{chunk-ZBBHJGPI.js → chunk-KBWJRXYS.js} +2 -2
  74. package/dist/cli/chunks/{chunk-MXDGMXJA.js → chunk-KEXERBH2.js} +2 -2
  75. package/dist/cli/chunks/{chunk-DSPH4GI3.js → chunk-KXVCKQ2O.js} +1 -1
  76. package/dist/cli/chunks/{chunk-6LKEFWKI.js → chunk-L2D56OS2.js} +3 -3
  77. package/dist/cli/chunks/{chunk-DERQRIAR.js → chunk-LCOVR5PF.js} +3 -3
  78. package/dist/cli/chunks/{chunk-UNAVOVD7.js → chunk-LFUJSR5V.js} +3 -3
  79. package/dist/cli/chunks/{chunk-BKGCMWFL.js → chunk-LSPQUQZQ.js} +3 -3
  80. package/dist/cli/chunks/{chunk-3BFNYFXV.js → chunk-LVW2AMCE.js} +1 -1
  81. package/dist/cli/chunks/{chunk-O3PLWCCD.js → chunk-MGTHNWDX.js} +2 -2
  82. package/dist/cli/chunks/{chunk-5ILP2ZDZ.js → chunk-MHV7VXPW.js} +2 -2
  83. package/dist/cli/chunks/{chunk-RYBFRFKY.js → chunk-N242BGZS.js} +1 -1
  84. package/dist/cli/chunks/{chunk-LATJ2LKJ.js → chunk-N7LNGYUI.js} +1 -1
  85. package/dist/cli/chunks/{chunk-IHBRFVGA.js → chunk-NDBSIHGC.js} +1 -1
  86. package/dist/cli/chunks/{chunk-4HD7YRW7.js → chunk-NKHHOJBJ.js} +2 -2
  87. package/dist/cli/chunks/{chunk-OD5SVOVP.js → chunk-O2RWRFY2.js} +1 -1
  88. package/dist/cli/chunks/{chunk-V5UB75TQ.js → chunk-OLDHOXH5.js} +2 -2
  89. package/dist/cli/chunks/{chunk-7Q7SCQMQ.js → chunk-P3CE2OST.js} +2 -2
  90. package/dist/cli/chunks/{chunk-2J5OO63R.js → chunk-PC3NYFID.js} +2 -2
  91. package/dist/cli/chunks/{chunk-UAE37LHP.js → chunk-PJQVLSZL.js} +2 -2
  92. package/dist/cli/chunks/{chunk-JCPXG42O.js → chunk-PUBADXN6.js} +2 -2
  93. package/dist/cli/chunks/{chunk-SL7WTN5Z.js → chunk-Q4Q4ZPEO.js} +2 -2
  94. package/dist/cli/chunks/{chunk-T5MMSSSF.js → chunk-Q6NM3PHP.js} +2 -2
  95. package/dist/cli/chunks/{chunk-CEVIRL2S.js → chunk-QBQHA2PQ.js} +2 -2
  96. package/dist/cli/chunks/{chunk-QLZPCEVI.js → chunk-QBY4LMKC.js} +1 -1
  97. package/dist/cli/chunks/{chunk-3ZHUKLU7.js → chunk-QH5PMTYD.js} +2 -2
  98. package/dist/cli/chunks/{chunk-MIST354H.js → chunk-QKDYDDO6.js} +2 -2
  99. package/dist/cli/chunks/{chunk-Q4OITFDX.js → chunk-QUASI6T7.js} +2 -2
  100. package/dist/cli/chunks/{chunk-NGWGOMOP.js → chunk-QXFPR4ND.js} +2 -2
  101. package/dist/cli/chunks/{chunk-LSYMQG52.js → chunk-QYUA3QRO.js} +1 -1
  102. package/dist/cli/chunks/{chunk-Z65DB2Z7.js → chunk-RDFBNLOP.js} +3 -3
  103. package/dist/cli/chunks/{chunk-RVWGW7TI.js → chunk-RHJXNBT5.js} +2 -2
  104. package/dist/cli/chunks/{chunk-LJW7BTMK.js → chunk-SBXMNI7G.js} +2 -2
  105. package/dist/cli/chunks/{chunk-XJRXB5Z5.js → chunk-SEFMGIDM.js} +2 -2
  106. package/dist/cli/chunks/{chunk-FAQPPMEC.js → chunk-SZXKDWNU.js} +2 -2
  107. package/dist/cli/chunks/{chunk-YPUDYGIU.js → chunk-T62S7PHC.js} +1 -1
  108. package/dist/cli/chunks/{chunk-J7SDO52P.js → chunk-T6SZZ6GL.js} +2 -2
  109. package/dist/cli/chunks/{chunk-KMDZOVCF.js → chunk-TF33AXXK.js} +1 -1
  110. package/dist/cli/chunks/{chunk-3CLKKAGH.js → chunk-TFEEZPAV.js} +2 -2
  111. package/dist/cli/chunks/{chunk-GXO42P3X.js → chunk-U33MB6BS.js} +6 -6
  112. package/dist/cli/chunks/{chunk-GJACTPDK.js → chunk-UG4NLJ6S.js} +2 -2
  113. package/dist/cli/chunks/{chunk-LGSPAQSP.js → chunk-UJQ4APLZ.js} +2 -2
  114. package/dist/cli/chunks/chunk-UZ5D7CNQ.js +2 -0
  115. package/dist/cli/chunks/{chunk-TG6P44UT.js → chunk-V6FH47RF.js} +4 -4
  116. package/dist/cli/chunks/{chunk-QAZYSC3T.js → chunk-VBNVPKPJ.js} +2 -2
  117. package/dist/cli/chunks/{chunk-7OGFOHG5.js → chunk-VEQZARRH.js} +2 -2
  118. package/dist/cli/chunks/{chunk-QMGXALN3.js → chunk-WXM3QRV3.js} +2 -2
  119. package/dist/cli/chunks/{chunk-DJCLA5AG.js → chunk-X3UEZQIH.js} +2 -2
  120. package/dist/cli/chunks/{chunk-P2ABIGYB.js → chunk-XNLRBJLS.js} +1 -1
  121. package/dist/cli/chunks/{chunk-QKOPJ5CZ.js → chunk-XRTQMK2J.js} +2 -2
  122. package/dist/cli/chunks/{chunk-QQMHE4RT.js → chunk-XZLXDSDH.js} +2 -2
  123. package/dist/cli/chunks/{chunk-U7RTH6F4.js → chunk-YBPODHK5.js} +2 -2
  124. package/dist/cli/chunks/{chunk-HXQ7GAUV.js → chunk-YCG6NXTH.js} +3 -3
  125. package/dist/cli/chunks/{chunk-BXGAXGME.js → chunk-YJ3KKNS5.js} +2 -2
  126. package/dist/cli/chunks/{chunk-7Y4QQ6JL.js → chunk-YT45LRYT.js} +1 -1
  127. package/dist/cli/chunks/{chunk-NWYYWFUO.js → chunk-ZHJL5MGV.js} +1 -1
  128. package/dist/cli/chunks/{chunk-SYXPLFK7.js → chunk-ZIRSR3CR.js} +2 -2
  129. package/dist/cli/chunks/{chunk-F3PX6EJX.js → chunk-ZTVYRPXO.js} +1 -1
  130. package/dist/cli/chunks/{chunk-ZCH5MNST.js → chunk-ZYLONMC3.js} +2 -2
  131. package/dist/cli/chunks/{chunk-5LM2W3NE.js → chunk-ZYVFF2GF.js} +1 -1
  132. package/dist/cli/chunks/{chunk-RCPFDAOC.js → chunk-ZZD2O63H.js} +1 -1
  133. package/dist/cli/chunks/{ci-TE3744OR.js → ci-KE7FOGU7.js} +2 -2
  134. package/dist/cli/chunks/{ci-output-GSNS52SY.js → ci-output-22E7MB4A.js} +2 -2
  135. package/dist/cli/chunks/{circuit-breaker-7ROW7QBW.js → circuit-breaker-AVTSU65L.js} +2 -2
  136. package/dist/cli/chunks/{claude-flow-setup-Z5GPMILN.js → claude-flow-setup-UWD5DRUE.js} +2 -2
  137. package/dist/cli/chunks/client-GNL46JU5.js +2 -0
  138. package/dist/cli/chunks/{cline-installer-6D4SAAM4.js → cline-installer-H3MJDJKK.js} +2 -2
  139. package/dist/cli/chunks/{code-JZKH7FRS.js → code-3G4FPMSZ.js} +2 -2
  140. package/dist/cli/chunks/{code-index-extractor-JJFTZLOK.js → code-index-extractor-PBZIQOI5.js} +2 -2
  141. package/dist/cli/chunks/{codex-installer-O5KIPN3Z.js → codex-installer-M4P7K7LO.js} +2 -2
  142. package/dist/cli/chunks/{completions-QNMAUYKK.js → completions-WWUW6CX4.js} +2 -2
  143. package/dist/cli/chunks/{complexity-analyzer-JYJ7TLYE.js → complexity-analyzer-H2F37PAW.js} +2 -2
  144. package/dist/cli/chunks/{continuedev-installer-JYMVLG6S.js → continuedev-installer-NSUF5Y6W.js} +2 -2
  145. package/dist/cli/chunks/{copilot-installer-SSV6GF5G.js → copilot-installer-BHFKNSU4.js} +2 -2
  146. package/dist/cli/chunks/{cost-tracker-2VZ3IMJZ.js → cost-tracker-QTQ32PGG.js} +2 -2
  147. package/dist/cli/chunks/{coverage-KW4V5D5L.js → coverage-LCBTTMUE.js} +3 -3
  148. package/dist/cli/chunks/cross-domain-router-2JHRNGD7.js +2 -0
  149. package/dist/cli/chunks/{cursor-installer-QVGDAHOI.js → cursor-installer-KBWXMRRA.js} +2 -2
  150. package/dist/cli/chunks/{daemon-JKMFDYK2.js → daemon-UYTVWZOZ.js} +3 -3
  151. package/dist/cli/chunks/{dag-attention-scheduler-WKRV7DFE.js → dag-attention-scheduler-3WVICTLD.js} +2 -2
  152. package/dist/cli/chunks/{detect-ROCCKX63.js → detect-R3CMY3ZB.js} +2 -2
  153. package/dist/cli/chunks/{dist-node-QGU7TJTW.js → dist-node-OALHZZ67.js} +2 -2
  154. package/dist/cli/chunks/{domain-handler-3UJHQPOR.js → domain-handler-QWZEBRVB.js} +2 -2
  155. package/dist/cli/chunks/{domain-transfer-R47ISVU5.js → domain-transfer-BO2XBDRA.js} +2 -2
  156. package/dist/cli/chunks/dream-XDWOQVNR.js +2 -0
  157. package/dist/cli/chunks/{embed-and-insert-pattern-ZVK7WSY2.js → embed-and-insert-pattern-YJJ5MHIV.js} +2 -2
  158. package/dist/cli/chunks/{eval-WNZWXFOW.js → eval-BIDGZOD7.js} +2 -2
  159. package/dist/cli/chunks/experience-capture-middleware-SBZNJVIN.js +40 -0
  160. package/dist/cli/chunks/{fast-paths-QPF47RZJ.js → fast-paths-W6FORZ7G.js} +2 -2
  161. package/dist/cli/chunks/{feature-flags-PGIG2W3G.js → feature-flags-25T4IUQL.js} +2 -2
  162. package/dist/cli/chunks/{feature-flags-2MAHHM66.js → feature-flags-A4YTFMSI.js} +2 -2
  163. package/dist/cli/chunks/{file-discovery-JL6FCXRB.js → file-discovery-S4GNW5SS.js} +2 -2
  164. package/dist/cli/chunks/{fleet-LMBZU2GU.js → fleet-QTXBVBXM.js} +3 -3
  165. package/dist/cli/chunks/{gnn-wrapper-GFNFVEER.js → gnn-wrapper-S3HPS6UZ.js} +2 -2
  166. package/dist/cli/chunks/{heartbeat-handler-YN7ES3AX.js → heartbeat-handler-Z536VVQ4.js} +4 -4
  167. package/dist/cli/chunks/{heartbeat-scheduler-SII2KJSQ.js → heartbeat-scheduler-ECHKRR2V.js} +2 -2
  168. package/dist/cli/chunks/hnsw-adapter-ELKAHTIH.js +2 -0
  169. package/dist/cli/chunks/hnsw-index-3VJYUSOM.js +2 -0
  170. package/dist/cli/chunks/{hnsw-legacy-bridge-CPMBYE7C.js → hnsw-legacy-bridge-NR2LB4MK.js} +2 -2
  171. package/dist/cli/chunks/hnswlib-node-VHJGVLVU.js +2 -0
  172. package/dist/cli/chunks/{hooks-EYSB7XDW.js → hooks-K6B7FOWK.js} +10 -10
  173. package/dist/cli/chunks/{hybrid-router-BR7O6WT2.js → hybrid-router-PWEAUPDI.js} +2 -2
  174. package/dist/cli/chunks/{hypergraph-engine-HAKGWDYX.js → hypergraph-engine-2GMPZADI.js} +2 -2
  175. package/dist/cli/chunks/{hypergraph-handler-UCI3LXUF.js → hypergraph-handler-7EZBLA7J.js} +3 -3
  176. package/dist/cli/chunks/impact-analyzer-4BLPFGDS.js +2 -0
  177. package/dist/cli/chunks/{init-handler-7RYGU3W5.js → init-handler-IC2REBTQ.js} +6 -6
  178. package/dist/cli/chunks/init-wizard-UR23AJFX.js +2 -0
  179. package/dist/cli/chunks/kernel-BTP323I5.js +2 -0
  180. package/dist/cli/chunks/{kilocode-installer-W6ITMEFA.js → kilocode-installer-O7CW3AWL.js} +2 -2
  181. package/dist/cli/chunks/{kiro-installer-2BO34D3O.js → kiro-installer-PCUKTCMG.js} +2 -2
  182. package/dist/cli/chunks/knowledge-graph-JH3O5ZMS.js +2 -0
  183. package/dist/cli/chunks/{learning-GEXYG72Z.js → learning-X6GZCD2J.js} +3 -3
  184. package/dist/cli/chunks/{llm-router-EGHA5YOC.js → llm-router-K7S7VYA3.js} +4 -4
  185. package/dist/cli/chunks/{load-VU2OOAEF.js → load-RHLRH7M5.js} +2 -2
  186. package/dist/cli/chunks/load-test-E6GTBB2W.js +2 -0
  187. package/dist/cli/chunks/{mcp-NVQFFQ2R.js → mcp-RGHX7REI.js} +2 -2
  188. package/dist/cli/chunks/{memory-JNXMKTZQ.js → memory-BDEEXPIV.js} +5 -5
  189. package/dist/cli/chunks/memory-backend-FAOO6R3B.js +2 -0
  190. package/dist/cli/chunks/{memory-handlers-NLGQ5I7K.js → memory-handlers-PR5ZSN5E.js} +2 -2
  191. package/dist/cli/chunks/{multi-model-executor-SG6OME2A.js → multi-model-executor-SGVRJWI5.js} +2 -2
  192. package/dist/cli/chunks/{opencode-installer-AY4JCZIM.js → opencode-installer-3ZWQ7Q5S.js} +2 -2
  193. package/dist/cli/chunks/{orchestrator-GWI7HQG6.js → orchestrator-O5EZXLG6.js} +5 -5
  194. package/dist/cli/chunks/{pipeline-7T6IAMC7.js → pipeline-LW7SFRRB.js} +2 -2
  195. package/dist/cli/chunks/{platform-IXUST66M.js → platform-DIISFS5U.js} +2 -2
  196. package/dist/cli/chunks/{plugin-PW7F6MVH.js → plugin-B563LDGV.js} +2 -2
  197. package/dist/cli/chunks/{prime-radiant-advanced-wasm-BUAZHZCM.js → prime-radiant-advanced-wasm-FJBQPN3U.js} +2 -2
  198. package/dist/cli/chunks/protocol-executor-AYBNZNRK.js +2 -0
  199. package/dist/cli/chunks/{protocol-handler-6746OC4P.js → protocol-handler-PVZNJNNP.js} +2 -2
  200. package/dist/cli/chunks/{prove-VYV5DQGC.js → prove-MYKQTKZM.js} +2 -2
  201. package/dist/cli/chunks/{provider-manager-GEO3CUOO.js → provider-manager-RDOMJIKC.js} +2 -2
  202. package/dist/cli/chunks/qe-reasoning-bank-LFMZCMKB.js +2 -0
  203. package/dist/cli/chunks/{quality-4XXENNNW.js → quality-OOXFIM76.js} +2 -2
  204. package/dist/cli/chunks/queen-coordinator-JEGURMXS.js +2 -0
  205. package/dist/cli/chunks/{real-embeddings-ZVEZVXVT.js → real-embeddings-JQVUQQKL.js} +2 -2
  206. package/dist/cli/chunks/{roocode-installer-ZRNDOIDL.js → roocode-installer-G7ZV5Z3V.js} +2 -2
  207. package/dist/cli/chunks/router-LMESYCAS.js +2 -0
  208. package/dist/cli/chunks/routing-feedback-3GOMFT5Q.js +2 -0
  209. package/dist/cli/chunks/{routing-handler-MPSJ7DDI.js → routing-handler-W5XOGRVI.js} +2 -2
  210. package/dist/cli/chunks/{ruvector-commands-V4BVCY2U.js → ruvector-commands-YBR64EE3.js} +2 -2
  211. package/dist/cli/chunks/{rvf-dual-writer-X4VNU5KH.js → rvf-dual-writer-XIDYK3CA.js} +2 -2
  212. package/dist/cli/chunks/{rvf-migration-adapter-KOYYJSNH.js → rvf-migration-adapter-6FJ7XRBL.js} +2 -2
  213. package/dist/cli/chunks/{rvf-migration-coordinator-SF5IBKTK.js → rvf-migration-coordinator-7GD7BGUG.js} +2 -2
  214. package/dist/cli/chunks/rvf-native-adapter-MEKCU4HV.js +2 -0
  215. package/dist/cli/chunks/safe-db-PZBRYCSI.js +2 -0
  216. package/dist/cli/chunks/schedule-NXQZQIBV.js +2 -0
  217. package/dist/cli/chunks/scheduler-I3HGTMNU.js +2 -0
  218. package/dist/cli/chunks/{security-AA5GBNNU.js → security-5RH45PGS.js} +3 -3
  219. package/dist/cli/chunks/shared-rvf-adapter-5QLSVTXS.js +2 -0
  220. package/dist/cli/chunks/{shared-rvf-dual-writer-EGP3BYIY.js → shared-rvf-dual-writer-A7T5EJ3W.js} +2 -2
  221. package/dist/cli/chunks/sqlite-persistence-3MEKZAPX.js +2 -0
  222. package/dist/cli/chunks/{status-handler-ARHPRXJ4.js → status-handler-LNNNK2AK.js} +2 -2
  223. package/dist/cli/chunks/{structural-health-IDV4RBZV.js → structural-health-7I7G6LFO.js} +2 -2
  224. package/dist/cli/chunks/{sync-7BRLSLDG.js → sync-QPWRLTD6.js} +2 -2
  225. package/dist/cli/chunks/{task-handler-XY42QA3K.js → task-handler-BMKDHVBD.js} +2 -2
  226. package/dist/cli/chunks/{task-handlers-QEHOKEJC.js → task-handlers-ECOL3VV6.js} +3 -3
  227. package/dist/cli/chunks/{test-TQIHDBEX.js → test-FY33BVTJ.js} +4 -4
  228. package/dist/cli/chunks/{test-scheduling-BBVOLGFT.js → test-scheduling-4NHGC3EB.js} +3 -3
  229. package/dist/cli/chunks/{token-bootstrap-BUHTWVEF.js → token-bootstrap-MAOYJSZN.js} +2 -2
  230. package/dist/cli/chunks/{token-usage-MRVQ7G3H.js → token-usage-TJPP4UFG.js} +2 -2
  231. package/dist/cli/chunks/{hnswlib-node-NWNBNU3W.js → transformers-QIGZ7SE7.js} +2 -2
  232. package/dist/cli/chunks/{tree-sitter-wasm-parser-6GDZQNFV.js → tree-sitter-wasm-parser-CVKNF5NP.js} +2 -2
  233. package/dist/cli/chunks/{types-F2LWFMRI.js → types-FCGVB2IX.js} +2 -2
  234. package/dist/cli/chunks/unified-memory-U4CPBW5V.js +2 -0
  235. package/dist/cli/chunks/unified-memory-hnsw-BYBD2V33.js +2 -0
  236. package/dist/cli/chunks/unified-persistence-LAUTFWNC.js +2 -0
  237. package/dist/cli/chunks/{upgrade-N676MSDA.js → upgrade-HWJRLW6H.js} +2 -2
  238. package/dist/cli/chunks/{validate-56AA6YYM.js → validate-Z45LLWQQ.js} +2 -2
  239. package/dist/cli/chunks/{validate-swarm-YPHV7MMC.js → validate-swarm-VAEKMIJB.js} +2 -2
  240. package/dist/cli/chunks/{vibium-ABPFT3DX.js → vibium-O7MMGI45.js} +2 -2
  241. package/dist/cli/chunks/visual-security-XVWGWA4J.js +2 -0
  242. package/dist/cli/chunks/{web-tree-sitter-KN4PWKMV.js → web-tree-sitter-G3TTBGKP.js} +2 -2
  243. package/dist/cli/chunks/{windsurf-installer-IZOJBDNN.js → windsurf-installer-II3ZTH55.js} +2 -2
  244. package/dist/cli/chunks/witness-chain-CTIZD4GL.js +2 -0
  245. package/dist/cli/chunks/{witness-chain-H2DM5WMB.js → witness-chain-KYMMCOIV.js} +2 -2
  246. package/dist/cli/chunks/{workflow-R42PK45F.js → workflow-P4GQ3NJK.js} +4 -4
  247. package/dist/cli/chunks/workflow-orchestrator-NG3KLTLJ.js +2 -0
  248. package/dist/cli/chunks/{wrappers-6TIJNWN4.js → wrappers-7MWZ6R6U.js} +2 -2
  249. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +6 -0
  250. package/dist/domains/code-intelligence/coordinator.js +20 -0
  251. package/dist/integrations/embeddings/index/HNSWIndex.js +16 -6
  252. package/dist/integrations/ruvector/hypergraph-engine.d.ts +45 -0
  253. package/dist/integrations/ruvector/hypergraph-engine.js +102 -0
  254. package/dist/integrations/ruvector/shared-rvf-adapter.js +110 -2
  255. package/dist/learning/experience-consolidation.d.ts +19 -3
  256. package/dist/learning/experience-consolidation.js +57 -27
  257. package/dist/learning/pattern-store.js +38 -1
  258. package/dist/mcp/bundle.js +307 -303
  259. package/package.json +2 -2
  260. package/scripts/preinstall.cjs +54 -0
  261. package/dist/cli/chunks/adapter-UOX57IAN.js +0 -2
  262. package/dist/cli/chunks/aqe-learning-engine-KZES2SKE.js +0 -2
  263. package/dist/cli/chunks/base-7MXMBRSW.js +0 -2
  264. package/dist/cli/chunks/browser-workflow-4C5R54CZ.js +0 -2
  265. package/dist/cli/chunks/chunk-35HDLA22.js +0 -2
  266. package/dist/cli/chunks/chunk-F32R4LVS.js +0 -2
  267. package/dist/cli/chunks/chunk-ZTWHRDUY.js +0 -2
  268. package/dist/cli/chunks/client-S5TFLKHN.js +0 -2
  269. package/dist/cli/chunks/cross-domain-router-GZG5GU7Q.js +0 -2
  270. package/dist/cli/chunks/dream-PGYTIOQS.js +0 -2
  271. package/dist/cli/chunks/hnsw-adapter-ANJKCXK6.js +0 -2
  272. package/dist/cli/chunks/hnsw-index-D4CJEP7L.js +0 -2
  273. package/dist/cli/chunks/impact-analyzer-55JW3OK6.js +0 -2
  274. package/dist/cli/chunks/init-wizard-MWKJNVB2.js +0 -2
  275. package/dist/cli/chunks/kernel-5MKKDS4J.js +0 -2
  276. package/dist/cli/chunks/knowledge-graph-2A7AE7L7.js +0 -2
  277. package/dist/cli/chunks/load-test-UD4ZXCGG.js +0 -2
  278. package/dist/cli/chunks/memory-backend-X3Z4IAYG.js +0 -2
  279. package/dist/cli/chunks/protocol-executor-AB6KPFK5.js +0 -2
  280. package/dist/cli/chunks/qe-reasoning-bank-Y4IDDIYA.js +0 -2
  281. package/dist/cli/chunks/queen-coordinator-GBSTXGA2.js +0 -2
  282. package/dist/cli/chunks/router-JA2X4MF6.js +0 -2
  283. package/dist/cli/chunks/routing-feedback-YCVJIWFM.js +0 -2
  284. package/dist/cli/chunks/rvf-native-adapter-5YN7EEB5.js +0 -2
  285. package/dist/cli/chunks/safe-db-S46Y7IC5.js +0 -2
  286. package/dist/cli/chunks/schedule-KSDHFWSY.js +0 -2
  287. package/dist/cli/chunks/scheduler-PLFJHU54.js +0 -2
  288. package/dist/cli/chunks/shared-rvf-adapter-MLXVW4N6.js +0 -2
  289. package/dist/cli/chunks/sqlite-persistence-RK3JWKB4.js +0 -2
  290. package/dist/cli/chunks/transformers-3PFLFSWR.js +0 -2
  291. package/dist/cli/chunks/unified-memory-JVZZMZRE.js +0 -2
  292. package/dist/cli/chunks/unified-memory-hnsw-EJJHCMFR.js +0 -2
  293. package/dist/cli/chunks/unified-persistence-IEKOYCBL.js +0 -2
  294. package/dist/cli/chunks/visual-security-APS7K3TZ.js +0 -2
  295. package/dist/cli/chunks/witness-chain-DMHO7R75.js +0 -2
  296. package/dist/cli/chunks/workflow-orchestrator-BDHRNVOG.js +0 -2
@@ -1,17 +1,17 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.20");process.exit(0)}
2
- import{a as w,b as A,c as O,e as D,f as $}from"./chunk-MXAEZHW6.js";import{b as S,d as z}from"./chunk-JCPXG42O.js";import{a as b,c as F}from"./chunk-NN6VRHNL.js";import{i as v}from"./chunk-NQIOXSHW.js";import*as I from"node:path";$();z();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],R=class{ensureSchema(e){e.transaction(()=>{e.exec(w),e.exec(A),e.exec(O)})()}schemaExists(e){return D(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function H(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function f(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function C(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},_=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new R}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=v(),r={id:t,...e},i=H(r);return this.config.db.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.22");process.exit(0)}
2
+ import{a as w,b as A,c as O,e as D,f as z}from"./chunk-7TASYE2O.js";import{b as S,d as $}from"./chunk-PUBADXN6.js";import{a as N,c as F}from"./chunk-C32ZD3IM.js";import{i as v}from"./chunk-7TWDEXR4.js";import*as I from"node:path";z();$();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],b=class{ensureSchema(e){e.transaction(()=>{e.exec(w),e.exec(A),e.exec(O)})()}schemaExists(e){return D(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function C(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function T(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function H(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},R=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new b}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=v(),r={id:t,...e},s=C(r);return this.config.db.prepare(`
3
3
  INSERT INTO hypergraph_nodes (id, type, name, file_path, line_start, line_end, complexity, coverage, metadata, embedding)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5
- `).run(i.id,i.type,i.name,i.file_path,i.line_start,i.line_end,i.complexity,i.coverage,i.metadata,i.embedding),t}async addEdge(e){this.ensureInitialized();let t=x(e.sourceId,e.targetId,e.type),r={id:t,...e},i=M(r);return this.config.db.prepare(`
5
+ `).run(s.id,s.type,s.name,s.file_path,s.line_start,s.line_end,s.complexity,s.coverage,s.metadata,s.embedding),t}async addEdge(e){this.ensureInitialized();let t=x(e.sourceId,e.targetId,e.type),r={id:t,...e},s=M(r);return this.config.db.prepare(`
6
6
  INSERT OR REPLACE INTO hypergraph_edges (id, source_id, target_id, type, weight, properties)
7
7
  VALUES (?, ?, ?, ?, ?, ?)
8
- `).run(i.id,i.source_id,i.target_id,i.type,i.weight,i.properties),t}async getNode(e){this.ensureInitialized();let t=this.config.db.prepare("SELECT * FROM hypergraph_nodes WHERE id = ?").get(e);return t?f(t):null}async getEdge(e){this.ensureInitialized();let t=this.config.db.prepare("SELECT * FROM hypergraph_edges WHERE id = ?").get(e);return t?C(t):null}async updateNode(e,t){this.ensureInitialized();let r=await this.getNode(e);if(!r)throw new Error(`Node not found: ${e}`);let i={...r,...t},s=H(i);this.config.db.prepare(`
8
+ `).run(s.id,s.source_id,s.target_id,s.type,s.weight,s.properties),t}async getNode(e){this.ensureInitialized();let t=this.config.db.prepare("SELECT * FROM hypergraph_nodes WHERE id = ?").get(e);return t?T(t):null}async getEdge(e){this.ensureInitialized();let t=this.config.db.prepare("SELECT * FROM hypergraph_edges WHERE id = ?").get(e);return t?H(t):null}async updateNode(e,t){this.ensureInitialized();let r=await this.getNode(e);if(!r)throw new Error(`Node not found: ${e}`);let s={...r,...t},o=C(s);this.config.db.prepare(`
9
9
  UPDATE hypergraph_nodes
10
10
  SET type = ?, name = ?, file_path = ?, line_start = ?, line_end = ?,
11
11
  complexity = ?, coverage = ?, metadata = ?, embedding = ?,
12
12
  updated_at = datetime('now')
13
13
  WHERE id = ?
14
- `).run(s.type,s.name,s.file_path,s.line_start,s.line_end,s.complexity,s.coverage,s.metadata,s.embedding,e)}async deleteNode(e){this.ensureInitialized(),this.config.db.prepare("DELETE FROM hypergraph_edges WHERE source_id = ? OR target_id = ?").run(e,e),this.config.db.prepare("DELETE FROM hypergraph_nodes WHERE id = ?").run(e)}async deleteEdge(e){this.ensureInitialized(),this.config.db.prepare("DELETE FROM hypergraph_edges WHERE id = ?").run(e)}async findNodes(e){this.ensureInitialized();let t=[],r=[];if(e.type){let u=Array.isArray(e.type)?e.type:[e.type];t.push(`type IN (${u.map(()=>"?").join(", ")})`),r.push(...u)}e.filePath&&(e.filePath.includes("%")?t.push("file_path LIKE ?"):t.push("file_path = ?"),r.push(e.filePath)),e.name&&typeof e.name=="string"&&(t.push("name = ?"),r.push(e.name)),e.minComplexity!==void 0&&(t.push("complexity >= ?"),r.push(e.minComplexity)),e.maxComplexity!==void 0&&(t.push("complexity <= ?"),r.push(e.maxComplexity)),e.minCoverage!==void 0&&(t.push("coverage >= ?"),r.push(e.minCoverage)),e.maxCoverage!==void 0&&(t.push("coverage <= ?"),r.push(e.maxCoverage));let i=t.length>0?`WHERE ${t.join(" AND ")}`:"",s=e.limit??this.config.maxQueryResults,d=`SELECT * FROM hypergraph_nodes ${i} LIMIT ?`;r.push(s);let c=this.config.db.prepare(d).all(...r).map(f);return e.name instanceof RegExp&&(c=c.filter(u=>e.name instanceof RegExp&&e.name.test(u.name))),c}async findEdges(e){this.ensureInitialized();let t=[],r=[];if(e.type){let c=Array.isArray(e.type)?e.type:[e.type];t.push(`type IN (${c.map(()=>"?").join(", ")})`),r.push(...c)}e.sourceId&&(t.push("source_id = ?"),r.push(e.sourceId)),e.targetId&&(t.push("target_id = ?"),r.push(e.targetId)),e.minWeight!==void 0&&(t.push("weight >= ?"),r.push(e.minWeight));let i=t.length>0?`WHERE ${t.join(" AND ")}`:"",s=e.limit??this.config.maxQueryResults,d=`SELECT * FROM hypergraph_edges ${i} LIMIT ?`;return r.push(s),this.config.db.prepare(d).all(...r).map(C)}async traverse(e,t=[],r=5){this.ensureInitialized();let i=new Map,s=new Map,d=[],g=0,c=[{nodeId:e,depth:0,path:{nodes:[e],edges:[]}}],u=Math.min(r,this.config.maxTraversalDepth);for(;c.length>0;){let{nodeId:a,depth:p,path:o}=c.shift();if(!i.has(a)){let l=await this.getNode(a);l&&i.set(a,l)}if(g=Math.max(g,p),p>=u){d.push(o);continue}let h={sourceId:a};t.length>0&&(h.type=t);let y=await this.findEdges(h);if(y.length===0){d.push(o);continue}for(let l of y)if(!s.has(l.id)){s.set(l.id,l);let m={nodes:[...o.nodes,l.targetId],edges:[...o.edges,l.id]};c.push({nodeId:l.targetId,depth:p+1,path:m})}}return{nodes:Array.from(i.values()),edges:Array.from(s.values()),paths:d,maxDepthReached:g}}async findUntestedFunctions(){return this.ensureInitialized(),this.config.db.prepare(`
14
+ `).run(o.type,o.name,o.file_path,o.line_start,o.line_end,o.complexity,o.coverage,o.metadata,o.embedding,e)}async deleteNode(e){this.ensureInitialized(),this.config.db.prepare("DELETE FROM hypergraph_edges WHERE source_id = ? OR target_id = ?").run(e,e),this.config.db.prepare("DELETE FROM hypergraph_nodes WHERE id = ?").run(e)}async deleteEdge(e){this.ensureInitialized(),this.config.db.prepare("DELETE FROM hypergraph_edges WHERE id = ?").run(e)}async findNodes(e){this.ensureInitialized();let t=[],r=[];if(e.type){let u=Array.isArray(e.type)?e.type:[e.type];t.push(`type IN (${u.map(()=>"?").join(", ")})`),r.push(...u)}e.filePath&&(e.filePath.includes("%")?t.push("file_path LIKE ?"):t.push("file_path = ?"),r.push(e.filePath)),e.name&&typeof e.name=="string"&&(t.push("name = ?"),r.push(e.name)),e.minComplexity!==void 0&&(t.push("complexity >= ?"),r.push(e.minComplexity)),e.maxComplexity!==void 0&&(t.push("complexity <= ?"),r.push(e.maxComplexity)),e.minCoverage!==void 0&&(t.push("coverage >= ?"),r.push(e.minCoverage)),e.maxCoverage!==void 0&&(t.push("coverage <= ?"),r.push(e.maxCoverage));let s=t.length>0?`WHERE ${t.join(" AND ")}`:"",o=e.limit??this.config.maxQueryResults,d=`SELECT * FROM hypergraph_nodes ${s} LIMIT ?`;r.push(o);let c=this.config.db.prepare(d).all(...r).map(T);return e.name instanceof RegExp&&(c=c.filter(u=>e.name instanceof RegExp&&e.name.test(u.name))),c}async findEdges(e){this.ensureInitialized();let t=[],r=[];if(e.type){let c=Array.isArray(e.type)?e.type:[e.type];t.push(`type IN (${c.map(()=>"?").join(", ")})`),r.push(...c)}e.sourceId&&(t.push("source_id = ?"),r.push(e.sourceId)),e.targetId&&(t.push("target_id = ?"),r.push(e.targetId)),e.minWeight!==void 0&&(t.push("weight >= ?"),r.push(e.minWeight));let s=t.length>0?`WHERE ${t.join(" AND ")}`:"",o=e.limit??this.config.maxQueryResults,d=`SELECT * FROM hypergraph_edges ${s} LIMIT ?`;return r.push(o),this.config.db.prepare(d).all(...r).map(H)}async traverse(e,t=[],r=5){this.ensureInitialized();let s=new Map,o=new Map,d=[],p=0,c=[{nodeId:e,depth:0,path:{nodes:[e],edges:[]}}],u=Math.min(r,this.config.maxTraversalDepth);for(;c.length>0;){let{nodeId:a,depth:g,path:i}=c.shift();if(!s.has(a)){let l=await this.getNode(a);l&&s.set(a,l)}if(p=Math.max(p,g),g>=u){d.push(i);continue}let h={sourceId:a};t.length>0&&(h.type=t);let y=await this.findEdges(h);if(y.length===0){d.push(i);continue}for(let l of y)if(!o.has(l.id)){o.set(l.id,l);let m={nodes:[...i.nodes,l.targetId],edges:[...i.edges,l.id]};c.push({nodeId:l.targetId,depth:g+1,path:m})}}return{nodes:Array.from(s.values()),edges:Array.from(o.values()),paths:d,maxDepthReached:p}}async findUntestedFunctions(){return this.ensureInitialized(),this.config.db.prepare(`
15
15
  SELECT n.* FROM hypergraph_nodes n
16
16
  WHERE n.type = 'function'
17
17
  AND NOT EXISTS (
@@ -23,7 +23,7 @@ import{a as w,b as A,c as O,e as D,f as $}from"./chunk-MXAEZHW6.js";import{b as
23
23
  )
24
24
  ORDER BY n.complexity DESC NULLS LAST
25
25
  LIMIT ?
26
- `).all(this.config.maxQueryResults).map(f)}async findImpactedTests(e){if(this.ensureInitialized(),e.length===0)return[];let r=`
26
+ `).all(this.config.maxQueryResults).map(T)}async findImpactedTests(e){if(this.ensureInitialized(),e.length===0)return[];let r=`
27
27
  SELECT DISTINCT t.* FROM hypergraph_nodes t
28
28
  JOIN hypergraph_edges e ON e.source_id = t.id
29
29
  JOIN hypergraph_nodes f ON f.id = e.target_id
@@ -32,38 +32,46 @@ import{a as w,b as A,c as O,e as D,f as $}from"./chunk-MXAEZHW6.js";import{b as
32
32
  AND f.type = 'function'
33
33
  AND f.file_path IN (${e.map(()=>"?").join(", ")})
34
34
  LIMIT ?
35
- `,i=[...e,this.config.maxQueryResults];return this.config.db.prepare(r).all(...i).map(f)}async findCoverageGaps(e=50){return this.ensureInitialized(),this.config.db.prepare(`
35
+ `,s=[...e,this.config.maxQueryResults];return this.config.db.prepare(r).all(...s).map(T)}async findCoverageGaps(e=50){return this.ensureInitialized(),this.config.db.prepare(`
36
36
  SELECT * FROM hypergraph_nodes
37
37
  WHERE type = 'function'
38
38
  AND coverage IS NOT NULL
39
39
  AND coverage <= ?
40
40
  ORDER BY coverage ASC, complexity DESC NULLS LAST
41
41
  LIMIT ?
42
- `).all(e,this.config.maxQueryResults).map(f)}async findModuleDependencies(e){this.ensureInitialized();let t=await this.findNodes({type:"module",filePath:e,limit:1});if(t.length===0){let a=await this.findNodes({type:"file",filePath:e,limit:1});if(a.length===0)throw new Error(`Module not found: ${e}`);t.push(a[0])}let r=t[0],i=await this.findEdges({sourceId:r.id,type:["imports","depends_on"]}),s=[];for(let a of i){let p=await this.getNode(a.targetId);p&&s.push(p)}let d=await this.findEdges({targetId:r.id,type:["imports","depends_on"]}),g=[];for(let a of d){let p=await this.getNode(a.sourceId);p&&g.push(p)}let c=await this.traverse(r.id,["imports","depends_on"],5),u=c.nodes.filter(a=>a.id!==r.id);return{module:r,directDependencies:s,dependents:g,transitiveDependencies:u,maxDependencyDepth:c.maxDepthReached}}async buildFromIndexResult(e){this.ensureInitialized();let t=Date.now(),r=0,i=0,s=0,d=[];return this.config.db.transaction(()=>{for(let a of e.files)try{let p=`file:${a.path}`;this.config.db.prepare("SELECT id FROM hypergraph_nodes WHERE id = ?").get(p)?i++:(this.config.db.prepare(`
42
+ `).all(e,this.config.maxQueryResults).map(T)}async findModuleDependencies(e){this.ensureInitialized();let t=await this.findNodes({type:"module",filePath:e,limit:1});if(t.length===0){let a=await this.findNodes({type:"file",filePath:e,limit:1});if(a.length===0)throw new Error(`Module not found: ${e}`);t.push(a[0])}let r=t[0],s=await this.findEdges({sourceId:r.id,type:["imports","depends_on"]}),o=[];for(let a of s){let g=await this.getNode(a.targetId);g&&o.push(g)}let d=await this.findEdges({targetId:r.id,type:["imports","depends_on"]}),p=[];for(let a of d){let g=await this.getNode(a.sourceId);g&&p.push(g)}let c=await this.traverse(r.id,["imports","depends_on"],5),u=c.nodes.filter(a=>a.id!==r.id);return{module:r,directDependencies:o,dependents:p,transitiveDependencies:u,maxDependencyDepth:c.maxDepthReached}}async buildFromIndexResult(e){this.ensureInitialized();let t=Date.now(),r=0,s=0,o=0,d=[];return this.config.db.transaction(()=>{for(let a of e.files)try{let g=`file:${a.path}`;this.config.db.prepare("SELECT id FROM hypergraph_nodes WHERE id = ?").get(g)?s++:(this.config.db.prepare(`
43
43
  INSERT INTO hypergraph_nodes (id, type, name, file_path)
44
44
  VALUES (?, 'file', ?, ?)
45
- `).run(p,a.path.split("/").pop()||a.path,a.path),r++)}catch(p){d.push({entity:`file:${a.path}`,error:b(p)})}for(let a of e.files){let p=`file:${a.path}`;for(let o of a.entities)try{let h=`${o.type}:${a.path}:${o.name}`,y=this.mapEntityTypeToNodeType(o.type);this.config.db.prepare("SELECT id FROM hypergraph_nodes WHERE id = ?").get(h)?(this.config.db.prepare(`
45
+ `).run(g,a.path.split("/").pop()||a.path,a.path),r++)}catch(g){d.push({entity:`file:${a.path}`,error:N(g)})}for(let a of e.files){let g=`file:${a.path}`;for(let i of a.entities)try{let h=`${i.type}:${a.path}:${i.name}`,y=this.mapEntityTypeToNodeType(i.type);this.config.db.prepare("SELECT id FROM hypergraph_nodes WHERE id = ?").get(h)?(this.config.db.prepare(`
46
46
  UPDATE hypergraph_nodes
47
47
  SET line_start = ?, line_end = ?, complexity = ?, coverage = ?,
48
48
  updated_at = datetime('now')
49
49
  WHERE id = ?
50
- `).run(o.lineStart,o.lineEnd,o.complexity,o.coverage,h),i++):(this.config.db.prepare(`
50
+ `).run(i.lineStart,i.lineEnd,i.complexity,i.coverage,h),s++):(this.config.db.prepare(`
51
51
  INSERT INTO hypergraph_nodes (id, type, name, file_path, line_start, line_end, complexity, coverage)
52
52
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
53
- `).run(h,y,o.name,a.path,o.lineStart,o.lineEnd,o.complexity,o.coverage),r++);try{let m=x(p,h,"contains");this.config.db.prepare(`
53
+ `).run(h,y,i.name,a.path,i.lineStart,i.lineEnd,i.complexity,i.coverage),r++);try{let m=x(g,h,"contains");this.config.db.prepare(`
54
54
  INSERT OR REPLACE INTO hypergraph_edges (id, source_id, target_id, type, weight)
55
55
  VALUES (?, ?, ?, 'contains', 1.0)
56
- `).run(m,p,h),s++}catch(m){d.push({entity:`contains:${o.type}:${o.name}`,error:b(m)})}}catch(h){d.push({entity:`${o.type}:${o.name}`,error:b(h)})}}let c=[".ts",".tsx",".js",".jsx",".py",".mjs",".cjs"],u=["/index.ts","/index.tsx","/index.js","/index.jsx","/index.py"];for(let a of e.files){let p=`file:${a.path}`;for(let o of a.imports)try{let h=o;(o.startsWith("./")||o.startsWith("../"))&&(h=I.resolve(I.dirname(a.path),o));let y=`file:${h}`,l=this.config.db.prepare("SELECT id FROM hypergraph_nodes WHERE id = ?"),m=l.get(y);if(!m)for(let E of c){let T=y+E,N=l.get(T);if(N){y=T,m=N;break}}if(!m)for(let E of u){let T=y+E,N=l.get(T);if(N){y=T,m=N;break}}if(m){let E=x(p,y,"imports");this.config.db.prepare(`
56
+ `).run(m,g,h),o++}catch(m){d.push({entity:`contains:${i.type}:${i.name}`,error:N(m)})}}catch(h){d.push({entity:`${i.type}:${i.name}`,error:N(h)})}}let c=[".ts",".tsx",".js",".jsx",".py",".mjs",".cjs"],u=["/index.ts","/index.tsx","/index.js","/index.jsx","/index.py"];for(let a of e.files){let g=`file:${a.path}`;for(let i of a.imports)try{let h=i;(i.startsWith("./")||i.startsWith("../"))&&(h=I.resolve(I.dirname(a.path),i));let y=`file:${h}`,l=this.config.db.prepare("SELECT id FROM hypergraph_nodes WHERE id = ?"),m=l.get(y);if(!m)for(let f of c){let E=y+f,_=l.get(E);if(_){y=E,m=_;break}}if(!m)for(let f of u){let E=y+f,_=l.get(E);if(_){y=E,m=_;break}}if(m){let f=x(g,y,"imports");this.config.db.prepare(`
57
57
  INSERT OR REPLACE INTO hypergraph_edges (id, source_id, target_id, type, weight)
58
58
  VALUES (?, ?, ?, 'imports', 1.0)
59
- `).run(E,p,y),s++}}catch(h){d.push({entity:`import:${o}`,error:b(h)})}}})(),{nodesCreated:r,nodesUpdated:i,edgesCreated:s,durationMs:Date.now()-t,errors:d}}async syncWithKnowledgeGraph(e){this.ensureInitialized();let t=Date.now(),r=0,i=0,s=0,d=0,g=await this.findNodes({});for(let u of g){let a=await e.getNode(u.id);r++}return i=(await this.findEdges({})).length,{nodesSynced:r,edgesSynced:i,nodesAdded:s,nodesRemoved:d,durationMs:Date.now()-t}}async getStats(){this.ensureInitialized();let e=this.schemaManager.getStats(this.config.db),t=this.config.db.prepare(`
59
+ `).run(f,g,y),o++}}catch(h){d.push({entity:`import:${i}`,error:N(h)})}}})(),{nodesCreated:r,nodesUpdated:s,edgesCreated:o,durationMs:Date.now()-t,errors:d}}async syncWithKnowledgeGraph(e){this.ensureInitialized();let t=Date.now(),r=0,s=0,o=0,d=0,p=await this.findNodes({});for(let u of p){let a=await e.getNode(u.id);r++}return s=(await this.findEdges({})).length,{nodesSynced:r,edgesSynced:s,nodesAdded:o,nodesRemoved:d,durationMs:Date.now()-t}}async getStats(){this.ensureInitialized();let e=this.schemaManager.getStats(this.config.db),t=this.config.db.prepare(`
60
60
  SELECT type, COUNT(*) as count FROM hypergraph_nodes GROUP BY type
61
- `).all(),r={function:0,module:0,test:0,file:0,class:0};for(let g of t)g.type in r&&(r[g.type]=g.count);let i=this.config.db.prepare(`
61
+ `).all(),r={function:0,module:0,test:0,file:0,class:0};for(let p of t)p.type in r&&(r[p.type]=p.count);let s=this.config.db.prepare(`
62
62
  SELECT type, COUNT(*) as count FROM hypergraph_edges GROUP BY type
63
- `).all(),s={calls:0,imports:0,tests:0,depends_on:0,covers:0,contains:0};for(let g of i)g.type in s&&(s[g.type]=g.count);let d=this.config.db.prepare(`
63
+ `).all(),o={calls:0,imports:0,tests:0,depends_on:0,covers:0,contains:0};for(let p of s)p.type in o&&(o[p.type]=p.count);let d=this.config.db.prepare(`
64
64
  SELECT
65
65
  AVG(complexity) as avg_complexity,
66
66
  AVG(coverage) as avg_coverage,
67
67
  COUNT(CASE WHEN embedding IS NOT NULL THEN 1 END) as nodes_with_embeddings
68
68
  FROM hypergraph_nodes
69
- `).get();return{totalNodes:e.nodeCount,totalEdges:e.edgeCount,nodesByType:r,edgesByType:s,avgComplexity:d.avg_complexity??0,avgCoverage:d.avg_coverage??0,nodesWithEmbeddings:d.nodes_with_embeddings}}ensureInitialized(){if(!this.initialized)throw new Error("HypergraphEngine not initialized. Call initialize() first.")}mapEntityTypeToNodeType(e){return{function:"function",class:"class",module:"module",interface:"module",file:"file",test:"test"}[e]??"function"}};async function Q(n){let e=new _(n);return await e.initialize(),e}function J(n){return new _(n)}var X=_;export{B as a,_ as b,Q as c,J as d,X as e};
69
+ `).get();return{totalNodes:e.nodeCount,totalEdges:e.edgeCount,nodesByType:r,edgesByType:o,avgComplexity:d.avg_complexity??0,avgCoverage:d.avg_coverage??0,nodesWithEmbeddings:d.nodes_with_embeddings}}ensureInitialized(){if(!this.initialized)throw new Error("HypergraphEngine not initialized. Call initialize() first.")}mapEntityTypeToNodeType(e){return{function:"function",class:"class",module:"module",interface:"module",file:"file",test:"test"}[e]??"function"}async synthesizeTestCoverage(e){this.ensureInitialized();let t=e?.testPathPatterns??j,r=0,s=0,o=this.config.db.prepare(`SELECT id, file_path FROM hypergraph_nodes
70
+ WHERE type IN ('file', 'test') AND file_path IS NOT NULL`).all(),d=[];for(let i of o)t.some(h=>h.test(i.file_path))&&d.push(i.id);if(d.length===0)return{testsTagged:0,coversCreated:0};let p=this.config.db.prepare(`UPDATE hypergraph_nodes SET type = 'test', updated_at = datetime('now')
71
+ WHERE id = ? AND type = 'file'`),c=this.config.db.prepare(`SELECT target_id FROM hypergraph_edges
72
+ WHERE source_id = ? AND type = 'imports'`),u=this.config.db.prepare(`SELECT n.id AS id FROM hypergraph_nodes n
73
+ JOIN hypergraph_edges e ON e.target_id = n.id
74
+ WHERE e.source_id = ? AND e.type = 'contains' AND n.type = 'function'`),a=this.config.db.prepare(`
75
+ INSERT OR REPLACE INTO hypergraph_edges (id, source_id, target_id, type, weight)
76
+ VALUES (?, ?, ?, 'covers', 1.0)
77
+ `);return this.config.db.transaction(()=>{for(let i of d){p.run(i).changes>0&&r++;let y=c.all(i).map(l=>l.target_id);for(let l of y){let m=u.all(l).map(f=>f.id);for(let f of m){let E=`${i}--covers-->${f}`;a.run(E,i,f),s++}}}})(),{testsTagged:r,coversCreated:s}}},j=[/\.test\.[tj]sx?$/,/\.spec\.[tj]sx?$/,/_test\.[tj]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/];async function Q(n){let e=new R(n);return await e.initialize(),e}function X(n){return new R(n)}var K=R;export{B as a,R as b,Q as c,X as d,K as e};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.20");process.exit(0)}
2
- import{a as W}from"./chunk-3ZHUKLU7.js";import{c as V,d as q}from"./chunk-BKGCMWFL.js";import{c as M}from"./chunk-SYXPLFK7.js";import{a as $}from"./chunk-F32R4LVS.js";import{c as N}from"./chunk-MIST354H.js";import{b as D,d as H}from"./chunk-JCPXG42O.js";import{a as E,c as k}from"./chunk-NN6VRHNL.js";import{i as y}from"./chunk-NQIOXSHW.js";import{a as R,b as U,d as J}from"./chunk-AFMLL2G3.js";var P={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};H();k();var A=class{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...P,...e}}async initialize(){if(!this.initialized)try{if(this.persistence=M(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.prepareStatements(),this.initialized=!0,this.config.debug){let e=await this.getStats();console.log(`[ConceptGraph] Initialized: ${this.persistence.getDbPath()}`,e)}}catch(e){throw new Error(`Failed to initialize ConceptGraph: ${E(e)}`)}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertNode",this.db.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.22");process.exit(0)}
2
+ import{a as W}from"./chunk-QH5PMTYD.js";import{c as V,d as q}from"./chunk-LSPQUQZQ.js";import{c as M}from"./chunk-ZIRSR3CR.js";import{a as $}from"./chunk-D4GHYV5T.js";import{c as N}from"./chunk-QKDYDDO6.js";import{b as D,d as H}from"./chunk-PUBADXN6.js";import{a as E,c as k}from"./chunk-C32ZD3IM.js";import{i as y}from"./chunk-7TWDEXR4.js";import{a as R,b as U,d as J}from"./chunk-EBFG55L3.js";var P={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};H();k();var A=class{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...P,...e}}async initialize(){if(!this.initialized)try{if(this.persistence=M(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.prepareStatements(),this.initialized=!0,this.config.debug){let e=await this.getStats();console.log(`[ConceptGraph] Initialized: ${this.persistence.getDbPath()}`,e)}}catch(e){throw new Error(`Failed to initialize ConceptGraph: ${E(e)}`)}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertNode",this.db.prepare(`
3
3
  INSERT INTO concept_nodes
4
4
  (id, concept_type, content, embedding, activation_level, last_activated, pattern_id, metadata)
5
5
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
@@ -59,7 +59,7 @@ import{a as W}from"./chunk-3ZHUKLU7.js";import{c as V,d as q}from"./chunk-BKGCMW
59
59
  ORDER BY weight DESC
60
60
  LIMIT -1 OFFSET ?
61
61
  )
62
- `).run(s,e);a+=c.changes}return a})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,a=t.get().count,r={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)r[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:a,byType:r,avgEdgesPerNode:i>0?a/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?D(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function K(h){return new A(h)}J();function Z(h,e){if(e<0||e>=h.length)return h[0]??0;let t=0,n=h.length-1;for(;t<n;){let i=t+n>>1;if(h[i]<h[t]){let s=h[t];h[t]=h[i],h[i]=s}if(h[n]<h[t]){let s=h[t];h[t]=h[n],h[n]=s}if(h[i]<h[n]){let s=h[i];h[i]=h[n],h[n]=s}let a=h[n],r=t;for(let s=t;s<n;s++)if(h[s]<=a){let c=h[r];h[r]=h[s],h[s]=c,r++}let o=h[r];if(h[r]=h[n],h[n]=o,r===e)return h[r];r<e?t=r+1:n=r-1}return h[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},S=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(d=>this.graph.getConcept(d)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let d of i)this.graph.setActivation(d,t),this.recordActivation(d,t);let a=0,r=t,o=0,s=0;for(;a<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),l=this.graph.getActiveNodes(this.config.threshold);for(let u of l)u.activationLevel>r&&(r=u.activationLevel);if(l.length===o&&d===0){if(s++,s>=3)break}else s=0;o=l.length,a++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,l)=>l.activation-d.activation),p=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:a,nodesActivated:c.length,peakActivation:r,activatedNodes:c,novelAssociations:p.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,a=0,r=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let d=U(0,o.length),l=o[d];if(l){let u=this.config.noiseLevel+R()*this.config.noiseLevel*2,m=l.activationLevel,v=Math.min(1,m+u+.3);this.graph.setActivation(l.id,v);let f=await this.spread([l.id],v,s);i+=f.iterations,f.peakActivation>a&&(a=f.peakActivation);for(let b of f.activatedNodes)r.add(b.nodeId);for(let b of f.novelAssociations)n.push(b)}if(Date.now()>=s)break;await this.sleep(50+R()*50)}let c=this.deduplicateAssociations(n),p=Array.from(r).map(d=>{let l=this.graph.getConcept(d);return{nodeId:d,activation:l?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,l)=>l.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:p.length,peakActivation:a,activatedNodes:p,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((r,o)=>o.activationLevel-r.activationLevel).slice(0,i));let a=[];for(let r=0;r<n.length;r++)for(let o=r+1;o<n.length;o++){let s=n[r],c=n[o],p=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),l=this.graph.getEdge(c.id,s.id),u=d!==void 0||l!==void 0,m=d?.weight??l?.weight??0,v=!u||m<.3;p>.3&&(a.push({source:s,target:c,coActivation:p,isNovel:v}),this.trackCoActivation(s.id,c.id))}return a.sort((r,o)=>r.isNovel!==o.isNovel?r.isNovel?-1:1:o.coActivation-r.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=B)return;let e=Math.floor(B*F),t=this.activationHistory.size-e,n=Array.from(this.activationHistory.keys()).slice(0,t);for(let i of n)this.activationHistory.delete(i)}trimCoActivationCounts(){if(this.coActivationCounts.size<=O)return;let e=Math.floor(O*F),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=Z(n,t-1),a=[];for(let[r,o]of this.coActivationCounts){if(a.length>=t)break;o<=i&&a.push(r)}for(let r of a)this.coActivationCounts.delete(r)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let a=this.graph.getEdges(i.id);for(let r of a){let o=this.graph.getConcept(r.target);if(!o)continue;let s=i.activationLevel*r.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,p=Math.min(1,c+s);n.push({nodeId:r.target,newActivation:p})}}}for(let i of n){let a=this.graph.getConcept(i.nodeId);a&&i.newActivation>a.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(R()-.5)*2*this.config.noiseLevel,i=Math.max(0,Math.min(1,t.activationLevel+n));this.graph.setActivation(t.id,i)}}recordActivation(e,t){let n=this.activationHistory.get(e)||[];n.push(t),n.length>50&&n.shift(),this.activationHistory.set(e,n)}trackCoActivation(e,t){let n=[e,t].sort().join(":"),i=this.coActivationCounts.get(n)||0;this.coActivationCounts.set(n,i+1)}deduplicateAssociations(e){let t=new Map;for(let n of e){let i=[n.source,n.target].sort().join(":"),a=t.get(i);(!a||n.strength>a.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ee}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},I=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let a=await this.detectPatternMerges(i);for(let c of a)c.cycleId=e,n.push(c);let r=await this.detectNovelAssociations(t.novelAssociations);for(let c of r)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,p)=>p.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let a=i+1;a<n.length;a++){let r=n[i],o=n[a],s=this.graph.getEdge(r.id,o.id),c=this.graph.getEdge(o.id,r.id),p=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(r.content,o.content),l=Math.sqrt(r.activationLevel*o.activationLevel),u=p*.4+d*.3+l*.3;if(u>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[r.id,o.id]}),v=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[r.id,o.id],edgeWeight:p,contentSimilarity:d,coActivation:l});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[r.id,o.id],description:this.generatePatternMergeDescription(r,o,u),noveltyScore:m,confidenceScore:v,actionable:v>=this.config.minConfidence,applied:!1,suggestedAction:v>=this.config.minConfidence?`Merge "${this.truncate(r.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),a=this.graph.getConcept(n.target);if(!i||!a)continue;let r=this.graph.getEdge(n.source,n.target);if(r&&r.weight>.5)continue;let o=i.conceptType!==a.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,a,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(a.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},a=i.successRate,r=i.executionCount,o=i.confidence,s=a!==void 0&&a<.7,c=r!==void 0&&r>10,p=o!==void 0&&o<.6;if(s||c&&p){let d=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),l=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,a,r),noveltyScore:d,confidenceScore:l,actionable:l>=this.config.minConfidence,applied:!1,suggestedAction:l>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let a=i.conceptType??"pattern";n[a]||(n[a]=[]),n[a].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(a=>a.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ee().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),a=new Set(n),r=new Set(i),o=n.filter(c=>r.has(c)),s=a.size+r.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let a=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${a}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};H();k();$();import{existsSync as te,unlinkSync as ne}from"fs";var T={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},C=class{constructor(e,t=T){this.db=e;this.thresholds=t}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-PGIG2W3G.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let a=`/tmp/dream-branch-${t}.rvf`,r=this.rvfAdapter.derive(a),o=i;o._rvfBranchPath=a,o._rvfChildAdapter=r}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),a=i.patternCount-n.patternCount,r=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-a/n.patternCount;d>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(d*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(r<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-r).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let d=o/n.highConfidenceCount;d>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(d*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let d=this.rvfAdapter.dimension?.()??384,l=new Float32Array(d);for(let m=0;m<d;m++)l[m]=Math.sin(m*.1);let u=this.rvfAdapter.search?.(l,10)??[];u.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${u.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let p=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:p,patternCountDelta:a,avgConfidenceDelta:r,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&te(n)&&ne(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var x=N.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...T}},z=class{constructor(e){this.graph=e}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 a=(await this.graph.getNeighbors(n.id)).map(r=>r.edge);this.edgeCache.set(n.id,a)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let r of e)t[r.conceptType]=(t[r.conceptType]??0)+1,n+=this.activationLevels.get(r.id)??r.activationLevel;let i=0,a=Array.from(this.edgeCache.values());for(let r of a)i+=r.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},_=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=M(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase();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(),a=new Set(i.map(s=>s.name)),r=a.has("insight_type"),o=a.has("source_concepts");if(!r)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),x.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),x.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){x.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:y(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let a=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(a),this.emitBranchEvent("dream:branch_created",i)}try{let a=await this.graph.getActiveNodes(0);if(a.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${a.length} < ${this.config.minConceptsRequired}`);let r=new z(this.graph);await r.loadIntoMemory(30);let s=await new S(r,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await r.persistActivations();let p=await new I(r,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=p.length;for(let l of p)await this.saveInsight(l);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let l=this.branchManager.validateBranch(i);if(l.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,l);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,l);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:l.reason},"dream-engine")}catch{}x.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:l.reason})}i=null}let d={cycle:{...this.currentCycle},insights:p,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(a){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=E(a),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,a}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async ensureConceptsLoaded(){if(this.ensureInitialized(),(await this.graph.getActiveNodes(0)).length>=this.config.minConceptsRequired)return 0;let t=this.db.prepare(`SELECT id, name, description, qe_domain as domain, pattern_type as patternType,
62
+ `).run(s,e);a+=c.changes}return a})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,a=t.get().count,r={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)r[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:a,byType:r,avgEdgesPerNode:i>0?a/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?D(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function K(h){return new A(h)}J();function Z(h,e){if(e<0||e>=h.length)return h[0]??0;let t=0,n=h.length-1;for(;t<n;){let i=t+n>>1;if(h[i]<h[t]){let s=h[t];h[t]=h[i],h[i]=s}if(h[n]<h[t]){let s=h[t];h[t]=h[n],h[n]=s}if(h[i]<h[n]){let s=h[i];h[i]=h[n],h[n]=s}let a=h[n],r=t;for(let s=t;s<n;s++)if(h[s]<=a){let c=h[r];h[r]=h[s],h[s]=c,r++}let o=h[r];if(h[r]=h[n],h[n]=o,r===e)return h[r];r<e?t=r+1:n=r-1}return h[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},S=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(d=>this.graph.getConcept(d)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let d of i)this.graph.setActivation(d,t),this.recordActivation(d,t);let a=0,r=t,o=0,s=0;for(;a<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),l=this.graph.getActiveNodes(this.config.threshold);for(let u of l)u.activationLevel>r&&(r=u.activationLevel);if(l.length===o&&d===0){if(s++,s>=3)break}else s=0;o=l.length,a++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,l)=>l.activation-d.activation),p=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:a,nodesActivated:c.length,peakActivation:r,activatedNodes:c,novelAssociations:p.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,a=0,r=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let d=U(0,o.length),l=o[d];if(l){let u=this.config.noiseLevel+R()*this.config.noiseLevel*2,m=l.activationLevel,v=Math.min(1,m+u+.3);this.graph.setActivation(l.id,v);let f=await this.spread([l.id],v,s);i+=f.iterations,f.peakActivation>a&&(a=f.peakActivation);for(let b of f.activatedNodes)r.add(b.nodeId);for(let b of f.novelAssociations)n.push(b)}if(Date.now()>=s)break;await this.sleep(50+R()*50)}let c=this.deduplicateAssociations(n),p=Array.from(r).map(d=>{let l=this.graph.getConcept(d);return{nodeId:d,activation:l?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,l)=>l.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:p.length,peakActivation:a,activatedNodes:p,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((r,o)=>o.activationLevel-r.activationLevel).slice(0,i));let a=[];for(let r=0;r<n.length;r++)for(let o=r+1;o<n.length;o++){let s=n[r],c=n[o],p=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),l=this.graph.getEdge(c.id,s.id),u=d!==void 0||l!==void 0,m=d?.weight??l?.weight??0,v=!u||m<.3;p>.3&&(a.push({source:s,target:c,coActivation:p,isNovel:v}),this.trackCoActivation(s.id,c.id))}return a.sort((r,o)=>r.isNovel!==o.isNovel?r.isNovel?-1:1:o.coActivation-r.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=B)return;let e=Math.floor(B*F),t=this.activationHistory.size-e,n=Array.from(this.activationHistory.keys()).slice(0,t);for(let i of n)this.activationHistory.delete(i)}trimCoActivationCounts(){if(this.coActivationCounts.size<=O)return;let e=Math.floor(O*F),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=Z(n,t-1),a=[];for(let[r,o]of this.coActivationCounts){if(a.length>=t)break;o<=i&&a.push(r)}for(let r of a)this.coActivationCounts.delete(r)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let a=this.graph.getEdges(i.id);for(let r of a){let o=this.graph.getConcept(r.target);if(!o)continue;let s=i.activationLevel*r.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,p=Math.min(1,c+s);n.push({nodeId:r.target,newActivation:p})}}}for(let i of n){let a=this.graph.getConcept(i.nodeId);a&&i.newActivation>a.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(R()-.5)*2*this.config.noiseLevel,i=Math.max(0,Math.min(1,t.activationLevel+n));this.graph.setActivation(t.id,i)}}recordActivation(e,t){let n=this.activationHistory.get(e)||[];n.push(t),n.length>50&&n.shift(),this.activationHistory.set(e,n)}trackCoActivation(e,t){let n=[e,t].sort().join(":"),i=this.coActivationCounts.get(n)||0;this.coActivationCounts.set(n,i+1)}deduplicateAssociations(e){let t=new Map;for(let n of e){let i=[n.source,n.target].sort().join(":"),a=t.get(i);(!a||n.strength>a.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ee}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},I=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let a=await this.detectPatternMerges(i);for(let c of a)c.cycleId=e,n.push(c);let r=await this.detectNovelAssociations(t.novelAssociations);for(let c of r)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,p)=>p.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let a=i+1;a<n.length;a++){let r=n[i],o=n[a],s=this.graph.getEdge(r.id,o.id),c=this.graph.getEdge(o.id,r.id),p=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(r.content,o.content),l=Math.sqrt(r.activationLevel*o.activationLevel),u=p*.4+d*.3+l*.3;if(u>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[r.id,o.id]}),v=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[r.id,o.id],edgeWeight:p,contentSimilarity:d,coActivation:l});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[r.id,o.id],description:this.generatePatternMergeDescription(r,o,u),noveltyScore:m,confidenceScore:v,actionable:v>=this.config.minConfidence,applied:!1,suggestedAction:v>=this.config.minConfidence?`Merge "${this.truncate(r.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),a=this.graph.getConcept(n.target);if(!i||!a)continue;let r=this.graph.getEdge(n.source,n.target);if(r&&r.weight>.5)continue;let o=i.conceptType!==a.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,a,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(a.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},a=i.successRate,r=i.executionCount,o=i.confidence,s=a!==void 0&&a<.7,c=r!==void 0&&r>10,p=o!==void 0&&o<.6;if(s||c&&p){let d=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),l=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,a,r),noveltyScore:d,confidenceScore:l,actionable:l>=this.config.minConfidence,applied:!1,suggestedAction:l>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let a=i.conceptType??"pattern";n[a]||(n[a]=[]),n[a].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(a=>a.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ee().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),a=new Set(n),r=new Set(i),o=n.filter(c=>r.has(c)),s=a.size+r.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let a=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${a}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};H();k();$();import{existsSync as te,unlinkSync as ne}from"fs";var T={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},C=class{constructor(e,t=T){this.db=e;this.thresholds=t}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-25T4IUQL.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let a=`/tmp/dream-branch-${t}.rvf`,r=this.rvfAdapter.derive(a),o=i;o._rvfBranchPath=a,o._rvfChildAdapter=r}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),a=i.patternCount-n.patternCount,r=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-a/n.patternCount;d>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(d*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(r<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-r).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let d=o/n.highConfidenceCount;d>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(d*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let d=this.rvfAdapter.dimension?.()??384,l=new Float32Array(d);for(let m=0;m<d;m++)l[m]=Math.sin(m*.1);let u=this.rvfAdapter.search?.(l,10)??[];u.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${u.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let p=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:p,patternCountDelta:a,avgConfidenceDelta:r,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&te(n)&&ne(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var x=N.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...T}},z=class{constructor(e){this.graph=e}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 a=(await this.graph.getNeighbors(n.id)).map(r=>r.edge);this.edgeCache.set(n.id,a)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let r of e)t[r.conceptType]=(t[r.conceptType]??0)+1,n+=this.activationLevels.get(r.id)??r.activationLevel;let i=0,a=Array.from(this.edgeCache.values());for(let r of a)i+=r.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},_=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=M(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase();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(),a=new Set(i.map(s=>s.name)),r=a.has("insight_type"),o=a.has("source_concepts");if(!r)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),x.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),x.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){x.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:y(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let a=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(a),this.emitBranchEvent("dream:branch_created",i)}try{let a=await this.graph.getActiveNodes(0);if(a.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${a.length} < ${this.config.minConceptsRequired}`);let r=new z(this.graph);await r.loadIntoMemory(30);let s=await new S(r,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await r.persistActivations();let p=await new I(r,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=p.length;for(let l of p)await this.saveInsight(l);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let l=this.branchManager.validateBranch(i);if(l.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,l);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,l);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:l.reason},"dream-engine")}catch{}x.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:l.reason})}i=null}let d={cycle:{...this.currentCycle},insights:p,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(a){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=E(a),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,a}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async ensureConceptsLoaded(){if(this.ensureInitialized(),(await this.graph.getActiveNodes(0)).length>=this.config.minConceptsRequired)return 0;let t=this.db.prepare(`SELECT id, name, description, qe_domain as domain, pattern_type as patternType,
63
63
  confidence, success_rate as successRate
64
64
  FROM qe_patterns
65
65
  WHERE confidence >= 0.3
@@ -92,4 +92,4 @@ import{a as W}from"./chunk-3ZHUKLU7.js";import{c as V,d as q}from"./chunk-BKGCMW
92
92
  (id, cycle_id, insight_type, source_concepts, description, novelty_score,
93
93
  confidence_score, actionable, applied, suggested_action, pattern_id)
94
94
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
95
- `).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:D(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function ie(h){let e=new _(h);return import("./feature-flags-PGIG2W3G.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-MLXVW4N6.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var re=_;$();var g=N.create("DreamScheduler"),Y={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},L=class h{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Y,...t},this.metaLearningEngine=new q}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,g.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),g.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),g.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,g.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(g.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{g.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,g.info("Starting dream cycle",{durationMs:e});try{let t=await this.dreamEngine.ensureConceptsLoaded();t>0&&g.info("Auto-loaded concepts for dream",{loaded:t});let n=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=n,this.totalDreamsCompleted++,this.clearExperienceBuffer(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(n),await this.publishDreamCompletedEvent(n),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(i){g.warn("Post-dream meta-learning failed (non-critical)",{error:i instanceof Error?i.message:String(i)})}return this.running&&this.scheduleNextDream(),g.info("Dream completed",{insightsGenerated:n.insights.length}),n}finally{this.dreaming=!1}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&g.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){g.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new W,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>h.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){g.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)g.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>h.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:y(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{g.debug("Failed to publish meta-learning insight event")}}}else g.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),g.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){g.info("Quality gate failed but cannot start dream yet");return}g.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){g.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){g.info("Milestone reached but cannot start dream yet");return}g.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:y(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){g.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){g.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],g.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){g.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function ae(h,e){return new L(h,e)}var se=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],G=class{constructor(e,t){this.db=e;this.branchManager=new C(e,t??T)}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(),a=[];for(let s of e){let c=await this.executeStrategy(s,i,t);a.push(c)}let r=a.filter(s=>s.validation.passed),o=null;if(r.length>0){o=r.reduce((c,p)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(p.validation)>d?p:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:a,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,a=this.branchManager.createBranch(i),r=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(a,t);return this.branchManager.discardBranch(a),{strategy:e,branch:a,validation:o,selected:!1,durationMs:Date.now()-r}}catch{return this.branchManager.discardBranch(a),{strategy:e,branch:a,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-r}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{P as a,A as b,K as c,B as d,O as e,F as f,j as g,S as h,Q as i,I as j,T as k,C as l,X as m,_ as n,ie as o,re as p,Y as q,L as r,ae as s,se as t,G as u};
95
+ `).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:D(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function ie(h){let e=new _(h);return import("./feature-flags-25T4IUQL.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-5QLSVTXS.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var re=_;$();var g=N.create("DreamScheduler"),Y={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},L=class h{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Y,...t},this.metaLearningEngine=new q}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,g.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),g.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),g.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,g.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(g.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{g.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,g.info("Starting dream cycle",{durationMs:e});try{let t=await this.dreamEngine.ensureConceptsLoaded();t>0&&g.info("Auto-loaded concepts for dream",{loaded:t});let n=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=n,this.totalDreamsCompleted++,this.clearExperienceBuffer(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(n),await this.publishDreamCompletedEvent(n),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(i){g.warn("Post-dream meta-learning failed (non-critical)",{error:i instanceof Error?i.message:String(i)})}return this.running&&this.scheduleNextDream(),g.info("Dream completed",{insightsGenerated:n.insights.length}),n}finally{this.dreaming=!1}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&g.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){g.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new W,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>h.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){g.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)g.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>h.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:y(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{g.debug("Failed to publish meta-learning insight event")}}}else g.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),g.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){g.info("Quality gate failed but cannot start dream yet");return}g.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){g.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){g.info("Milestone reached but cannot start dream yet");return}g.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:y(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){g.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){g.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],g.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){g.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function ae(h,e){return new L(h,e)}var se=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],G=class{constructor(e,t){this.db=e;this.branchManager=new C(e,t??T)}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(),a=[];for(let s of e){let c=await this.executeStrategy(s,i,t);a.push(c)}let r=a.filter(s=>s.validation.passed),o=null;if(r.length>0){o=r.reduce((c,p)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(p.validation)>d?p:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:a,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,a=this.branchManager.createBranch(i),r=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(a,t);return this.branchManager.discardBranch(a),{strategy:e,branch:a,validation:o,selected:!1,durationMs:Date.now()-r}}catch{return this.branchManager.discardBranch(a),{strategy:e,branch:a,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-r}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{P as a,A as b,K as c,B as d,O as e,F as f,j as g,S as h,Q as i,I as j,T as k,C as l,X as m,_ as n,ie as o,re as p,Y as q,L as r,ae as s,se as t,G as u};
@@ -1,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.9.20");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.22");process.exit(0)}
2
2
  var l=["ECONNREFUSED","ETIMEOUT","ENOMEM","ENOSPC"];var s={successRate:.1,failureRate:1,viabilityThreshold:.3,rehabilitationThreshold:10,maxQuarantineDurationMs:6048e5,domainOverrides:{"security-compliance":{successRate:.05,failureRate:1,viabilityThreshold:.5},"test-generation":{successRate:.15,failureRate:1,viabilityThreshold:.2},"quality-assessment":{successRate:.1,failureRate:1,viabilityThreshold:.4}}},a=class{config;_witnessChain=null;set witnessChain(e){this._witnessChain=e}constructor(e={}){this.config={...s,...e,domainOverrides:{...s.domainOverrides,...e.domainOverrides}}}computeConfidenceUpdate(e,r,i){let{successRate:u,failureRate:o}=this.getConfigForDomain(i),n=r==="success"?u:-o;if(r==="failure")try{this._witnessChain?.append("HEBBIAN_PENALTY",{previousConfidence:e,delta:n,domain:i},"asymmetric-learning")}catch{}return c(e+n,0,1)}shouldQuarantine(e,r){let{viabilityThreshold:i}=this.getConfigForDomain(r);return{shouldQuarantine:e<i,confidence:e,viabilityThreshold:i,domain:r}}classifyFailure(e){if(e.infrastructureHealthy===!1||e.durationMs!==void 0&&e.durationMs>3e4)return"infrastructure";if(e.errorMessage){let r=e.errorMessage.toUpperCase();for(let i of l)if(r.includes(i))return"infrastructure"}return e.failureCategory==="infrastructure"?"infrastructure":(e.failureCategory==="pattern","pattern")}checkRehabilitation(e,r){let i=this.config.rehabilitationThreshold;return{canRehabilitate:e>=i,consecutiveSuccesses:e,requiredSuccesses:i,domain:r}}getConfigForDomain(e){return e&&this.config.domainOverrides?.[e]?this.config.domainOverrides[e]:{successRate:this.config.successRate,failureRate:this.config.failureRate,viabilityThreshold:this.config.viabilityThreshold}}getAsymmetryRatio(e){let{successRate:r,failureRate:i}=this.getConfigForDomain(e);return r===0?1/0:i/r}};function c(t,e,r){return t<e?e:t>r?r:t}export{a};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.20");process.exit(0)}
2
- import{a as _}from"./chunk-4PNLBMKY.js";import{e as E}from"./chunk-5LM2W3NE.js";import{a as T}from"./chunk-F32R4LVS.js";import{c as h}from"./chunk-MIST354H.js";import{b as p,d as b}from"./chunk-JCPXG42O.js";import{S,j as g}from"./chunk-4SBMTHTA.js";b();T();S();var o=h.create("pattern-lifecycle"),A={promotionRewardThreshold:.7,promotionMinOccurrences:E,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3,maxAgeForActivePatterns:90,promotionActivityWindowDays:30,asymmetricLearning:{}},f=class{constructor(e,t={}){this.db=e;this.config={...A,...t},this.asymmetricEngine=new _(this.config.asymmetricLearning),this.ensureSchema()}db;config;asymmetricEngine;_witnessChain=null;set witnessChain(e){this._witnessChain=e}_compressionService=null;set compressionService(e){this._compressionService=e}ensureSchema(){try{this.db.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.22");process.exit(0)}
2
+ import{a as _}from"./chunk-3M7EAXED.js";import{e as E}from"./chunk-ZYVFF2GF.js";import{a as T}from"./chunk-D4GHYV5T.js";import{c as h}from"./chunk-QKDYDDO6.js";import{b as p,d as b}from"./chunk-PUBADXN6.js";import{S,j as g}from"./chunk-5Q4HS3PB.js";b();T();S();var o=h.create("pattern-lifecycle"),A={promotionRewardThreshold:.7,promotionMinOccurrences:E,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3,maxAgeForActivePatterns:90,promotionActivityWindowDays:30,asymmetricLearning:{}},f=class{constructor(e,t={}){this.db=e;this.config={...A,...t},this.asymmetricEngine=new _(this.config.asymmetricLearning),this.ensureSchema()}db;config;asymmetricEngine;_witnessChain=null;set witnessChain(e){this._witnessChain=e}_compressionService=null;set compressionService(e){this._compressionService=e}ensureSchema(){try{this.db.prepare(`
3
3
  SELECT deprecated_at FROM qe_patterns LIMIT 1
4
4
  `).get()}catch(e){o.debug("Adding missing deprecated_at column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
5
5
  ALTER TABLE qe_patterns ADD COLUMN deprecated_at TEXT DEFAULT NULL