agentic-qe 3.14.5 → 3.14.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (426) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +76 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/adapters/ag-ui/event-types.d.ts +1 -1
  5. package/dist/audit/witness-chain-hash.d.ts +18 -0
  6. package/dist/audit/witness-chain-hash.js +37 -0
  7. package/dist/audit/witness-chain-repair.d.ts +71 -0
  8. package/dist/audit/witness-chain-repair.js +203 -0
  9. package/dist/audit/witness-chain-verifier.d.ts +152 -0
  10. package/dist/audit/witness-chain-verifier.js +293 -0
  11. package/dist/audit/witness-chain.d.ts +10 -43
  12. package/dist/audit/witness-chain.js +16 -106
  13. package/dist/audit/witness-findings.js +4 -1
  14. package/dist/cli/bundle.js +7 -7
  15. package/dist/cli/chunks/adapter-UYOJPTOX.js +2 -0
  16. package/dist/cli/chunks/agent-booster-wasm-2YGML6OU.js +2 -0
  17. package/dist/cli/chunks/{agent-handler-V6CZ7Q6S.js → agent-handler-D5SSQYNU.js} +2 -2
  18. package/dist/cli/chunks/{agent-memory-branch-ZMD6ULC3.js → agent-memory-branch-YHPLTITV.js} +2 -2
  19. package/dist/cli/chunks/aqe-learning-engine-JR5AVQXR.js +2 -0
  20. package/dist/cli/chunks/{arena-QLSBESC7.js → arena-7BGOXGXO.js} +2 -2
  21. package/dist/cli/chunks/{arena-4UPAEHFT.js → arena-MCE6EU7K.js} +4 -4
  22. package/dist/cli/chunks/audit-BMWTQECB.js +4 -0
  23. package/dist/cli/chunks/base-DRZ2LS6X.js +2 -0
  24. package/dist/cli/chunks/{better-sqlite3-4DSBPDRH.js → better-sqlite3-PMUNGASU.js} +2 -2
  25. package/dist/cli/chunks/{brain-handler-GBY4EZ4P.js → brain-handler-QPUFYX7F.js} +3 -3
  26. package/dist/cli/chunks/{branch-enumerator-XYBVXCNO.js → branch-enumerator-WKFDGRN4.js} +2 -2
  27. package/dist/cli/chunks/{browser-32F6MREU.js → browser-VY5HKH5X.js} +2 -2
  28. package/dist/cli/chunks/browser-workflow-CJ7T3MXF.js +2 -0
  29. package/dist/cli/chunks/{chunk-C3Z4VVHP.js → chunk-257E2A5M.js} +5 -5
  30. package/dist/cli/chunks/{chunk-EFV4ADMO.js → chunk-2JVWITNK.js} +2 -2
  31. package/dist/cli/chunks/{chunk-IGBEJ4UJ.js → chunk-2NPKIBAZ.js} +2 -2
  32. package/dist/cli/chunks/{chunk-KIP6WZGV.js → chunk-2TMWAQQ3.js} +3 -3
  33. package/dist/cli/chunks/{chunk-DLF5BOJD.js → chunk-2YXGBZWV.js} +1 -1
  34. package/dist/cli/chunks/{chunk-KEY43ANX.js → chunk-3EA536JF.js} +2 -2
  35. package/dist/cli/chunks/{chunk-WX6RRIGW.js → chunk-3EZOZN25.js} +2 -2
  36. package/dist/cli/chunks/{chunk-BYG36QC5.js → chunk-3HZS4M3O.js} +2 -2
  37. package/dist/cli/chunks/{chunk-G3L5L6YQ.js → chunk-3NIG7S5W.js} +1 -1
  38. package/dist/cli/chunks/{chunk-CZO4BJG5.js → chunk-4N23RFDU.js} +2 -2
  39. package/dist/cli/chunks/{chunk-QWUXCG2L.js → chunk-5J6W7SIA.js} +1 -1
  40. package/dist/cli/chunks/{chunk-RD2VGOUH.js → chunk-5OOMJGFN.js} +1 -1
  41. package/dist/cli/chunks/{chunk-YDFL445W.js → chunk-5QQSIGUA.js} +2 -2
  42. package/dist/cli/chunks/{chunk-TUSSPKRM.js → chunk-5VFPCSK7.js} +1 -1
  43. package/dist/cli/chunks/{chunk-WLXK2KNU.js → chunk-62N4NUJH.js} +2 -2
  44. package/dist/cli/chunks/{chunk-JSZ663MU.js → chunk-64VGZQLB.js} +1 -1
  45. package/dist/cli/chunks/{chunk-UMGFMKDW.js → chunk-66VWCR67.js} +2 -2
  46. package/dist/cli/chunks/{chunk-6ITZZIQX.js → chunk-6LIHFV7O.js} +2 -2
  47. package/dist/cli/chunks/{chunk-DKUBQQFG.js → chunk-6OS76PHI.js} +2 -2
  48. package/dist/cli/chunks/{chunk-Y5L3ES4L.js → chunk-6RE3X4V5.js} +2 -2
  49. package/dist/cli/chunks/{chunk-CVMNJSCB.js → chunk-6SH5VZUD.js} +2 -2
  50. package/dist/cli/chunks/chunk-6SQM2MUX.js +4 -0
  51. package/dist/cli/chunks/{chunk-6CR4VQBQ.js → chunk-6U7LNMWZ.js} +2 -2
  52. package/dist/cli/chunks/{chunk-HYEJJJY3.js → chunk-72KXSMWI.js} +1 -1
  53. package/dist/cli/chunks/chunk-7CUQCCMD.js +27 -0
  54. package/dist/cli/chunks/chunk-7D3V65N5.js +2 -0
  55. package/dist/cli/chunks/{chunk-K7NJHFLZ.js → chunk-7J6QC567.js} +3 -3
  56. package/dist/cli/chunks/{chunk-6LKDHEBY.js → chunk-7LPR6HJG.js} +2 -2
  57. package/dist/cli/chunks/{chunk-RGGK6VZ7.js → chunk-7NITCZWD.js} +1 -1
  58. package/dist/cli/chunks/{chunk-IYTLXUBO.js → chunk-7Z5LHRC3.js} +2 -2
  59. package/dist/cli/chunks/{chunk-ZCWERUYB.js → chunk-AHKELLIO.js} +3 -3
  60. package/dist/cli/chunks/{chunk-IJHCIXJC.js → chunk-AIRGNL55.js} +2 -2
  61. package/dist/cli/chunks/{chunk-2OMLTYQK.js → chunk-AJRUJAAK.js} +1 -1
  62. package/dist/cli/chunks/{chunk-QYOGD2VW.js → chunk-AVBJYI5I.js} +1 -1
  63. package/dist/cli/chunks/{chunk-PSPKSUF6.js → chunk-B6D2CHEH.js} +1 -1
  64. package/dist/cli/chunks/{chunk-M23ZOZVY.js → chunk-B6MOJC3X.js} +1 -1
  65. package/dist/cli/chunks/{chunk-VD5IO5EO.js → chunk-BAMN2CHI.js} +1 -1
  66. package/dist/cli/chunks/{chunk-KO4FNAUR.js → chunk-BBT64TII.js} +3 -3
  67. package/dist/cli/chunks/{chunk-7JZJJA7U.js → chunk-BJTJLJRZ.js} +3 -3
  68. package/dist/cli/chunks/{chunk-LULD4JV2.js → chunk-BMAPORJ7.js} +2 -2
  69. package/dist/cli/chunks/{chunk-GTKCGPJZ.js → chunk-BPEDWS6O.js} +2 -2
  70. package/dist/cli/chunks/{chunk-3DDXWYMO.js → chunk-BVR7RMC5.js} +1 -1
  71. package/dist/cli/chunks/{chunk-52L77RMG.js → chunk-C6KWXUFJ.js} +2 -2
  72. package/dist/cli/chunks/{chunk-BJPL6THQ.js → chunk-CCK4BF76.js} +1 -1
  73. package/dist/cli/chunks/{chunk-RP2ZKPYV.js → chunk-CD542DNJ.js} +1 -1
  74. package/dist/cli/chunks/{chunk-AFEDJ3RU.js → chunk-CF2ISEOJ.js} +2 -2
  75. package/dist/cli/chunks/chunk-CM7U6TAX.js +5 -0
  76. package/dist/cli/chunks/{chunk-R74ZKREV.js → chunk-D45SG6CP.js} +1 -1
  77. package/dist/cli/chunks/{chunk-YXP6BKGS.js → chunk-D6CJIGRU.js} +89 -83
  78. package/dist/cli/chunks/{chunk-NVYBM3R4.js → chunk-DBDPRORT.js} +2 -2
  79. package/dist/cli/chunks/{chunk-CYE2TJFV.js → chunk-DHVX5UB2.js} +2 -2
  80. package/dist/cli/chunks/{chunk-XUR2M2WB.js → chunk-DK4XN4CU.js} +2 -2
  81. package/dist/cli/chunks/{chunk-W2XCZU62.js → chunk-DPYSUDAO.js} +1 -1
  82. package/dist/cli/chunks/{chunk-WJHWH5D2.js → chunk-DUYOVM5I.js} +2 -2
  83. package/dist/cli/chunks/{chunk-XLAUGSW7.js → chunk-DZ3AUAAB.js} +2 -2
  84. package/dist/cli/chunks/{chunk-37TUN44F.js → chunk-E6G2RD5H.js} +2 -2
  85. package/dist/cli/chunks/{chunk-ELBZON4V.js → chunk-EAY2JMZG.js} +2 -2
  86. package/dist/cli/chunks/{chunk-HSVKZ5KI.js → chunk-ELLBS5RP.js} +2 -2
  87. package/dist/cli/chunks/chunk-ENGZ4D5V.js +2 -0
  88. package/dist/cli/chunks/chunk-FBMN7B46.js +4 -0
  89. package/dist/cli/chunks/{chunk-F34OAHOM.js → chunk-FWASDOT2.js} +2 -2
  90. package/dist/cli/chunks/{chunk-E4AZXCT5.js → chunk-FZOBD67M.js} +1 -1
  91. package/dist/cli/chunks/{chunk-QZMUXJHZ.js → chunk-GDSXITFH.js} +2 -2
  92. package/dist/cli/chunks/{chunk-LSUILON7.js → chunk-GGRHV6D7.js} +1 -1
  93. package/dist/cli/chunks/{chunk-3YUB5HER.js → chunk-GPYVDFB3.js} +101 -101
  94. package/dist/cli/chunks/{chunk-4FWTLJEP.js → chunk-GSF6MB64.js} +2 -2
  95. package/dist/cli/chunks/{chunk-3KDL6QDK.js → chunk-H52HZ67P.js} +2 -2
  96. package/dist/cli/chunks/{chunk-2JGEZHWY.js → chunk-H5BS5VH7.js} +2 -2
  97. package/dist/cli/chunks/{chunk-SQF6HRXR.js → chunk-H6ZM3PUT.js} +1 -1
  98. package/dist/cli/chunks/{chunk-OEIQTWQP.js → chunk-HM6ZSCPI.js} +1 -1
  99. package/dist/cli/chunks/{chunk-URVHZPWY.js → chunk-HNFVJP4I.js} +2 -2
  100. package/dist/cli/chunks/{chunk-RD6TEZ64.js → chunk-I33ERSGB.js} +2 -2
  101. package/dist/cli/chunks/{chunk-IUDWEOLX.js → chunk-IAF6T27S.js} +2 -2
  102. package/dist/cli/chunks/{chunk-XZSMZHM2.js → chunk-IB27QACC.js} +2 -2
  103. package/dist/cli/chunks/{chunk-I6X3EGJI.js → chunk-ICTXTNQZ.js} +1 -1
  104. package/dist/cli/chunks/chunk-IG5GNEC6.js +4 -0
  105. package/dist/cli/chunks/{chunk-6A44AOGN.js → chunk-IQO7UCFR.js} +2 -2
  106. package/dist/cli/chunks/{chunk-R6IU3EWP.js → chunk-IV5UZOHH.js} +2 -2
  107. package/dist/cli/chunks/{chunk-VTOVWHEM.js → chunk-JBTPOIAC.js} +2 -2
  108. package/dist/cli/chunks/{chunk-KLTP5IDB.js → chunk-JIXUMYKZ.js} +1 -1
  109. package/dist/cli/chunks/{chunk-3VIXOHMS.js → chunk-JMONHE4B.js} +1 -1
  110. package/dist/cli/chunks/{chunk-SX4JLSLV.js → chunk-JVNTSNWU.js} +2 -2
  111. package/dist/cli/chunks/{chunk-JVQBWYHW.js → chunk-JXGFRBUO.js} +2 -2
  112. package/dist/cli/chunks/{chunk-HVXJC3OC.js → chunk-JZOS5FCX.js} +2 -2
  113. package/dist/cli/chunks/{chunk-XEZIIQYJ.js → chunk-KNNISEDY.js} +1 -1
  114. package/dist/cli/chunks/{chunk-73EI4C2E.js → chunk-L4RUBPLR.js} +2 -2
  115. package/dist/cli/chunks/{chunk-AF4XKLXO.js → chunk-LL3IGZBI.js} +2 -2
  116. package/dist/cli/chunks/{chunk-UJWAWIRV.js → chunk-MBRHSU6W.js} +10 -10
  117. package/dist/cli/chunks/{chunk-J5UNP6W3.js → chunk-MJS53PRX.js} +2 -2
  118. package/dist/cli/chunks/{chunk-EOR2UT72.js → chunk-MQROI74N.js} +2 -2
  119. package/dist/cli/chunks/{chunk-BXVAVFGU.js → chunk-MUOG6QXR.js} +2 -2
  120. package/dist/cli/chunks/{chunk-O3JTQ7N4.js → chunk-MW2GGZZ5.js} +1 -1
  121. package/dist/cli/chunks/{chunk-IIAR5S7Q.js → chunk-NHWGMJAP.js} +2 -2
  122. package/dist/cli/chunks/{chunk-WOIGKU2N.js → chunk-NMAIY4PX.js} +3 -3
  123. package/dist/cli/chunks/{chunk-QIRL6B3C.js → chunk-NQZ5AR3D.js} +2 -2
  124. package/dist/cli/chunks/{chunk-6TU7FEMD.js → chunk-P6OYS755.js} +1 -1
  125. package/dist/cli/chunks/{chunk-HVU64GP5.js → chunk-PI7TJS62.js} +2 -2
  126. package/dist/cli/chunks/{chunk-N7H767TP.js → chunk-PX5YDCRH.js} +2 -2
  127. package/dist/cli/chunks/{chunk-3EZ5DR2R.js → chunk-PZPWRQ2M.js} +2 -2
  128. package/dist/cli/chunks/{chunk-RKOUXVZZ.js → chunk-Q5XTSMWR.js} +2 -2
  129. package/dist/cli/chunks/{chunk-K27SU3RE.js → chunk-Q7EAGKAE.js} +2 -2
  130. package/dist/cli/chunks/{chunk-M5AEL7IS.js → chunk-QDFTT3RF.js} +2 -2
  131. package/dist/cli/chunks/{chunk-TY5WC3FT.js → chunk-QGA55PFM.js} +3 -3
  132. package/dist/cli/chunks/{chunk-NQI7FWCS.js → chunk-QW6VMTBR.js} +2 -2
  133. package/dist/cli/chunks/{chunk-BHFR2EXL.js → chunk-QZANMBIT.js} +1 -1
  134. package/dist/cli/chunks/{chunk-5D36YHS3.js → chunk-RETBYIAC.js} +4 -4
  135. package/dist/cli/chunks/{chunk-UKGXWW64.js → chunk-RFNPJK6N.js} +3 -3
  136. package/dist/cli/chunks/{chunk-G3W6BMVJ.js → chunk-RG52OKAM.js} +1 -1
  137. package/dist/cli/chunks/{chunk-DO6EI5KB.js → chunk-RSXXCL4A.js} +1 -1
  138. package/dist/cli/chunks/{chunk-E3W6XQ57.js → chunk-RTFO5UQH.js} +2 -2
  139. package/dist/cli/chunks/{chunk-DDCIYOGT.js → chunk-RZZCUIAI.js} +2 -2
  140. package/dist/cli/chunks/{chunk-C3HQL6S4.js → chunk-SDRHUMJB.js} +2 -2
  141. package/dist/cli/chunks/{chunk-KYA5LARK.js → chunk-SE4WIB26.js} +1 -1
  142. package/dist/cli/chunks/{chunk-NU7UTXMP.js → chunk-SESK3ARK.js} +2 -2
  143. package/dist/cli/chunks/{chunk-YQGPQBCX.js → chunk-SJUXE4IC.js} +2 -2
  144. package/dist/cli/chunks/{chunk-HBCGYMQU.js → chunk-SMDN3BQZ.js} +1 -1
  145. package/dist/cli/chunks/{chunk-D6OUCB2H.js → chunk-SNOBH4AZ.js} +2 -2
  146. package/dist/cli/chunks/{chunk-QRCIZFNK.js → chunk-SPV2VKC5.js} +2 -2
  147. package/dist/cli/chunks/chunk-TCHGOB2N.js +2 -0
  148. package/dist/cli/chunks/{chunk-2KJQ2UQE.js → chunk-TVYY3OCX.js} +1 -1
  149. package/dist/cli/chunks/{chunk-RIZVC4XY.js → chunk-UCFQALXO.js} +2 -2
  150. package/dist/cli/chunks/{chunk-XFPPERA2.js → chunk-UKA2KOXE.js} +2 -2
  151. package/dist/cli/chunks/{chunk-UTBYJ4RF.js → chunk-UNFFDHER.js} +16 -11
  152. package/dist/cli/chunks/{chunk-6VAZAHQG.js → chunk-UQ32JHES.js} +2 -2
  153. package/dist/cli/chunks/{chunk-CPC7FN52.js → chunk-V4DM6ELU.js} +2 -2
  154. package/dist/cli/chunks/{chunk-67YV75XP.js → chunk-VGFFFKGK.js} +2 -2
  155. package/dist/cli/chunks/{chunk-WK7B4B6Y.js → chunk-VMNWDJIZ.js} +2 -2
  156. package/dist/cli/chunks/chunk-W6HXLH5G.js +180 -0
  157. package/dist/cli/chunks/{chunk-7VFY7TUR.js → chunk-WCJBU2KI.js} +2 -2
  158. package/dist/cli/chunks/{chunk-JROVR6YS.js → chunk-WGM35YWL.js} +2 -2
  159. package/dist/cli/chunks/{chunk-IUHB5GVS.js → chunk-WO4QMXIG.js} +2 -2
  160. package/dist/cli/chunks/{chunk-JES6R5KP.js → chunk-XAS3XRYM.js} +1 -1
  161. package/dist/cli/chunks/chunk-Y3LZ35OG.js +2 -0
  162. package/dist/cli/chunks/{chunk-75QJ5HWE.js → chunk-Y3UOUNHM.js} +2 -2
  163. package/dist/cli/chunks/{chunk-WJTSY5MC.js → chunk-YFBSPLJG.js} +1 -1
  164. package/dist/cli/chunks/{chunk-DPBRWP4J.js → chunk-YHKEDEAA.js} +3 -3
  165. package/dist/cli/chunks/{chunk-NRE4NAVA.js → chunk-YS4FCTWF.js} +1 -1
  166. package/dist/cli/chunks/{chunk-I2NENQ44.js → chunk-YSLL6VSL.js} +2 -2
  167. package/dist/cli/chunks/chunk-Z6GGIRQQ.js +65 -0
  168. package/dist/cli/chunks/{chunk-E4EYPYR3.js → chunk-Z7WODOTH.js} +2 -2
  169. package/dist/cli/chunks/{chunk-7DETTOPZ.js → chunk-ZCRTRYXK.js} +2 -2
  170. package/dist/cli/chunks/{chunk-FUNGTIF2.js → chunk-ZEV3YTO7.js} +2 -2
  171. package/dist/cli/chunks/{chunk-SQKW3B6B.js → chunk-ZL6SYKUK.js} +1 -1
  172. package/dist/cli/chunks/{chunk-AMMQOV35.js → chunk-ZSPU4MOS.js} +2 -2
  173. package/dist/cli/chunks/{chunk-KKHYJF5U.js → chunk-ZVWVV4EX.js} +1 -1
  174. package/dist/cli/chunks/{ci-RACDAJMR.js → ci-W6K6G2KZ.js} +2 -2
  175. package/dist/cli/chunks/{ci-output-EHRSZBKG.js → ci-output-LDT24TS3.js} +2 -2
  176. package/dist/cli/chunks/{circuit-breaker-GBV7M5XG.js → circuit-breaker-F5V4KITU.js} +2 -2
  177. package/dist/cli/chunks/claude-flow-setup-DT6WQQVD.js +2 -0
  178. package/dist/cli/chunks/client-KHWJT6FB.js +2 -0
  179. package/dist/cli/chunks/{cline-installer-W4NMXJSG.js → cline-installer-G7TJOAEX.js} +2 -2
  180. package/dist/cli/chunks/{code-JWXJMYXB.js → code-PGE6A42V.js} +3 -3
  181. package/dist/cli/chunks/{code-index-extractor-RVI2IFTM.js → code-index-extractor-RNITH372.js} +2 -2
  182. package/dist/cli/chunks/{codex-installer-3BORJINH.js → codex-installer-LBX77AI3.js} +6 -6
  183. package/dist/cli/chunks/{completions-A55NCTAO.js → completions-4AWLAARX.js} +2 -2
  184. package/dist/cli/chunks/{complexity-analyzer-JCXHGGLY.js → complexity-analyzer-ZPNSS476.js} +2 -2
  185. package/dist/cli/chunks/{continuedev-installer-PUVFMGYW.js → continuedev-installer-UAPWX6OA.js} +2 -2
  186. package/dist/cli/chunks/{copilot-installer-4DCMYWHB.js → copilot-installer-BJN2YJGI.js} +2 -2
  187. package/dist/cli/chunks/core-handlers-HING5RRG.js +2 -0
  188. package/dist/cli/chunks/{cost-tracker-5TV2GGKY.js → cost-tracker-MHP2VJ63.js} +2 -2
  189. package/dist/cli/chunks/{coverage-NNWM7TX3.js → coverage-PQB4IEFG.js} +3 -3
  190. package/dist/cli/chunks/cross-domain-router-PQTD6AZN.js +2 -0
  191. package/dist/cli/chunks/{cursor-installer-4NCHGJGK.js → cursor-installer-ZXBWYAS3.js} +2 -2
  192. package/dist/cli/chunks/{daemon-T4JO4IXP.js → daemon-64C7R6OJ.js} +3 -3
  193. package/dist/cli/chunks/{daemon-QIKCXKWO.js → daemon-N2BEGEFY.js} +4 -4
  194. package/dist/cli/chunks/{dag-attention-scheduler-RPAAIDAD.js → dag-attention-scheduler-SPZDAPNL.js} +2 -2
  195. package/dist/cli/chunks/{detect-SBEEVDSN.js → detect-LXJBSSZW.js} +2 -2
  196. package/dist/cli/chunks/{dist-node-ZHI6NCSU.js → dist-node-U3TKZ2IZ.js} +2 -2
  197. package/dist/cli/chunks/{domain-handler-LBC3GJ7Z.js → domain-handler-3DDWUVSR.js} +2 -2
  198. package/dist/cli/chunks/{domain-plugins-H6IZ5USZ.js → domain-plugins-JJVWI4OQ.js} +2 -2
  199. package/dist/cli/chunks/domain-transfer-M36KUJ2U.js +2 -0
  200. package/dist/cli/chunks/dream-WUGRSNCV.js +2 -0
  201. package/dist/cli/chunks/{embed-and-insert-pattern-AHTR7CRU.js → embed-and-insert-pattern-JPAR7TXX.js} +2 -2
  202. package/dist/cli/chunks/{eval-DZU2KISM.js → eval-SOLG23EA.js} +2 -2
  203. package/dist/cli/chunks/{experience-capture-middleware-5IQCWKSL.js → experience-capture-middleware-T7G2VOOD.js} +3 -3
  204. package/dist/cli/chunks/{fast-paths-2KLDUWCY.js → fast-paths-32N3ELI4.js} +2 -2
  205. package/dist/cli/chunks/{feature-flags-N6UAEZY4.js → feature-flags-APJDQ4N7.js} +2 -2
  206. package/dist/cli/chunks/{feature-flags-7AC3XDZA.js → feature-flags-NAHKLDRN.js} +2 -2
  207. package/dist/cli/chunks/{file-discovery-5SDIW4V2.js → file-discovery-YKVM3MDB.js} +2 -2
  208. package/dist/cli/chunks/{fleet-ZIQCAZ2Y.js → fleet-55M5CJS4.js} +3 -3
  209. package/dist/cli/chunks/{gnn-wrapper-DUMBZJEV.js → gnn-wrapper-UD6E6S6Z.js} +2 -2
  210. package/dist/cli/chunks/{heartbeat-handler-6HVM6ZMR.js → heartbeat-handler-OYVW3VSC.js} +4 -4
  211. package/dist/cli/chunks/heartbeat-scheduler-33XX5XNQ.js +2 -0
  212. package/dist/cli/chunks/hnsw-adapter-XQPERX3H.js +2 -0
  213. package/dist/cli/chunks/hnsw-index-2GNXTWHH.js +2 -0
  214. package/dist/cli/chunks/{hnsw-legacy-bridge-5DRL5FLX.js → hnsw-legacy-bridge-HBYIS3ZW.js} +2 -2
  215. package/dist/cli/chunks/{hnswlib-node-GW67GTCL.js → hnswlib-node-EQPM42OU.js} +2 -2
  216. package/dist/cli/chunks/{hooks-QHH6FVO4.js → hooks-5ZSSJWO6.js} +10 -10
  217. package/dist/cli/chunks/hybrid-backend-CCF7URKI.js +2 -0
  218. package/dist/cli/chunks/{hypergraph-engine-7XDCCVG2.js → hypergraph-engine-XBGVQ4PD.js} +2 -2
  219. package/dist/cli/chunks/{hypergraph-handler-QHF7NOU5.js → hypergraph-handler-CAWAQ673.js} +3 -3
  220. package/dist/cli/chunks/impact-analyzer-HGKAZWIG.js +2 -0
  221. package/dist/cli/chunks/{init-handler-5UIVOM7K.js → init-handler-PRHXSARK.js} +6 -6
  222. package/dist/cli/chunks/init-wizard-72MFBI3G.js +2 -0
  223. package/dist/cli/chunks/kernel-BRCBVMSK.js +2 -0
  224. package/dist/cli/chunks/{kilocode-installer-TGGV6K5Q.js → kilocode-installer-F7LXBM7I.js} +2 -2
  225. package/dist/cli/chunks/{kiro-installer-4XYBHZWW.js → kiro-installer-NM723ZRG.js} +2 -2
  226. package/dist/cli/chunks/knowledge-graph-DG44IPEI.js +2 -0
  227. package/dist/cli/chunks/{learning-STE5W6BS.js → learning-5QYIDHH3.js} +3 -3
  228. package/dist/cli/chunks/{llm-router-NKF7J3RI.js → llm-router-43HKWPSX.js} +4 -4
  229. package/dist/cli/chunks/llm-router-service-24KXFX32.js +2 -0
  230. package/dist/cli/chunks/{load-B2T77UJQ.js → load-5YDBWSCS.js} +2 -2
  231. package/dist/cli/chunks/load-test-N4TAYJY3.js +2 -0
  232. package/dist/cli/chunks/mcp-UMAPMNMY.js +2 -0
  233. package/dist/cli/chunks/{memory-WRFZKG56.js → memory-FWCPCQFP.js} +5 -5
  234. package/dist/cli/chunks/memory-backend-NVYFYVAU.js +2 -0
  235. package/dist/cli/chunks/memory-handlers-UTWCNCHL.js +2 -0
  236. package/dist/cli/chunks/multi-model-executor-2XTBGLE4.js +14 -0
  237. package/dist/cli/chunks/{opencode-installer-J36EMQU7.js → opencode-installer-GIXOJ6NS.js} +2 -2
  238. package/dist/cli/chunks/orchestrator-VW6BKHLI.js +393 -0
  239. package/dist/cli/chunks/pattern-null-store-SBPNYDBR.js +2 -0
  240. package/dist/cli/chunks/{pattern-usage-recorder-BVMTWI3E.js → pattern-usage-recorder-7CEUC3J7.js} +2 -2
  241. package/dist/cli/chunks/{pipeline-OWAHDUAQ.js → pipeline-IGUQPPPO.js} +2 -2
  242. package/dist/cli/chunks/{platform-ANGBFWBV.js → platform-2P636I7B.js} +2 -2
  243. package/dist/cli/chunks/{plugin-OO7ON2YW.js → plugin-NY6SWDPE.js} +2 -2
  244. package/dist/cli/chunks/{prime-radiant-advanced-wasm-HFG3BXWU.js → prime-radiant-advanced-wasm-2UUDTIO2.js} +2 -2
  245. package/dist/cli/chunks/{project-root-LNOYVTYY.js → project-root-IOISG5KX.js} +2 -2
  246. package/dist/cli/chunks/protocol-executor-IBYEII5Q.js +2 -0
  247. package/dist/cli/chunks/{protocol-handler-CE3Q6LY4.js → protocol-handler-ZTPCRQ5W.js} +2 -2
  248. package/dist/cli/chunks/{prove-7XPN53PY.js → prove-SQX5A3IG.js} +2 -2
  249. package/dist/cli/chunks/qe-reasoning-bank-7IETWW6W.js +2 -0
  250. package/dist/cli/chunks/{quality-TT23JRFX.js → quality-DROILKRY.js} +2 -2
  251. package/dist/cli/chunks/{quality-gate-PPPRP255.js → quality-gate-PWKWDJY2.js} +3 -3
  252. package/dist/cli/chunks/queen-coordinator-NHUK2MWJ.js +2 -0
  253. package/dist/cli/chunks/{real-embeddings-EYNZIFJE.js → real-embeddings-P5U3MGYC.js} +2 -2
  254. package/dist/cli/chunks/{ref-validation-QQR64ZXD.js → ref-validation-KY73NQXD.js} +2 -2
  255. package/dist/cli/chunks/{roocode-installer-UIGS7ZJD.js → roocode-installer-6JPPRB3W.js} +2 -2
  256. package/dist/cli/chunks/router-SRSO3IHF.js +2 -0
  257. package/dist/cli/chunks/routing-feedback-PASRE5HY.js +2 -0
  258. package/dist/cli/chunks/{routing-handler-6AENUIRG.js → routing-handler-VTJIVFUO.js} +2 -2
  259. package/dist/cli/chunks/{ruvector-commands-5AWMEV34.js → ruvector-commands-C6RPSJJO.js} +2 -2
  260. package/dist/cli/chunks/rvf-dual-writer-4M4J67OU.js +2 -0
  261. package/dist/cli/chunks/rvf-migration-adapter-TSXGT5LF.js +2 -0
  262. package/dist/cli/chunks/{rvf-migration-coordinator-NWRJ7C22.js → rvf-migration-coordinator-R53URRIO.js} +2 -2
  263. package/dist/cli/chunks/rvf-native-adapter-MOF3E7BR.js +2 -0
  264. package/dist/cli/chunks/{rvf-store-integrity-ISKRP563.js → rvf-store-integrity-MMXN5TEJ.js} +2 -2
  265. package/dist/cli/chunks/safe-db-QJLFO33B.js +2 -0
  266. package/dist/cli/chunks/schedule-YIVXW5O2.js +2 -0
  267. package/dist/cli/chunks/scheduler-AON7DWSJ.js +2 -0
  268. package/dist/cli/chunks/{security-325A7FMB.js → security-3B3R2NL4.js} +3 -3
  269. package/dist/cli/chunks/shared-rvf-adapter-VIJB7JUS.js +2 -0
  270. package/dist/cli/chunks/{shared-rvf-dual-writer-THFDYS2Z.js → shared-rvf-dual-writer-UVWGDUWC.js} +2 -2
  271. package/dist/cli/chunks/sqlite-persistence-75VHKKQB.js +2 -0
  272. package/dist/cli/chunks/{standalone-memory-UD4MJ6GZ.js → standalone-memory-M4LWAAYZ.js} +2 -2
  273. package/dist/cli/chunks/{status-handler-CPFTN4XL.js → status-handler-YYFV6OZL.js} +2 -2
  274. package/dist/cli/chunks/{structural-health-2MG2IVBL.js → structural-health-27E6LLKB.js} +2 -2
  275. package/dist/cli/chunks/sync-26CEGSTC.js +2 -0
  276. package/dist/cli/chunks/{sync-EE4VVKOW.js → sync-J3LJ56WN.js} +2 -2
  277. package/dist/cli/chunks/{task-handler-7H5OYJG4.js → task-handler-4MCEBQZL.js} +2 -2
  278. package/dist/cli/chunks/{task-handlers-NH4GJHCJ.js → task-handlers-GYBAWKE2.js} +3 -3
  279. package/dist/cli/chunks/{test-MPHGT4T6.js → test-MPC5HRH5.js} +4 -4
  280. package/dist/cli/chunks/{test-scheduling-CHQ4ZLLJ.js → test-scheduling-ZJBFRZ3J.js} +3 -3
  281. package/dist/cli/chunks/token-bootstrap-2Y2XITBX.js +2 -0
  282. package/dist/cli/chunks/{token-usage-EBXUJNRB.js → token-usage-3X5WMTG2.js} +2 -2
  283. package/dist/cli/chunks/{transformers-ZEKS2OJZ.js → transformers-MVL4C5IX.js} +2 -2
  284. package/dist/cli/chunks/tree-sitter-wasm-parser-SLW65ZFO.js +2 -0
  285. package/dist/cli/chunks/{types-KYAA5VLV.js → types-TG5P3CRS.js} +2 -2
  286. package/dist/cli/chunks/unified-memory-UCQ6AB32.js +2 -0
  287. package/dist/cli/chunks/unified-memory-hnsw-IXYUMKRR.js +2 -0
  288. package/dist/cli/chunks/unified-persistence-7E6JQ4FZ.js +2 -0
  289. package/dist/cli/chunks/{upgrade-UJBJ5AYM.js → upgrade-ETBHDEPY.js} +2 -2
  290. package/dist/cli/chunks/{validate-RUV6YMWS.js → validate-C2A73LZK.js} +2 -2
  291. package/dist/cli/chunks/{validate-swarm-IVEVMGVM.js → validate-swarm-67XN42ML.js} +2 -2
  292. package/dist/cli/chunks/{vibium-HOGMFJ2Z.js → vibium-NILGKHLN.js} +2 -2
  293. package/dist/cli/chunks/visual-security-4VZXPEVG.js +2 -0
  294. package/dist/cli/chunks/{web-tree-sitter-AVWA6HKE.js → web-tree-sitter-USJN77P4.js} +2 -2
  295. package/dist/cli/chunks/{windsurf-installer-DAH7HI2W.js → windsurf-installer-5GGZXGJW.js} +2 -2
  296. package/dist/cli/chunks/witness-chain-IWS5ZHHL.js +2 -0
  297. package/dist/cli/chunks/witness-chain-JQA2VPZI.js +2 -0
  298. package/dist/cli/chunks/witness-chain-repair-4UA7IPS3.js +2 -0
  299. package/dist/cli/chunks/witness-chain-verifier-3GEADWPE.js +2 -0
  300. package/dist/cli/chunks/{witness-key-manager-JSTBMG43.js → witness-key-manager-ZWEIK3VJ.js} +2 -2
  301. package/dist/cli/chunks/{workflow-TWOIA6LZ.js → workflow-KHMVVBBA.js} +4 -4
  302. package/dist/cli/chunks/workflow-orchestrator-GI5NQH7C.js +2 -0
  303. package/dist/cli/chunks/wrappers-N6XIK5PT.js +2 -0
  304. package/dist/cli/commands/audit.d.ts +20 -2
  305. package/dist/cli/commands/audit.js +158 -16
  306. package/dist/cli/commands/claude-flow-setup.js +5 -4
  307. package/dist/cli/index.js +2 -1
  308. package/dist/init/agents-installer.d.ts +4 -0
  309. package/dist/init/agents-installer.js +24 -11
  310. package/dist/init/codex-installer.js +4 -2
  311. package/dist/init/idempotent-write.d.ts +53 -0
  312. package/dist/init/idempotent-write.js +160 -0
  313. package/dist/init/phases/05-learning.js +3 -1
  314. package/dist/init/phases/07-hooks.js +32 -16
  315. package/dist/init/phases/08-mcp.js +4 -2
  316. package/dist/init/phases/10-workers.js +7 -5
  317. package/dist/init/phases/12-verification.js +7 -2
  318. package/dist/init/project-analyzer.d.ts +9 -0
  319. package/dist/init/project-analyzer.js +20 -1
  320. package/dist/init/self-configurator.d.ts +5 -3
  321. package/dist/init/self-configurator.js +18 -29
  322. package/dist/init/skills-installer.js +4 -2
  323. package/dist/init/types.d.ts +6 -0
  324. package/dist/init/types.js +20 -24
  325. package/dist/integrations/coherence/coherence-service.js +84 -24
  326. package/dist/integrations/coherence/vote-tally.d.ts +38 -0
  327. package/dist/integrations/coherence/vote-tally.js +39 -0
  328. package/dist/integrations/ruvector/shared-rvf-adapter.d.ts +23 -0
  329. package/dist/integrations/ruvector/shared-rvf-adapter.js +24 -0
  330. package/dist/kernel/kernel.js +3 -2
  331. package/dist/learning/pattern-store.d.ts +11 -0
  332. package/dist/learning/pattern-store.js +26 -8
  333. package/dist/learning/qe-patterns.d.ts +6 -0
  334. package/dist/learning/qe-patterns.js +7 -1
  335. package/dist/learning/qe-reasoning-bank.js +3 -0
  336. package/dist/learning/rvf-pattern-store.js +20 -7
  337. package/dist/learning/sqlite-persistence.d.ts +8 -1
  338. package/dist/learning/sqlite-persistence.js +49 -9
  339. package/dist/logging/console-logger.d.ts +2 -5
  340. package/dist/logging/console-logger.js +10 -46
  341. package/dist/logging/index.d.ts +2 -0
  342. package/dist/logging/index.js +1 -0
  343. package/dist/logging/redaction.d.ts +27 -0
  344. package/dist/logging/redaction.js +170 -0
  345. package/dist/mcp/bundle.js +435 -421
  346. package/dist/mcp/handlers/core-handlers.js +5 -4
  347. package/dist/mcp/protocol-server.js +2 -1
  348. package/dist/mcp/tools/base.d.ts +9 -2
  349. package/dist/mcp/tools/base.js +7 -0
  350. package/dist/mcp/tools/coherence/consensus.js +51 -2
  351. package/dist/mcp/tools/planning/goap-plan.d.ts +20 -7
  352. package/dist/mcp/tools/planning/goap-plan.js +92 -20
  353. package/dist/mcp/tools/planning/goap-status.d.ts +37 -12
  354. package/dist/mcp/tools/planning/goap-status.js +52 -23
  355. package/dist/mcp/tools/planning/world-state.d.ts +101 -0
  356. package/dist/mcp/tools/planning/world-state.js +274 -0
  357. package/dist/mcp/types.d.ts +4 -2
  358. package/dist/planning/goap-planner.d.ts +60 -4
  359. package/dist/planning/goap-planner.js +218 -60
  360. package/dist/planning/index.d.ts +1 -1
  361. package/dist/planning/index.js +1 -1
  362. package/dist/planning/plan-executor.d.ts +20 -1
  363. package/dist/planning/plan-executor.js +209 -100
  364. package/dist/planning/types.d.ts +16 -0
  365. package/dist/planning/types.js +17 -0
  366. package/package.json +1 -1
  367. package/dist/cli/chunks/adapter-IYC62SXA.js +0 -2
  368. package/dist/cli/chunks/agent-booster-wasm-EDNKP3SP.js +0 -2
  369. package/dist/cli/chunks/aqe-learning-engine-LLOU2IXD.js +0 -2
  370. package/dist/cli/chunks/audit-CVZQMF55.js +0 -3
  371. package/dist/cli/chunks/base-P3Z4IKCT.js +0 -2
  372. package/dist/cli/chunks/browser-workflow-YYHQQ25X.js +0 -2
  373. package/dist/cli/chunks/chunk-5WOSWNDN.js +0 -2
  374. package/dist/cli/chunks/chunk-7CD7PBHY.js +0 -3
  375. package/dist/cli/chunks/chunk-7X7JYWT4.js +0 -27
  376. package/dist/cli/chunks/chunk-J27F4NSB.js +0 -2
  377. package/dist/cli/chunks/chunk-MI5Q55DG.js +0 -65
  378. package/dist/cli/chunks/chunk-UDHVCKGA.js +0 -5
  379. package/dist/cli/chunks/chunk-XQSIRBKT.js +0 -180
  380. package/dist/cli/chunks/chunk-ZBABIZ2D.js +0 -2
  381. package/dist/cli/chunks/claude-flow-setup-5LVJOFKP.js +0 -2
  382. package/dist/cli/chunks/client-HUVFA5PF.js +0 -2
  383. package/dist/cli/chunks/core-handlers-UEXO3VAA.js +0 -2
  384. package/dist/cli/chunks/cross-domain-router-ODU5IZD6.js +0 -2
  385. package/dist/cli/chunks/domain-transfer-JZA5TMW3.js +0 -2
  386. package/dist/cli/chunks/dream-HE3OX42F.js +0 -2
  387. package/dist/cli/chunks/heartbeat-scheduler-QUIFGGLX.js +0 -2
  388. package/dist/cli/chunks/hnsw-adapter-42KB37KP.js +0 -2
  389. package/dist/cli/chunks/hnsw-index-T2PGO77J.js +0 -2
  390. package/dist/cli/chunks/hybrid-backend-FRNWYRKH.js +0 -2
  391. package/dist/cli/chunks/impact-analyzer-A5QYOYBR.js +0 -2
  392. package/dist/cli/chunks/init-wizard-XBU674YH.js +0 -2
  393. package/dist/cli/chunks/kernel-DV5MTNZD.js +0 -2
  394. package/dist/cli/chunks/knowledge-graph-4ACGVJQK.js +0 -2
  395. package/dist/cli/chunks/llm-router-service-PSMASERT.js +0 -2
  396. package/dist/cli/chunks/load-test-MRUO2VPF.js +0 -2
  397. package/dist/cli/chunks/mcp-JGSFCEMH.js +0 -2
  398. package/dist/cli/chunks/memory-backend-2MPGI6JW.js +0 -2
  399. package/dist/cli/chunks/memory-handlers-XT4HMITB.js +0 -2
  400. package/dist/cli/chunks/multi-model-executor-26Q5BSVG.js +0 -14
  401. package/dist/cli/chunks/orchestrator-D5IFV65I.js +0 -393
  402. package/dist/cli/chunks/pattern-null-store-TGWUL237.js +0 -2
  403. package/dist/cli/chunks/protocol-executor-GEVH5KD6.js +0 -2
  404. package/dist/cli/chunks/qe-reasoning-bank-DJ2JL6QB.js +0 -2
  405. package/dist/cli/chunks/queen-coordinator-F7E3AS26.js +0 -2
  406. package/dist/cli/chunks/router-OZH3QSAU.js +0 -2
  407. package/dist/cli/chunks/routing-feedback-J2E3ADZB.js +0 -2
  408. package/dist/cli/chunks/rvf-dual-writer-HK525Y5Y.js +0 -2
  409. package/dist/cli/chunks/rvf-migration-adapter-Q7FB3BKR.js +0 -2
  410. package/dist/cli/chunks/rvf-native-adapter-5ZRCGUI6.js +0 -2
  411. package/dist/cli/chunks/safe-db-3OYEPVEH.js +0 -2
  412. package/dist/cli/chunks/schedule-AG4C2EIQ.js +0 -2
  413. package/dist/cli/chunks/scheduler-SQS2CZFZ.js +0 -2
  414. package/dist/cli/chunks/shared-rvf-adapter-NFL6QSZ6.js +0 -2
  415. package/dist/cli/chunks/sqlite-persistence-MAKDFSHC.js +0 -2
  416. package/dist/cli/chunks/sync-MBTW5XBF.js +0 -2
  417. package/dist/cli/chunks/token-bootstrap-SSDCYEKK.js +0 -2
  418. package/dist/cli/chunks/tree-sitter-wasm-parser-J6ZMAK37.js +0 -2
  419. package/dist/cli/chunks/unified-memory-DDWMC435.js +0 -2
  420. package/dist/cli/chunks/unified-memory-hnsw-4JA7SGBK.js +0 -2
  421. package/dist/cli/chunks/unified-persistence-F6OSNTXY.js +0 -2
  422. package/dist/cli/chunks/visual-security-25SMBIYT.js +0 -2
  423. package/dist/cli/chunks/witness-chain-PJOQPFUX.js +0 -2
  424. package/dist/cli/chunks/witness-chain-ZW6KKUZU.js +0 -2
  425. package/dist/cli/chunks/workflow-orchestrator-UKSIDM7Q.js +0 -2
  426. package/dist/cli/chunks/wrappers-UR7BLXKV.js +0 -2
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.6");process.exit(0)}
2
+ import{a as x}from"./chunk-TCHGOB2N.js";import{e as f}from"./chunk-FBMN7B46.js";import"./chunk-ENGZ4D5V.js";import"./chunk-64VGZQLB.js";x();import{createRequire as w}from"module";var S=f.create("agent-booster-wasm"),t={JavaScript:0,TypeScript:1,Python:2,Rust:3,Go:4,Java:5,C:6,Cpp:7},l={ExactReplace:0,FuzzyReplace:1,InsertAfter:2,InsertBefore:3,Append:4},v={0:"JavaScript",1:"TypeScript",2:"Python",3:"Rust",4:"Go",5:"Java",6:"C",7:"Cpp"},a=null,u=null,p=null;async function g(){if(a)return!0;if(p)return!1;try{if(a=w(import.meta.url)("./agent_booster_wasm.js"),!a)throw new Error("WASM module loaded but is null");return u=new a.AgentBoosterWasm,!0}catch(e){return p=e,console.warn("[AgentBoosterWASM] Failed to load WASM module:",e),!1}}function A(e){return{".js":t.JavaScript,".mjs":t.JavaScript,".cjs":t.JavaScript,".jsx":t.JavaScript,".ts":t.TypeScript,".tsx":t.TypeScript,".mts":t.TypeScript,".cts":t.TypeScript,".py":t.Python,".rs":t.Rust,".go":t.Go,".java":t.Java,".c":t.C,".h":t.C,".cpp":t.Cpp,".cc":t.Cpp,".cxx":t.Cpp,".hpp":t.Cpp}[e.toLowerCase()]??t.JavaScript}var M=[{name:"var-to-const",detect:(e,r)=>e.includes("var ")&&r.includes("const "),apply:(e,r)=>e.replace(/\bvar\s+/g,"const ")},{name:"var-to-let",detect:(e,r)=>e.includes("var ")&&r.includes("let "),apply:(e,r)=>e.replace(/\bvar\s+/g,"let ")},{name:"add-types-function",detect:(e,r)=>e.includes("function")&&!e.includes(":")&&r.includes(":"),apply:(e,r)=>r},{name:"async-wrapper",detect:(e,r)=>!e.includes("async")&&r.includes("async")&&r.includes("await"),apply:(e,r)=>r},{name:"try-catch-wrapper",detect:(e,r)=>!e.includes("try {")&&r.includes("try {"),apply:(e,r)=>r},{name:"null-check",detect:(e,r)=>!e.includes("if (!")&&!e.includes("if (!")&&(r.includes("if (!")||r.includes("?.")),apply:(e,r)=>r},{name:"test-assertion",detect:(e,r)=>e.includes("test(")&&!e.includes("expect(")&&r.includes("expect("),apply:(e,r)=>r}];function y(e,r){for(let n of M)if(n.detect(e,r))try{return{success:!0,code:n.apply(e,r),pattern:n.name}}catch(s){S.debug("Pattern transform failed, trying next",{pattern:n.name,error:s instanceof Error?s.message:String(s)});continue}return{success:!1,code:r}}async function b(e,r,n,s={}){let o=performance.now(),{confidenceThreshold:T=.5,allowFallback:d=!0}=s;if(!e.trim())return{success:!0,mergedCode:r,confidence:1,strategy:l.Append,syntaxValid:!0,source:"fallback",latencyMs:performance.now()-o};if(await g()&&u&&a)try{let c=a.WasmLanguage[v[n]],i=u.apply_edit(e,r,c);return{success:!0,mergedCode:i.merged_code,confidence:i.confidence,strategy:i.strategy,syntaxValid:i.syntax_valid,source:"wasm",latencyMs:performance.now()-o}}catch(c){let i=c;if(d){let m=y(e,r);if(m.success)return{success:!0,mergedCode:m.code,confidence:.7,strategy:l.FuzzyReplace,syntaxValid:!0,source:"pattern",latencyMs:performance.now()-o}}return{success:!1,mergedCode:r,confidence:0,strategy:l.Append,syntaxValid:!1,source:"fallback",latencyMs:performance.now()-o,error:i.message}}if(d){let c=y(e,r);return{success:c.success,mergedCode:c.code,confidence:c.success?.7:0,strategy:l.FuzzyReplace,syntaxValid:!0,source:"pattern",latencyMs:performance.now()-o}}return{success:!1,mergedCode:r,confidence:0,strategy:l.Append,syntaxValid:!1,source:"fallback",latencyMs:performance.now()-o,error:p?.message??"WASM not available"}}async function W(e,r={}){return Promise.all(e.map(({original:n,edit:s,language:o})=>b(n,s,o,r)))}async function C(){return g()}async function L(){return await g()&&a?a.AgentBoosterWasm.version():"unavailable"}async function R(){if(await g(),u&&a)try{u.apply_edit("function x() {}","function x() {}",a.WasmLanguage.JavaScript)}catch(e){console.debug("[AgentBoosterWASM] Warmup error:",e instanceof Error?e.message:e)}}var _={transform:b,batchTransform:W,isWasmAvailable:C,getVersion:L,warmup:R,Language:t,MergeStrategy:l,languageFromExtension:A};export{t as Language,l as MergeStrategy,W as batchTransform,_ as default,L as getVersion,C as isWasmAvailable,A as languageFromExtension,b as transform,R as warmup};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
- import{b as p}from"./chunk-URVHZPWY.js";import{a as g}from"./chunk-R74ZKREV.js";import"./chunk-IJHCIXJC.js";import"./chunk-JSZ663MU.js";import s from"chalk";var l=class{name="agent";description="Manage QE agents";cleanupAndExit;ensureInitialized;constructor(n,t){this.cleanupAndExit=n,this.ensureInitialized=t}register(n,t){let a=n.command("agent").description(this.description);a.command("list").description("List all agents").option("-d, --domain <domain>","Filter by domain").option("-s, --status <status>","Filter by status").action(async e=>{await this.executeList(e,t)}),a.command("spawn <domain>").description("Spawn an agent in a domain").option("-t, --type <type>","Agent type","worker").option("-c, --capabilities <caps>","Comma-separated capabilities","general").option("--no-progress","Disable progress indicator").action(async(e,o)=>{await this.executeSpawn(e,o,t)})}async executeList(n,t){if(await this.ensureInitialized())try{let a=n.domain?t.queen.getAgentsByDomain(n.domain):t.queen.listAllAgents();if(n.status&&(a=a.filter(e=>e.status===n.status)),console.log(s.blue(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.6");process.exit(0)}
2
+ import{b as p}from"./chunk-HNFVJP4I.js";import{a as g}from"./chunk-D45SG6CP.js";import"./chunk-AIRGNL55.js";import"./chunk-64VGZQLB.js";import s from"chalk";var l=class{name="agent";description="Manage QE agents";cleanupAndExit;ensureInitialized;constructor(n,t){this.cleanupAndExit=n,this.ensureInitialized=t}register(n,t){let a=n.command("agent").description(this.description);a.command("list").description("List all agents").option("-d, --domain <domain>","Filter by domain").option("-s, --status <status>","Filter by status").action(async e=>{await this.executeList(e,t)}),a.command("spawn <domain>").description("Spawn an agent in a domain").option("-t, --type <type>","Agent type","worker").option("-c, --capabilities <caps>","Comma-separated capabilities","general").option("--no-progress","Disable progress indicator").action(async(e,o)=>{await this.executeSpawn(e,o,t)})}async executeList(n,t){if(await this.ensureInitialized())try{let a=n.domain?t.queen.getAgentsByDomain(n.domain):t.queen.listAllAgents();if(n.status&&(a=a.filter(e=>e.status===n.status)),console.log(s.blue(`
3
3
  Agents (${a.length})
4
4
  `)),a.length===0)console.log(s.gray(" No agents found"));else{let e=new Map;for(let i of a)e.has(i.domain)||e.set(i.domain,[]),e.get(i.domain).push(i);let o=Array.from(e.entries());for(let[i,m]of o){console.log(s.cyan(` ${i}:`));for(let r of m)console.log(` ${r.id}`),console.log(` Type: ${r.type}`),console.log(` Status: ${g(r.status)}`),r.startedAt&&console.log(s.gray(` Started: ${r.startedAt.toISOString()}`));console.log("")}}}catch(a){console.error(s.red(`
5
5
  Failed to list agents:`),a),await this.cleanupAndExit(1)}}async executeSpawn(n,t,a){if(await this.ensureInitialized())try{let e=t.capabilities.split(",");console.log(s.blue(`
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
- import"./chunk-JSZ663MU.js";import{existsSync as i,mkdirSync as d,unlinkSync as s,readdirSync as p,statSync as f}from"fs";import{join as o,basename as l}from"path";var v={branchDir:".agentic-qe/branches",defaultStrategy:"child-wins",orphanMaxAgeMs:36e5},g=class{config;parentAdapter;activeBranches=new Map;witnessChain=null;constructor(t,e){this.parentAdapter=t,this.config={...v,...e}}setWitnessChain(t){this.witnessChain=t}createBranch(t){if(this.activeBranches.has(t))throw new Error(`Branch already exists for agent ${t}`);i(this.config.branchDir)||d(this.config.branchDir,{recursive:!0});let e=o(this.config.branchDir,`${t}.rvf`),r=this.parentAdapter.path(),n=this.parentAdapter.derive(e),a={agentId:t,childPath:e,parentPath:r,childAdapter:n,createdAt:Date.now(),ingestLog:[]};return this.activeBranches.set(t,a),a}recordIngest(t,e){let r=this.activeBranches.get(t);if(r)for(let n of e)r.ingestLog.push({id:n.id,vector:n.vector})}async mergeBranch(t,e){let r=e??this.config.defaultStrategy,n=performance.now(),a=0;if(r==="child-wins"&&t.ingestLog.length>0)try{a=this.parentAdapter.ingest(t.ingestLog).accepted}catch(c){console.warn(`[AgentMemoryBranch] Merge replay failed for ${t.agentId}:`,c)}return this.witnessChain?.append("BRANCH_MERGE",{agentId:t.agentId,strategy:r,vectorsMerged:a,branchPath:t.childPath},`agent-${t.agentId}`),this.cleanupBranchFile(t),this.activeBranches.delete(t.agentId),{vectorsMerged:a,strategy:r,durationMs:performance.now()-n}}discardBranch(t){this.witnessChain?.append("BRANCH_DISCARD",{agentId:t.agentId,action:"discard",branchPath:t.childPath},`agent-${t.agentId}`),this.cleanupBranchFile(t),this.activeBranches.delete(t.agentId)}getBranch(t){return this.activeBranches.get(t)}getActiveBranches(){return Array.from(this.activeBranches.values())}listBranchFiles(){return i(this.config.branchDir)?p(this.config.branchDir).filter(e=>e.endsWith(".rvf")).map(e=>{let r=o(this.config.branchDir,e),n=f(r);return{agentId:l(e,".rvf"),path:r,sizeBytes:n.size,modifiedAt:n.mtime}}):[]}cleanupOrphans(t){let e=t??this.config.orphanMaxAgeMs,r=Date.now(),n=0;for(let a of this.listBranchFiles())if(r-a.modifiedAt.getTime()>e&&!this.activeBranches.has(a.agentId))try{s(a.path);let h=`${a.path}.idmap.json`;i(h)&&s(h),n++}catch{}return n}cleanupBranchFile(t){try{t.childAdapter.close()}catch{}try{i(t.childPath)&&s(t.childPath);let e=`${t.childPath}.idmap.json`;i(e)&&s(e)}catch{}}};export{g as AgentMemoryBranch};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.6");process.exit(0)}
2
+ import"./chunk-64VGZQLB.js";import{existsSync as i,mkdirSync as d,unlinkSync as s,readdirSync as p,statSync as f}from"fs";import{join as o,basename as l}from"path";var v={branchDir:".agentic-qe/branches",defaultStrategy:"child-wins",orphanMaxAgeMs:36e5},g=class{config;parentAdapter;activeBranches=new Map;witnessChain=null;constructor(t,e){this.parentAdapter=t,this.config={...v,...e}}setWitnessChain(t){this.witnessChain=t}createBranch(t){if(this.activeBranches.has(t))throw new Error(`Branch already exists for agent ${t}`);i(this.config.branchDir)||d(this.config.branchDir,{recursive:!0});let e=o(this.config.branchDir,`${t}.rvf`),r=this.parentAdapter.path(),n=this.parentAdapter.derive(e),a={agentId:t,childPath:e,parentPath:r,childAdapter:n,createdAt:Date.now(),ingestLog:[]};return this.activeBranches.set(t,a),a}recordIngest(t,e){let r=this.activeBranches.get(t);if(r)for(let n of e)r.ingestLog.push({id:n.id,vector:n.vector})}async mergeBranch(t,e){let r=e??this.config.defaultStrategy,n=performance.now(),a=0;if(r==="child-wins"&&t.ingestLog.length>0)try{a=this.parentAdapter.ingest(t.ingestLog).accepted}catch(c){console.warn(`[AgentMemoryBranch] Merge replay failed for ${t.agentId}:`,c)}return this.witnessChain?.append("BRANCH_MERGE",{agentId:t.agentId,strategy:r,vectorsMerged:a,branchPath:t.childPath},`agent-${t.agentId}`),this.cleanupBranchFile(t),this.activeBranches.delete(t.agentId),{vectorsMerged:a,strategy:r,durationMs:performance.now()-n}}discardBranch(t){this.witnessChain?.append("BRANCH_DISCARD",{agentId:t.agentId,action:"discard",branchPath:t.childPath},`agent-${t.agentId}`),this.cleanupBranchFile(t),this.activeBranches.delete(t.agentId)}getBranch(t){return this.activeBranches.get(t)}getActiveBranches(){return Array.from(this.activeBranches.values())}listBranchFiles(){return i(this.config.branchDir)?p(this.config.branchDir).filter(e=>e.endsWith(".rvf")).map(e=>{let r=o(this.config.branchDir,e),n=f(r);return{agentId:l(e,".rvf"),path:r,sizeBytes:n.size,modifiedAt:n.mtime}}):[]}cleanupOrphans(t){let e=t??this.config.orphanMaxAgeMs,r=Date.now(),n=0;for(let a of this.listBranchFiles())if(r-a.modifiedAt.getTime()>e&&!this.activeBranches.has(a.agentId))try{s(a.path);let h=`${a.path}.idmap.json`;i(h)&&s(h),n++}catch{}return n}cleanupBranchFile(t){try{t.childAdapter.close()}catch{}try{i(t.childPath)&&s(t.childPath);let e=`${t.childPath}.idmap.json`;i(e)&&s(e)}catch{}}};export{g as AgentMemoryBranch};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.6");process.exit(0)}
2
+ import{a,b,c,d,e,f}from"./chunk-AHKELLIO.js";import"./chunk-CM7U6TAX.js";import"./chunk-MBRHSU6W.js";import"./chunk-Z6GGIRQQ.js";import"./chunk-CD542DNJ.js";import"./chunk-7LPR6HJG.js";import"./chunk-7D3V65N5.js";import"./chunk-CCK4BF76.js";import"./chunk-YFBSPLJG.js";import"./chunk-7CUQCCMD.js";import"./chunk-3HZS4M3O.js";import"./chunk-Y3LZ35OG.js";import"./chunk-JVNTSNWU.js";import"./chunk-SMDN3BQZ.js";import"./chunk-6U7LNMWZ.js";import"./chunk-I33ERSGB.js";import"./chunk-IG5GNEC6.js";import"./chunk-UNFFDHER.js";import"./chunk-2TMWAQQ3.js";import"./chunk-2JVWITNK.js";import"./chunk-Q5XTSMWR.js";import"./chunk-AIRGNL55.js";import"./chunk-QW6VMTBR.js";import"./chunk-SDRHUMJB.js";import"./chunk-5J6W7SIA.js";import"./chunk-KNNISEDY.js";import"./chunk-TCHGOB2N.js";import"./chunk-FBMN7B46.js";import"./chunk-ENGZ4D5V.js";import"./chunk-MJS53PRX.js";import"./chunk-DPYSUDAO.js";import"./chunk-PI7TJS62.js";import"./chunk-EAY2JMZG.js";import"./chunk-C6KWXUFJ.js";import"./chunk-IB27QACC.js";import"./chunk-6SH5VZUD.js";import"./chunk-SESK3ARK.js";import"./chunk-SNOBH4AZ.js";import"./chunk-IQO7UCFR.js";import"./chunk-DUYOVM5I.js";import"./chunk-64VGZQLB.js";export{b as AQELearningEngine,a as DEFAULT_ENGINE_CONFIG,c as DEFAULT_META_LEARNING_CONFIG,d as MetaLearningEngine,e as createAQELearningEngine,f as createDefaultLearningEngine};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
- import"./chunk-JSZ663MU.js";import*as K from"fs";import*as M from"path";function G(t){let r=t>>>0;return function(){r|=0,r=r+1831565813|0;let n=Math.imul(r^r>>>15,1|r);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function w(t,r){return Math.floor(t()*r)}var z=[["===","!=="],["!==","==="],["<=","<"],[">=",">"],["&&","||"],["||","&&"],["<","<="],[">",">="],["+","-"],["*","+"]];function H(t){let r=new Array(t.length).fill(!1),n=0,e="code";for(;n<t.length;){let s=t[n],i=t[n+1];e==="code"?(s==="'"?e="single":s==='"'?e="double":s==="`"?e="template":s==="/"&&i==="/"?e="line-comment":s==="/"&&i==="*"&&(e="block-comment"),e!=="code"&&(r[n]=!0)):(r[n]=!0,e==="single"&&s==="'"&&t[n-1]!=="\\"||e==="double"&&s==='"'&&t[n-1]!=="\\"||e==="template"&&s==="`"&&t[n-1]!=="\\"||e==="line-comment"&&s===`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.6");process.exit(0)}
2
+ import"./chunk-64VGZQLB.js";import*as K from"fs";import*as M from"path";function G(t){let r=t>>>0;return function(){r|=0,r=r+1831565813|0;let n=Math.imul(r^r>>>15,1|r);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function w(t,r){return Math.floor(t()*r)}var z=[["===","!=="],["!==","==="],["<=","<"],[">=",">"],["&&","||"],["||","&&"],["<","<="],[">",">="],["+","-"],["*","+"]];function H(t){let r=new Array(t.length).fill(!1),n=0,e="code";for(;n<t.length;){let s=t[n],i=t[n+1];e==="code"?(s==="'"?e="single":s==='"'?e="double":s==="`"?e="template":s==="/"&&i==="/"?e="line-comment":s==="/"&&i==="*"&&(e="block-comment"),e!=="code"&&(r[n]=!0)):(r[n]=!0,e==="single"&&s==="'"&&t[n-1]!=="\\"||e==="double"&&s==='"'&&t[n-1]!=="\\"||e==="template"&&s==="`"&&t[n-1]!=="\\"||e==="line-comment"&&s===`
3
3
  `?e="code":e==="block-comment"&&s==="*"&&i==="/"&&(r[n+1]=!0,n++,e="code")),n++}return r}function E(t,r){let n=1;for(let e=0;e<r;e++)t[e]===`
4
4
  `&&n++;return n}function A(t,r){let n=H(t),e=new Array(t.length).fill(!1),s=[];for(let[i,c]of z){let a=t.indexOf(i);for(;a!==-1;){let u=a+i.length,y=e.slice(a,u).some(Boolean),h=n.slice(a,u).some(Boolean),v=i===">"&&t[a-1]==="=",S=(i==="<"||i===">")&&(t[u]==="="||t[a-1]==="<"||t[a-1]===">");if(!y&&!h&&!v&&!S){for(let d=a;d<u;d++)e[d]=!0;s.push({id:`${r}:${E(t,a)}:${a}:${i}->${c}`,index:a,from:i,to:c,line:E(t,a)})}a=t.indexOf(i,a+1)}}return s.sort((i,c)=>i.index-c.index)}function W(t,r){return t.slice(0,r.index)+r.to+t.slice(r.index+r.from.length)}import*as m from"fs";import*as f from"path";import*as L from"os";import{spawnSync as J}from"child_process";function I(t){let r=f.resolve(t),n=f.join(r,"src"),e=f.join(r,"tests");if(!m.existsSync(n)||!m.existsSync(e))throw new Error(`not an arena fixture (expected src/ and tests/): ${r}`);let s=m.readdirSync(n).filter(c=>c.endsWith(".mjs")).sort().map(c=>f.join("src",c)),i={};for(let c of m.readdirSync(e).filter(a=>a.endsWith(".test.mjs")).sort())i[c.replace(".test.mjs","")]=f.join("tests",c);if(s.length===0||Object.keys(i).length===0)throw new Error(`fixture has no src/*.mjs or tests/*.test.mjs: ${r}`);return{root:r,sourceFiles:s,testGroups:i}}function T(t,r){let n=m.mkdtempSync(f.join(r,"arena-ws-"));m.mkdirSync(f.join(n,"src"),{recursive:!0}),m.mkdirSync(f.join(n,"tests"),{recursive:!0});for(let e of t.layout.sourceFiles){let s=t.mutatedFile&&t.mutatedFile.relPath===e?t.mutatedFile.content:m.readFileSync(f.join(t.layout.root,e),"utf8");m.writeFileSync(f.join(n,e),s)}for(let e of t.groups){let s=t.layout.testGroups[e];m.copyFileSync(f.join(t.layout.root,s),f.join(n,s))}return n}function $(t,r={}){let n=["--test"];r.coverage&&n.push("--experimental-test-coverage");let e=m.readdirSync(f.join(t,"tests")).filter(u=>u.endsWith(".test.mjs")).sort().map(u=>f.join("tests",u));n.push(...e);let s=process.hrtime.bigint(),i=J(process.execPath,n,{cwd:t,timeout:r.timeoutMs??12e4,encoding:"utf8"}),c=Number(process.hrtime.bigint()-s)/1e6,a=null;if(r.coverage){let u=/all files\s*\|\s*([\d.]+)/.exec(i.stdout??"");a=u?Number(u[1]):null}return{ok:i.status===0,durationMs:Math.round(c),coveragePct:a}}function N(){return m.mkdtempSync(f.join(L.tmpdir(),"qe-arena-"))}function B(t){m.rmSync(t,{recursive:!0,force:!0})}var k={kill:.6,coverage:.3,runtimePenalty:.1};function Q(t,r,n){let e=[...t].sort(),s=new Set([e.join("+")]),i=[{id:"s1",name:`all(${e.join("+")})`,groups:e}],c=0;for(;i.length<r&&c++<200;){let a=e.filter(()=>n()<.5);if(a.length===0)continue;let u=a.join("+");s.has(u)||(s.add(u),i.push({id:`s${i.length+1}`,name:u,groups:a}))}return i}function C(t,r,n){let e=r===null?0:r/100,s=k.kill*t+k.coverage*e-k.runtimePenalty*n;return Math.round(s*1e4)/1e4}function D(t,r,n,e){let s=T({layout:t,groups:r.groups},e),i=$(s,{coverage:!0});if(!i.ok)return{baselinePassed:!1,killed:0,total:0,coveragePct:i.coveragePct,runtimeMs:i.durationMs};let c=0,a=0;for(let u of n)for(let y of u.mutants){a++;let h=T({layout:t,groups:r.groups,mutatedFile:{relPath:u.relPath,content:W(u.source,y)}},e);$(h).ok||c++}return{baselinePassed:!0,killed:c,total:a,coveragePct:i.coveragePct,runtimeMs:i.durationMs}}function rt(t){let r=t.seed??42,n=t.log??(()=>{}),e=G(r),s=I(t.target),i=N();try{let c=t.maxMutants??24,a=s.sourceFiles.map(l=>{let o=K.readFileSync(M.join(s.root,l),"utf8");return{relPath:l,source:o,mutants:A(o,l)}}),u=a.flatMap(l=>l.mutants.map(o=>({file:l.relPath,m:o})));if(u.length>c){let l=new Set;for(;l.size<c;)l.add(u[w(e,u.length)].m.id);for(let o of a)o.mutants=o.mutants.filter(p=>l.has(p.id));u=a.flatMap(o=>o.mutants.map(p=>({file:o.relPath,m:p})))}n(`mutants: ${u.length} (of ${a.reduce((l,o)=>l+A(o.source,o.relPath).length,0)} enumerated)`);let y=Q(Object.keys(s.testGroups),t.strategies??4,e),h={},v=y.map(l=>{n(`evaluating ${l.id} [${l.name}] ...`);let o=D(s,l,a,i);return h[l.id]=o.runtimeMs,{s:l,e:o}}),S=Object.keys(s.testGroups).length,d=v.map(({s:l,e:o})=>{let p=o.total>0?Math.round(o.killed/o.total*1e4)/1e4:0,g=Math.round(l.groups.length/S*1e4)/1e4;return{...l,baselinePassed:o.baselinePassed,mutantsKilled:o.killed,mutantsTotal:o.total,killRate:p,coveragePct:o.coveragePct,suiteCostRatio:g,fitness:o.baselinePassed?C(p,o.coveragePct,g):0}}),P=[...d].sort((l,o)=>o.fitness-l.fitness||l.id.localeCompare(o.id)).map(l=>l.id),U=d.map(l=>d.map(o=>l.fitness>o.fitness?1:l.fitness<o.fitness?-1:0)),j=[];if(t.evolveSteps&&t.evolveSteps>0){let l=Object.keys(s.testGroups).sort(),o=d.find(g=>g.id===P[0]).groups,p=d.find(g=>g.id===P[0]).fitness;for(let g=1;g<=t.evolveSteps;g++){let R=l[w(e,l.length)],b=o.includes(R)?o.filter(q=>q!==R):[...o,R].sort();if(b.length===0){j.push({step:g,groups:b,fitness:0,accepted:!1});continue}let x=D(s,{id:`evo${g}`,name:b.join("+"),groups:b},a,i),_=x.total>0?x.killed/x.total:0,F=x.baselinePassed?C(_,x.coveragePct,b.length/l.length):0,O=F>p;j.push({step:g,groups:b,fitness:F,accepted:O}),O&&(o=b,p=F)}}return{contract:"arena-result@1",seed:r,target:M.relative(process.cwd(),s.root)||".",weights:{...k},mutantsTotal:u.length,strategies:d,ranking:P,competitiveArray:U,evolution:j,informational:{runtimesMs:h}}}finally{B(i)}}export{Q as buildStrategies,rt as runArena};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
- import{a as c,c as f}from"./chunk-J5UNP6W3.js";import"./chunk-JSZ663MU.js";f();import{Command as $}from"commander";import r from"chalk";function x(v,g,p){let m=new $("arena").description("Competitive test-strategy tournaments (ADR-104)").addHelpText("after",`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.6");process.exit(0)}
2
+ import{a as c,c as f}from"./chunk-MJS53PRX.js";import"./chunk-64VGZQLB.js";f();import{Command as $}from"commander";import r from"chalk";function x(v,g,p){let m=new $("arena").description("Competitive test-strategy tournaments (ADR-104)").addHelpText("after",`
3
3
  Examples:
4
4
  # Run a 4-strategy tournament against the demo fixture (reproducible under --seed)
5
5
  aqe arena run --strategies 4 --target fixtures/arena-demo --seed 42
@@ -9,10 +9,10 @@ Examples:
9
9
 
10
10
  # List persisted runs
11
11
  aqe arena list
12
- `);return m.command("run").description("Run a seeded strategy tournament against an arena fixture").requiredOption("--target <dir>","Arena fixture directory (src/*.mjs + tests/*.test.mjs)").option("--strategies <n>","Number of strategies","4").option("--seed <n>","RNG seed (same seed = same tournament)","42").option("--max-mutants <n>","Mutant sample cap","24").option("--evolve <steps>","Hill-climb steps from the winner","0").option("--json","Output the full arena-result@1 envelope as JSON").action(async a=>{try{let{runArena:i}=await import("./arena-QLSBESC7.js"),t=i({target:a.target,strategies:parseInt(a.strategies,10),seed:parseInt(a.seed,10),maxMutants:parseInt(a.maxMutants,10),evolveSteps:parseInt(a.evolve,10),log:a.json?()=>{}:e=>console.error(r.dim(` ${e}`))});try{let{getUnifiedMemory:e}=await import("./unified-memory-DDWMC435.js"),s=e();s.isInitialized()||await s.initialize(),s.getDatabase().prepare("INSERT OR REPLACE INTO kv_store (namespace, key, value) VALUES ('arena', ?, ?)").run(`run:${t.seed}:${t.target}`,JSON.stringify(t))}catch(e){console.error(r.dim(` note: run not persisted (${c(e)})`))}if(a.json){console.log(JSON.stringify(t,null,2));return}let d=new Map(t.strategies.map(e=>[e.id,e]));console.log(r.blue(`
12
+ `);return m.command("run").description("Run a seeded strategy tournament against an arena fixture").requiredOption("--target <dir>","Arena fixture directory (src/*.mjs + tests/*.test.mjs)").option("--strategies <n>","Number of strategies","4").option("--seed <n>","RNG seed (same seed = same tournament)","42").option("--max-mutants <n>","Mutant sample cap","24").option("--evolve <steps>","Hill-climb steps from the winner","0").option("--json","Output the full arena-result@1 envelope as JSON").action(async a=>{try{let{runArena:i}=await import("./arena-7BGOXGXO.js"),t=i({target:a.target,strategies:parseInt(a.strategies,10),seed:parseInt(a.seed,10),maxMutants:parseInt(a.maxMutants,10),evolveSteps:parseInt(a.evolve,10),log:a.json?()=>{}:e=>console.error(r.dim(` ${e}`))});try{let{getUnifiedMemory:e}=await import("./unified-memory-UCQ6AB32.js"),s=e();s.isInitialized()||await s.initialize(),s.getDatabase().prepare("INSERT OR REPLACE INTO kv_store (namespace, key, value) VALUES ('arena', ?, ?)").run(`run:${t.seed}:${t.target}`,JSON.stringify(t))}catch(e){console.error(r.dim(` note: run not persisted (${c(e)})`))}if(a.json){console.log(JSON.stringify(t,null,2));return}let d=new Map(t.strategies.map(e=>[e.id,e]));console.log(r.blue(`
13
13
  Arena: ${t.target} \xB7 seed ${t.seed} \xB7 ${t.mutantsTotal} mutants
14
14
  `)),console.log(" rank id kill-rate coverage cost fitness groups"),t.ranking.forEach((e,s)=>{let n=d.get(e),u=n.coveragePct===null?" n/a":`${n.coveragePct.toFixed(2)}%`.padStart(7);console.log(` ${String(s+1).padEnd(5)}${n.id.padEnd(5)}${(n.killRate*100).toFixed(1).padStart(6)}% ${u} ${n.suiteCostRatio.toFixed(2).padEnd(6)}${n.fitness.toFixed(4).padEnd(9)}${n.name}`+(n.baselinePassed?"":r.red(" [baseline FAILED]")))}),console.log(`
15
15
  competitive array (row beats column = 1):`);let o=t.strategies.map(e=>e.id);if(console.log(` ${o.map(e=>e.padEnd(4)).join("")}`),t.competitiveArray.forEach((e,s)=>{console.log(` ${o[s].padEnd(4)}${e.map(n=>String(n).padStart(2).padEnd(4)).join("")}`)}),t.evolution.length>0){console.log(`
16
16
  evolution:`);for(let e of t.evolution)console.log(` step ${e.step}: [${e.groups.join("+")}] fitness ${e.fitness.toFixed(4)} ${e.accepted?r.green("accepted"):"rejected"}`)}let l=d.get(t.ranking[0]);console.log(r.green(`
17
17
  winner: ${l.id} [${l.name}] \u2014 kill ${(l.killRate*100).toFixed(1)}%, fitness ${l.fitness.toFixed(4)}
18
- `))}catch(i){console.error(r.red(` \u2717 ${c(i)}`)),await g(1)}}),m.command("list").description("List persisted arena runs").option("--json","Output as JSON").action(async a=>{if(await p())try{let{getUnifiedMemory:i}=await import("./unified-memory-DDWMC435.js"),t=i();t.isInitialized()||await t.initialize();let d=t.getDatabase().prepare("SELECT key, value FROM kv_store WHERE namespace = 'arena' ORDER BY key").all();if(a.json){console.log(JSON.stringify(d.map(o=>({key:o.key,result:JSON.parse(o.value)})),null,2));return}if(d.length===0){console.log(r.yellow(" no persisted arena runs"));return}for(let o of d){let l=JSON.parse(o.value),e=l.strategies.find(s=>s.id===l.ranking[0]);console.log(` ${r.green(o.key)} \u2014 winner ${e?.id} [${e?.name}] fitness ${e?.fitness}`)}}catch(i){console.error(r.red(` \u2717 ${c(i)}`)),await g(1)}}),m}export{x as createArenaCommand};
18
+ `))}catch(i){console.error(r.red(` \u2717 ${c(i)}`)),await g(1)}}),m.command("list").description("List persisted arena runs").option("--json","Output as JSON").action(async a=>{if(await p())try{let{getUnifiedMemory:i}=await import("./unified-memory-UCQ6AB32.js"),t=i();t.isInitialized()||await t.initialize();let d=t.getDatabase().prepare("SELECT key, value FROM kv_store WHERE namespace = 'arena' ORDER BY key").all();if(a.json){console.log(JSON.stringify(d.map(o=>({key:o.key,result:JSON.parse(o.value)})),null,2));return}if(d.length===0){console.log(r.yellow(" no persisted arena runs"));return}for(let o of d){let l=JSON.parse(o.value),e=l.strategies.find(s=>s.id===l.ranking[0]);console.log(` ${r.green(o.key)} \u2014 winner ${e?.id} [${e?.name}] fitness ${e?.fitness}`)}}catch(i){console.error(r.red(` \u2717 ${c(i)}`)),await g(1)}}),m}export{x as createArenaCommand};
@@ -0,0 +1,4 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.6");process.exit(0)}
2
+ import{d as g,e as y,f as k,g as w}from"./chunk-BPEDWS6O.js";import{o as x}from"./chunk-2JVWITNK.js";import"./chunk-Q5XTSMWR.js";import"./chunk-AIRGNL55.js";import"./chunk-QW6VMTBR.js";import{b as l}from"./chunk-SDRHUMJB.js";import"./chunk-TCHGOB2N.js";import"./chunk-FBMN7B46.js";import"./chunk-ENGZ4D5V.js";import"./chunk-MJS53PRX.js";import"./chunk-PI7TJS62.js";import{p as F,q as j}from"./chunk-EAY2JMZG.js";import"./chunk-C6KWXUFJ.js";import"./chunk-IB27QACC.js";import"./chunk-6SH5VZUD.js";import"./chunk-SESK3ARK.js";import"./chunk-SNOBH4AZ.js";import"./chunk-IQO7UCFR.js";import"./chunk-DUYOVM5I.js";import{f as v}from"./chunk-64VGZQLB.js";import{Command as E}from"commander";import s from"chalk";x();import{existsSync as f}from"node:fs";import p from"node:path";function b(e,a,n){let t=[];t.push(s.bold("Witness Chain Audit Verification")),t.push("");let r=a?s.green("ENABLED"):s.yellow("DISABLED");t.push(` Feature Flag: ${r}`),t.push(` Chain Length: ${e.length} receipts`);let o=n?.status==="forked"?s.yellow("FORKED (no tampering detected)"):e.valid?s.green(n?.status==="valid-with-forks"?"VALID (forks re-anchored)":"VALID"):s.red(n?.status==="tampered"?"BROKEN (tampering detected)":"BROKEN");t.push(` Integrity: ${o}`),e.length>0&&t.push(` Last Hash: ${e.lastHash.slice(0,16)}...`);let i=n?.forks?.length??0;if(i>0){let d=n?.acknowledgedForks?.length??0;t.push(` Forks: ${i} accidental (pre-3.14.5 concurrent writes, #753), ${d} re-anchored`)}if(n?.status==="forked")t.push(""),t.push(s.yellow(` ${e.message}`));else if(!e.valid&&e.brokenAt>=0){t.push("");let d=n?.status==="tampered"&&n.tamperedAt!==void 0?n.tamperedAt:e.brokenAt;t.push(s.red(` Break detected at index ${d}${n?.tamperReason?` (${n.tamperReason})`:""}`)),t.push(s.red(` ${e.message}`))}else e.valid&&i>0&&(t.push(""),t.push(s.green(` ${e.message}`)));return t.push(""),t.join(`
3
+ `)}function O(){try{let e=l(),a=p.join(e,".agentic-qe","memory.db");if(!f(a))return null;let n=(j(),v(F)),t=new n(a),r=g(t),o=k(r);return t.close(),o}catch{return null}}async function P(e){let a=w(),t=(O()??y()).verifyChain(),r={featureEnabled:a,chainLength:t.length,integrity:t.valid,brokenAt:t.brokenAt,lastHash:t.lastHash,message:t.message};return e.format==="json"?console.log(JSON.stringify(r,null,2)):console.log(b(t,a)),r}async function L(e){let{WitnessChain:a,hashWith:n,serializeEntry:t}=await import("./witness-chain-JQA2VPZI.js"),{dbPath:r,keyDir:o}=R(),i;if(!f(r))i={featureEnabled:!0,chainLength:0,integrity:!0,brokenAt:-1,lastHash:"",message:`No database found at ${r} \u2014 nothing to verify`};else{let{default:d}=await import("./better-sqlite3-PMUNGASU.js"),u=new d(r,{readonly:!0});try{let m=new a(u,await A(o)??void 0);await m.initialize();let c=m.verify({includeArchive:!0,checkSignatures:!1}),{tableExists:C}=await import("./witness-chain-verifier-3GEADWPE.js"),h=C(u,"witness_chain")?u.prepare("SELECT * FROM witness_chain ORDER BY id DESC LIMIT 1").get():void 0,$=h?n(h.hash_algo||"sha256",t(h)):"";i={featureEnabled:!0,chainLength:c.entriesChecked,integrity:c.valid,brokenAt:c.brokenAt??-1,lastHash:$,message:V(c),status:c.status,tampered:c.tampered,...c.tamperedAt!==void 0?{tamperedAt:c.tamperedAt}:{},...c.tamperReason?{tamperReason:c.tamperReason}:{},forks:c.forks,acknowledgedForks:c.acknowledgedForks}}finally{u.close()}}return e.format==="json"?console.log(JSON.stringify(i,null,2)):console.log(b({valid:i.integrity,length:i.chainLength,brokenAt:i.brokenAt,lastHash:i.lastHash,message:i.message},i.featureEnabled,i)),i}function R(){let e=l();return{dbPath:p.join(e,".agentic-qe","memory.db"),keyDir:p.join(e,".agentic-qe","witness-keys")}}async function A(e){if(!f(e))return null;let{WitnessKeyManager:a}=await import("./witness-key-manager-ZWEIK3VJ.js");return new a({keyDir:e,autoGenerate:!1})}function V(e){let a=e.entriesChecked,n=e.forks.length,t=n-e.acknowledgedForks.length;switch(e.status){case"valid":return`Audit chain verified: ${a} entries checked, ${e.signatureFailures??0} signature failures`;case"valid-with-forks":return`Audit chain verified: ${a} entries checked; ${n} accidental fork(s) from pre-3.14.5 concurrent writes are re-anchored by CHAIN_REANCHOR, no tampering detected`;case"forked":return`${t} accidental fork(s) (pre-3.14.5 concurrent writes, #753), no tampering detected \u2014 ${a} entries checked, first fork at id=${e.brokenAt}. Run \`aqe audit repair --chain audit\` to back up the store and re-anchor.`;default:return`Audit chain BROKEN: tampering detected at id=${e.tamperedAt} (${e.tamperReason}); ${a} entries checked`+(n>0?`, ${n} accidental fork(s) found before it`:"")}}function W(e){return e.action==="refused"?!0:e.action==="reanchored"&&!(e.after?.status==="valid"||e.after?.status==="valid-with-forks")}async function D(e){let{repairWitnessChainForks:a}=await import("./witness-chain-repair-4UA7IPS3.js"),{dbPath:n,keyDir:t}=R(),r=e.dryRun===!0,o;if(f(n)){let{openDatabase:i}=await import("./safe-db-QJLFO33B.js"),d=i(n,{readonly:r,fileMustExist:!0});try{let u=r?await A(t):(await import("./witness-key-manager-ZWEIK3VJ.js")).getDefaultWitnessKeyManager();o=await a(d,{dbPath:n,dryRun:r,keyManager:u})}finally{d.close()}}else{let i={status:"valid",entriesChecked:0,forks:0,unacknowledgedForks:0};o={action:"none",dryRun:r,message:`No database found at ${n} \u2014 nothing to repair`,before:i,rowsBefore:{live:0,archive:0},rowsAfter:{live:0,archive:0},forksAcknowledged:[]}}return e.format==="json"?console.log(JSON.stringify(o,null,2)):console.log(S(o)),o}function S(e){let a=e.action==="refused"?s.red:e.action==="reanchored"?s.green:s.yellow,n=[s.bold("Witness Chain Audit Repair"),"",` Action: ${a(e.action.toUpperCase())}${e.dryRun?" (dry run)":""}`,` Before: ${e.before.status}, ${e.before.forks} fork(s), ${e.before.unacknowledgedForks} unacknowledged`,` Rows: live ${e.rowsBefore.live} -> ${e.rowsAfter.live}, archive ${e.rowsBefore.archive} -> ${e.rowsAfter.archive}`];return e.after&&n.push(` After: ${e.after.status}`),e.backupPath&&n.push(` Backup: ${e.backupPath}`),n.push("",` ${a(e.message)}`,""),n.join(`
4
+ `)}function q(e,a,n){let t=new E("audit").description("Witness chain audit trail management");return t.command("verify").description("Verify witness chain integrity").option("-F, --format <format>","Output format (json|text)","text").option("-C, --chain <chain>","Which chain to verify: governance (29 decision receipts) or audit (full QE audit trail)","governance").action(async r=>{try{let o=r.format,i=r.chain==="audit"?await L({format:o}):await P({format:o});await a(i.integrity?0:1)}catch(o){console.error("Failed to verify witness chain:",o),await a(1)}}),t.command("repair").description("Re-anchor accidental pre-3.14.5 forks in the audit chain (#753); backs up first, refuses on tampering").option("-C, --chain <chain>",'Chain to repair (only "audit" is supported)',"audit").option("--dry-run","Report what would be done without writing anything",!1).option("-F, --format <format>","Output format (json|text)","text").action(async r=>{try{if(r.chain!=="audit"){console.error(`aqe audit repair supports only --chain audit (got "${r.chain}")`),await a(1);return}let o=await D({format:r.format,dryRun:r.dryRun===!0});await a(W(o)?1:0)}catch(o){console.error("Failed to repair witness chain:",o),await a(1)}}),t}export{q as createAuditCommand,b as formatVerificationText,D as handleAuditChainRepair,L as handleAuditChainVerify,P as handleAuditVerify};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.6");process.exit(0)}
2
+ import{a,b,c,d,e,f,g,h,i,j,k,l}from"./chunk-5QQSIGUA.js";import"./chunk-BMAPORJ7.js";import"./chunk-2JVWITNK.js";import"./chunk-Q5XTSMWR.js";import"./chunk-AIRGNL55.js";import"./chunk-QW6VMTBR.js";import"./chunk-SDRHUMJB.js";import"./chunk-TCHGOB2N.js";import"./chunk-FBMN7B46.js";import"./chunk-ENGZ4D5V.js";import"./chunk-MJS53PRX.js";import"./chunk-DPYSUDAO.js";import"./chunk-WCJBU2KI.js";import"./chunk-PI7TJS62.js";import"./chunk-EAY2JMZG.js";import"./chunk-C6KWXUFJ.js";import"./chunk-IB27QACC.js";import"./chunk-6SH5VZUD.js";import"./chunk-SESK3ARK.js";import"./chunk-SNOBH4AZ.js";import"./chunk-IQO7UCFR.js";import"./chunk-DUYOVM5I.js";import"./chunk-64VGZQLB.js";export{l as MCPToolBase,k as defaultToolLogger,j as getKernel,i as getLLMRouter,e as getMemoryBackend,g as getSharedLLMRouter,c as getSharedMemoryBackend,a as isMemoryOnlyMode,b as registerRvfResetFn,h as resetSharedLLMRouter,d as resetSharedMemoryBackend,f as setSharedLLMRouter};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,q as p}from"./chunk-ELBZON4V.js";import"./chunk-JSZ663MU.js";p();export{i as DotProductAttention,h as FlashAttention,k as HyperbolicAttention,l as LinearAttention,m as MoEAttention,j as MultiHeadAttention,b as RuvectorLayer,n as SonaEngine,c as TensorCompress,a as default,d as differentiableSearch,f as getCompressionLevel,e as hierarchicalForward,g as init,o as pipeline};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.6");process.exit(0)}
2
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,q as p}from"./chunk-EAY2JMZG.js";import"./chunk-64VGZQLB.js";p();export{i as DotProductAttention,h as FlashAttention,k as HyperbolicAttention,l as LinearAttention,m as MoEAttention,j as MultiHeadAttention,b as RuvectorLayer,n as SonaEngine,c as TensorCompress,a as default,d as differentiableSearch,f as getCompressionLevel,e as hierarchicalForward,g as init,o as pipeline};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
- import{a as L,b as z,c as K,d as _,e as ie,f as W,g as G,h as A,i as Ce,j as se,k as Q,l as xe,m as J,n as le,o as Ie,p as P,q as Y,r as X,s as Z,t as ee}from"./chunk-RIZVC4XY.js";import{a as we,b as Re,c as H,d as V,f as tn}from"./chunk-SX4JLSLV.js";import{a as Se,d as ae,e as _e,h as Ee}from"./chunk-7X7JYWT4.js";import{b as ve}from"./chunk-RD6TEZ64.js";import"./chunk-EFV4ADMO.js";import"./chunk-RKOUXVZZ.js";import{b as k,d as oe}from"./chunk-IJHCIXJC.js";import"./chunk-NQI7FWCS.js";import"./chunk-C3HQL6S4.js";import"./chunk-J27F4NSB.js";import"./chunk-7CD7PBHY.js";import"./chunk-J5UNP6W3.js";import{a as F,b as nn}from"./chunk-HVU64GP5.js";import"./chunk-ELBZON4V.js";import"./chunk-52L77RMG.js";import"./chunk-XZSMZHM2.js";import"./chunk-CVMNJSCB.js";import"./chunk-NU7UTXMP.js";import"./chunk-D6OUCB2H.js";import"./chunk-6A44AOGN.js";import"./chunk-WJHWH5D2.js";import"./chunk-JSZ663MU.js";import $ from"path";import o from"chalk";nn();oe();import{existsSync as te,mkdirSync as rn,writeFileSync as on,readFileSync as ce}from"fs";import{join as D,resolve as de}from"path";function ne(e,n){let r="shake256",t=JSON.stringify(n),a=e.prepare("SELECT * FROM witness_chain ORDER BY id DESC LIMIT 1").get(),i=a?ae(r,_e(a)):Se;e.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.14.6");process.exit(0)}
2
+ import{a as L,b as z,c as K,d as _,e as ie,f as W,g as G,h as A,i as Ce,j as se,k as Q,l as xe,m as J,n as le,o as Ie,p as P,q as Y,r as X,s as Z,t as ee}from"./chunk-UCFQALXO.js";import{c as Ee}from"./chunk-7CUQCCMD.js";import{a as we,b as Re,c as H,d as V,f as tn}from"./chunk-JVNTSNWU.js";import{b as ve}from"./chunk-I33ERSGB.js";import{a as Se,d as ae,e as _e}from"./chunk-IG5GNEC6.js";import"./chunk-2JVWITNK.js";import"./chunk-Q5XTSMWR.js";import{b as k,d as oe}from"./chunk-AIRGNL55.js";import"./chunk-QW6VMTBR.js";import"./chunk-SDRHUMJB.js";import"./chunk-TCHGOB2N.js";import"./chunk-FBMN7B46.js";import"./chunk-ENGZ4D5V.js";import"./chunk-MJS53PRX.js";import{a as F,b as nn}from"./chunk-PI7TJS62.js";import"./chunk-EAY2JMZG.js";import"./chunk-C6KWXUFJ.js";import"./chunk-IB27QACC.js";import"./chunk-6SH5VZUD.js";import"./chunk-SESK3ARK.js";import"./chunk-SNOBH4AZ.js";import"./chunk-IQO7UCFR.js";import"./chunk-DUYOVM5I.js";import"./chunk-64VGZQLB.js";import $ from"path";import o from"chalk";nn();oe();import{existsSync as te,mkdirSync as rn,writeFileSync as on,readFileSync as ce}from"fs";import{join as D,resolve as de}from"path";function ne(e,n){let r="shake256",t=JSON.stringify(n),a=e.prepare("SELECT * FROM witness_chain ORDER BY id DESC LIMIT 1").get(),i=a?ae(r,_e(a)):Se;e.prepare(`
3
3
  INSERT INTO witness_chain
4
4
  (prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo)
5
5
  VALUES (?, ?, 'BRAIN_IMPORT', ?, ?, 'brain-import', ?)
@@ -79,7 +79,7 @@ Examples:
79
79
  aqe brain diff ./brain-a ./brain-b --verbose
80
80
  aqe brain search -i ./brain-export --query oauth --domain test-generation
81
81
  aqe brain search -i ./brain-export --since 2026-03-01 --limit 50 --json
82
- `}};async function ye(e){if(e)return e;let{findProjectRoot:n}=await import("./unified-memory-DDWMC435.js");return $.join(n(),".agentic-qe","memory.db")}function Ze(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Wn(e){let n=Number.parseInt(e,10);return!Number.isFinite(n)||n<1?20:n}function Jn(e){if(e===void 0)return;let n=Array.isArray(e)?e:[e],r=[];for(let t of n)for(let a of t.split(",")){let i=a.trim();i&&r.push(i)}return r.length>0?r:void 0}function Un(e,n){console.log(o.blue(`
82
+ `}};async function ye(e){if(e)return e;let{findProjectRoot:n}=await import("./unified-memory-UCQ6AB32.js");return $.join(n(),".agentic-qe","memory.db")}function Ze(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Wn(e){let n=Number.parseInt(e,10);return!Number.isFinite(n)||n<1?20:n}function Jn(e){if(e===void 0)return;let n=Array.isArray(e)?e:[e],r=[];for(let t of n)for(let a of t.split(",")){let i=a.trim();i&&r.push(i)}return r.length>0?r:void 0}function Un(e,n){console.log(o.blue(`
83
83
  Brain Diff
84
84
  `)),console.log(` A: ${o.cyan(e.pathA)} (${e.formatA})`),console.log(` B: ${o.cyan(e.pathB)} (${e.formatB})`),console.log(` Versions: ${o.cyan(e.manifestA.version)} \u2192 ${o.cyan(e.manifestB.version)}`+(e.versionMatch?o.gray(" (match)"):o.yellow(" (differ)"))),console.log(` Checksums: ${o.gray(e.manifestA.checksum.slice(0,12))}\u2026 \u2192 ${o.gray(e.manifestB.checksum.slice(0,12))}\u2026`+(e.checksumMatch?o.gray(" (match)"):o.yellow(" (differ)"))),console.log(` Exported: ${o.gray(e.manifestA.exportedAt)} \u2192 ${o.gray(e.manifestB.exportedAt)}`),console.log(` Records: ${o.cyan(e.manifestA.totalRecords)} \u2192 ${o.cyan(e.manifestB.totalRecords)} `+en(e.manifestB.totalRecords-e.manifestA.totalRecords)),(e.domainsOnlyInA.length>0||e.domainsOnlyInB.length>0)&&(console.log(o.blue(`
85
85
  Domains:`)),e.domainsOnlyInA.length>0&&console.log(` Only in A: ${o.yellow(e.domainsOnlyInA.join(", "))}`),e.domainsOnlyInB.length>0&&console.log(` Only in B: ${o.yellow(e.domainsOnlyInB.join(", "))}`)),e.recordLevel||console.log(o.gray(`
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
- import"./chunk-JSZ663MU.js";var f=class{language;constructor(e="typescript"){this.language=e}enumerate(e,s){let r=[],n=e.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.6");process.exit(0)}
2
+ import"./chunk-64VGZQLB.js";var f=class{language;constructor(e="typescript"){this.language=e}enumerate(e,s){let r=[],n=e.split(`
3
3
  `),l=!1;for(let i=0;i<n.length;i++){let d=n[i],t=d.trim(),c=i+1,u=d.length-d.trimStart().length+1;if(l){t.includes("*/")&&(l=!1);continue}if(t.startsWith("/*")){l=!t.includes("*/");continue}if(t.startsWith("//"))continue;if(/^\s*if\s*\(/.test(d)&&(this.findMatchingElse(n,i)||r.push({file:s,line:c,column:u,language:this.language,construct:"if-without-else",triggerCondition:"when condition is false",currentHandling:"falls through \u2014 no else branch",suggestedGuard:"Add else branch or document why falsy path is safe",severity:"medium"})),/^\s*switch\s*\(/.test(d)){let a=this.extractBlock(n,i);if(a&&!a.includes("default:")&&!a.includes("default :")&&r.push({file:s,line:c,column:u,language:this.language,construct:"switch-no-default",triggerCondition:"when value matches no case",currentHandling:"falls through \u2014 no default case",suggestedGuard:"Add default case with error handling or exhaustive check",severity:"high"}),a){let g=a.match(/case\s+[^:]+:/g)||[],h=a.match(/\b(break|return|throw|continue)\b/g)||[];g.length>0&&h.length<g.length&&r.push({file:s,line:c,column:u,language:this.language,construct:"switch-missing-break",triggerCondition:"when case falls through to next case",currentHandling:"fall-through \u2014 may execute unintended cases",suggestedGuard:"Add break/return to each case or add explicit // falls through comment",severity:"medium"})}}if(/\bcatch\s*\(/.test(t)||/\bcatch\s*\{/.test(t)){let a=this.extractBlock(n,i);if(a!==null){let g=a.replace(/[{}]/g,"").trim();(g.length===0||/^\s*\/\//.test(g))&&r.push({file:s,line:c,column:u,language:this.language,construct:"try-empty-catch",triggerCondition:"when exception is thrown",currentHandling:"exception silently swallowed",suggestedGuard:"Log the error or rethrow with context",severity:"high"})}}if(/\btry\s*\{/.test(t)&&this.extractBlock(n,i)&&(n.slice(i,Math.min(i+30,n.length)).join(`
4
4
  `).includes("finally")||r.push({file:s,line:c,column:u,language:this.language,construct:"try-no-finally",triggerCondition:"when cleanup is needed regardless of success/failure",currentHandling:"no finally block \u2014 cleanup may be skipped on exception",suggestedGuard:"Add finally block for resource cleanup if applicable",severity:"low"})),t.includes("?.")){let a=t.match(/(\w+(?:\.\w+)*)\?\./g)||[];for(let g of a)if(!t.includes("??")&&!t.includes("|| ")&&!t.includes("if")){r.push({file:s,line:c,column:u,language:this.language,construct:"optional-chaining-null-path",triggerCondition:`when ${g.replace("?.","")} is null/undefined`,currentHandling:"returns undefined \u2014 may propagate",suggestedGuard:"Add ?? fallback or explicit null check",severity:"low"});break}}if(t.includes("??")&&!t.includes("?.")&&r.push({file:s,line:c,column:u,language:this.language,construct:"nullish-coalescing-fallback",triggerCondition:"when left side is null/undefined",currentHandling:"uses fallback value",suggestedGuard:"Verify fallback value is appropriate for all null cases",severity:"low"}),/\.\s*then\s*\(/.test(t)&&!t.includes(".catch")&&!t.includes("await")){let a=n.slice(i,Math.min(i+5,n.length)).join(" ");!a.includes(".catch")&&!a.includes("try")&&r.push({file:s,line:c,column:u,language:this.language,construct:"promise-no-catch",triggerCondition:"when promise rejects",currentHandling:"unhandled rejection \u2014 may crash process",suggestedGuard:"Add .catch() handler or use try/catch with await",severity:"high"})}let p=["map","filter","reduce","forEach","find","some","every","flatMap"];for(let a of p)if(new RegExp(`\\.${a}\\s*\\(`).test(t)){let h=n.slice(Math.max(0,i-3),i).join(" ");if(!h.includes(".length")&&!h.includes("if (")&&!h.includes("?.")){r.push({file:s,line:c,column:u,language:this.language,construct:"array-callback-empty",triggerCondition:`when array is empty before .${a}()`,currentHandling:a==="reduce"?"may throw without initial value":"returns empty result \u2014 may cause downstream issues",suggestedGuard:a==="reduce"?"Provide initial value or check array length":"Check array length or handle empty result",severity:a==="reduce"?"high":"low"});break}}/\|\|\s*['"`\d]/.test(t)&&!t.includes("??")&&r.push({file:s,line:c,column:u,language:this.language,construct:"logical-or-falsy",triggerCondition:'when left side is falsy (0, "", false, null, undefined)',currentHandling:'uses fallback \u2014 may unintentionally override 0, "", or false',suggestedGuard:"Use ?? instead of || if only null/undefined should trigger fallback",severity:"medium"}),/&&\s*\w+\s*\(/.test(t)&&!t.includes("if")&&!t.includes("while")&&r.push({file:s,line:c,column:u,language:this.language,construct:"logical-and-short-circuit",triggerCondition:"when left side is falsy \u2014 right side never executes",currentHandling:"short-circuits \u2014 function call skipped silently",suggestedGuard:"Use explicit if-statement for clarity when side effects matter",severity:"low"}),(t.match(/\?/g)||[]).length>=2&&t.includes(":")&&r.push({file:s,line:c,column:u,language:this.language,construct:"ternary-complex",triggerCondition:"when nested ternary conditions interact",currentHandling:"nested ternary \u2014 hard to read and maintain",suggestedGuard:"Refactor to if/else or switch for readability",severity:"medium"}),(/\btypeof\s+\w+\s*===?\s*['"]/.test(t)||/\binstanceof\b/.test(t))&&!t.includes("else")&&!this.findMatchingElse(n,i)&&r.push({file:s,line:c,column:u,language:this.language,construct:"type-guard-unhandled",triggerCondition:"when value does not match the guarded type",currentHandling:"unguarded type path \u2014 may cause runtime type errors",suggestedGuard:"Add else branch or exhaustive type checking",severity:"medium"})}return r}findMatchingElse(e,s){let r={depth:0};for(let n=s;n<Math.min(s+30,e.length);n++){let l=e[n];for(let i of l)i==="{"&&r.depth++,i==="}"&&r.depth--;if(r.depth===0&&n>s){if((e[n+1]?.trim()||"").startsWith("else")||e[n].trim().endsWith("else")||e[n].trim().endsWith("else {")||e[n].includes("} else"))return!0;break}}return!1}extractBlock(e,s){let r=0,n=!1,l=[];for(let i=s;i<Math.min(s+50,e.length);i++){let d=e[i];for(let t of d)t==="{"&&(r++,n=!0),t==="}"&&r--;if(n&&(l.push(d),r===0))return l.join(`
5
5
  `)}return null}};function y(o,e,s){let r=Date.now(),n=s||(e.endsWith(".ts")||e.endsWith(".tsx")?"typescript":"javascript"),i=new f(n).enumerate(o,e);return{file:e,language:n,branches:i,totalConstructs:i.length,unhandledCount:i.length,duration:Date.now()-r}}function b(o){let e=[];if(e.push(`# Branch Enumeration Report: ${o.file}`),e.push(""),e.push(`**Language**: ${o.language} | **Branches**: ${o.unhandledCount} | **Duration**: ${o.duration}ms`),e.push(""),o.branches.length===0)return e.push("No unhandled branches detected."),e.join(`
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
- import{a as p}from"./chunk-KKHYJF5U.js";import"./chunk-JSZ663MU.js";import{readFile as m,readdir as k}from"fs/promises";import{join as c,basename as y,dirname as W}from"path";import{fileURLToPath as v}from"url";import{parse as d}from"yaml";var b=v(import.meta.url),E=W(b),l=class{templatesDir;cache=new Map;constructor(r){this.templatesDir=r||c(E,"templates")}async load(r){if(this.cache.has(r))return this.cache.get(r);try{let e=c(this.templatesDir,`${r}.yaml`),n=await m(e,"utf-8"),o=d(n),i=await this.validate(o);if(!i.valid)throw new Error(`Invalid workflow template ${r}:
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.6");process.exit(0)}
2
+ import{a as p}from"./chunk-ZVWVV4EX.js";import"./chunk-64VGZQLB.js";import{readFile as m,readdir as k}from"fs/promises";import{join as c,basename as y,dirname as W}from"path";import{fileURLToPath as v}from"url";import{parse as d}from"yaml";var b=v(import.meta.url),E=W(b),l=class{templatesDir;cache=new Map;constructor(r){this.templatesDir=r||c(E,"templates")}async load(r){if(this.cache.has(r))return this.cache.get(r);try{let e=c(this.templatesDir,`${r}.yaml`),n=await m(e,"utf-8"),o=d(n),i=await this.validate(o);if(!i.valid)throw new Error(`Invalid workflow template ${r}:
3
3
  ${i.errors.join(`
4
4
  `)}`);return this.cache.set(r,o),o}catch(e){throw e.code==="ENOENT"?new Error(`Workflow template not found: ${r}`):e}}async list(){try{return(await k(this.templatesDir)).filter(e=>e.endsWith(".yaml")||e.endsWith(".yml")).map(e=>y(e,e.endsWith(".yaml")?".yaml":".yml")).sort()}catch(r){if(r.code==="ENOENT")return[];throw r}}async validate(r){let e=[],n=[];if(r.name||e.push("Workflow must have a name"),r.version||e.push("Workflow must have a version"),r.description||n.push("Workflow should have a description"),Array.isArray(r.variables)?r.variables.forEach((o,i)=>{o.name||e.push(`Variable at index ${i} must have a name`),o.type||e.push(`Variable ${o.name} must have a type`),o.required===void 0&&n.push(`Variable ${o.name} should specify if it's required`)}):e.push("Workflow must have a variables array"),!Array.isArray(r.steps))e.push("Workflow must have a steps array");else if(r.steps.length===0)e.push("Workflow must have at least one step");else{r.steps.forEach((t,s)=>{t.name||e.push(`Step at index ${s} must have a name`),t.action||e.push(`Step ${t.name||s} must have an action`),(!t.config||typeof t.config!="object")&&e.push(`Step ${t.name||s} must have a config object`),t.assertions&&Array.isArray(t.assertions)&&t.assertions.forEach((f,u)=>{f.condition||e.push(`Assertion ${u} in step ${t.name||s} must have a condition`),f.message||n.push(`Assertion ${u} in step ${t.name||s} should have a message`)})});let o=r.steps.map(t=>t.name),i=o.filter((t,s)=>o.indexOf(t)!==s);i.length>0&&e.push(`Duplicate step names found: ${i.join(", ")}`)}return{valid:e.length===0,errors:e,warnings:n}}async createContext(r,e){let n=await this.load(r),o=n.variables.filter(t=>t.required&&!(t.name in e)).map(t=>t.name);if(o.length>0)throw new Error(`Missing required variables: ${o.join(", ")}`);let i={};return n.variables.forEach(t=>{t.name in e?i[t.name]=e[t.name]:"default"in t&&(i[t.name]=t.default)}),{variables:i,results:new Map,metadata:{startTime:Date.now(),workflow:n.name,templateName:r}}}async getMetadata(r){try{let e=c(this.templatesDir,`${r}.yaml`),n=await m(e,"utf-8"),o=d(n);return{name:o.name,version:o.version,description:o.description}}catch(e){throw e.code==="ENOENT"?new Error(`Workflow template not found: ${r}`):e}}clearCache(){this.cache.clear()}async reload(r){return this.cache.delete(r),this.load(r)}},x=new l;function w(a,r){return a.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=n.trim().split("."),t=r;for(let s of i)if(t&&typeof t=="object"&&s in t)t=t[s];else return e;return t!=null?String(t):e})}function T(a,r){let e={...r.variables,result:r.results.get("__last_result__")},n=w(a,e);return p(n,e,!1)}var g=["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"],A={"login-flow":"Authentication testing workflow for login forms with credential validation","oauth-flow":"OAuth2/OIDC authentication testing workflow with provider integration","scraping-workflow":"Data extraction workflow for web scraping with pagination and structured output","visual-regression":"Screenshot comparison workflow for visual regression testing across breakpoints","form-validation":"Input validation testing workflow for form fields with error handling","navigation-flow":"Multi-page navigation workflow for testing user journeys and state persistence","api-integration":"Browser-API hybrid testing workflow for validating frontend-backend integration","performance-audit":"Lighthouse-style performance audit workflow with Core Web Vitals","accessibility-audit":"WCAG 2.1 Level AA compliance audit workflow with automated accessibility testing"},h={authentication:["login-flow","oauth-flow"],testing:["form-validation","navigation-flow","api-integration"],quality:["visual-regression","performance-audit","accessibility-audit"],automation:["scraping-workflow"]};function _(a){return h[a]}function P(a){return g.includes(a)}function L(){return g.map(a=>{let r=Object.entries(h).find(([e,n])=>n.includes(a))?.[0]||"other";return{name:a,description:A[a],category:r}})}export{h as WORKFLOW_CATEGORIES,A as WORKFLOW_DESCRIPTIONS,g as WORKFLOW_TEMPLATES,l as WorkflowLoader,x as defaultWorkflowLoader,T as evaluateCondition,L as getAllWorkflowTemplates,_ as getWorkflowsByCategory,w as interpolateVariables,P as isValidWorkflowTemplate};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.6");process.exit(0)}
2
+ import{a}from"./chunk-RTFO5UQH.js";import"./chunk-5QQSIGUA.js";import"./chunk-BMAPORJ7.js";import"./chunk-2JVWITNK.js";import"./chunk-Q5XTSMWR.js";import"./chunk-AIRGNL55.js";import"./chunk-QW6VMTBR.js";import"./chunk-SDRHUMJB.js";import"./chunk-TCHGOB2N.js";import"./chunk-FBMN7B46.js";import"./chunk-ENGZ4D5V.js";import"./chunk-MJS53PRX.js";import"./chunk-DPYSUDAO.js";import"./chunk-WCJBU2KI.js";import"./chunk-PI7TJS62.js";import"./chunk-EAY2JMZG.js";import"./chunk-C6KWXUFJ.js";import"./chunk-IB27QACC.js";import"./chunk-6SH5VZUD.js";import"./chunk-SESK3ARK.js";import"./chunk-SNOBH4AZ.js";import"./chunk-IQO7UCFR.js";import"./chunk-DUYOVM5I.js";import"./chunk-64VGZQLB.js";export{a as BrowserWorkflowTool};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
- import{a as q}from"./chunk-KEY43ANX.js";import{c as V,d as W}from"./chunk-ZCWERUYB.js";import{c as x}from"./chunk-CZO4BJG5.js";import{b as E,d as $}from"./chunk-IJHCIXJC.js";import{a as G}from"./chunk-J27F4NSB.js";import{c as R}from"./chunk-7CD7PBHY.js";import{a as C,c as H}from"./chunk-J5UNP6W3.js";import{i as v}from"./chunk-W2XCZU62.js";import{a as M,b as U,d as ee}from"./chunk-XZSMZHM2.js";var P={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};$();H();var T=class p{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...P,...e}}async initialize(){if(!this.initialized)try{if(this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.prepareStatements(),this.initialized=!0,this.config.debug){let e=await this.getStats();console.log(`[ConceptGraph] Initialized: ${this.persistence.getDbPath()}`,e)}}catch(e){throw new Error(`Failed to initialize ConceptGraph: ${C(e)}`)}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertNode",this.db.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.6");process.exit(0)}
2
+ import{a as q}from"./chunk-3EA536JF.js";import{c as V,d as W}from"./chunk-AHKELLIO.js";import{c as x}from"./chunk-4N23RFDU.js";import{b as E,d as $}from"./chunk-AIRGNL55.js";import{a as G}from"./chunk-TCHGOB2N.js";import{e as R}from"./chunk-FBMN7B46.js";import{a as C,c as H}from"./chunk-MJS53PRX.js";import{i as v}from"./chunk-DPYSUDAO.js";import{a as M,b as U,d as ee}from"./chunk-IB27QACC.js";var P={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};$();H();var T=class p{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...P,...e}}async initialize(){if(!this.initialized)try{if(this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.prepareStatements(),this.initialized=!0,this.config.debug){let e=await this.getStats();console.log(`[ConceptGraph] Initialized: ${this.persistence.getDbPath()}`,e)}}catch(e){throw new Error(`Failed to initialize ConceptGraph: ${C(e)}`)}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertNode",this.db.prepare(`
3
3
  INSERT INTO concept_nodes
4
4
  (id, concept_type, content, embedding, activation_level, last_activated, pattern_id, metadata)
5
5
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
@@ -63,7 +63,7 @@ import{a as q}from"./chunk-KEY43ANX.js";import{c as V,d as W}from"./chunk-ZCWERU
63
63
  ORDER BY weight DESC
64
64
  LIMIT -1 OFFSET ?
65
65
  )
66
- `).run(s,e);r+=c.changes}return r})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,r=t.get().count,a={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)a[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:r,byType:a,avgEdgesPerNode:i>0?r/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?E(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function te(p){return new T(p)}ee();function ne(p,e){if(e<0||e>=p.length)return p[0]??0;let t=0,n=p.length-1;for(;t<n;){let i=t+n>>1;if(p[i]<p[t]){let s=p[t];p[t]=p[i],p[i]=s}if(p[n]<p[t]){let s=p[t];p[t]=p[n],p[n]=s}if(p[i]<p[n]){let s=p[i];p[i]=p[n],p[n]=s}let r=p[n],a=t;for(let s=t;s<n;s++)if(p[s]<=r){let c=p[a];p[a]=p[s],p[s]=c,a++}let o=p[a];if(p[a]=p[n],p[n]=o,a===e)return p[a];a<e?t=a+1:n=a-1}return p[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},w=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(d=>this.graph.getConcept(d)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let d of i)this.graph.setActivation(d,t),this.recordActivation(d,t);let r=0,a=t,o=0,s=0;for(;r<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),h=this.graph.getActiveNodes(this.config.threshold);for(let g of h)g.activationLevel>a&&(a=g.activationLevel);if(h.length===o&&d===0){if(s++,s>=3)break}else s=0;o=h.length,r++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,h)=>h.activation-d.activation),l=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:r,nodesActivated:c.length,peakActivation:a,activatedNodes:c,novelAssociations:l.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,r=0,a=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let d=U(0,o.length),h=o[d];if(h){let g=this.config.noiseLevel+M()*this.config.noiseLevel*2,m=h.activationLevel,y=Math.min(1,m+g+.3);this.graph.setActivation(h.id,y);let f=await this.spread([h.id],y,s);i+=f.iterations,f.peakActivation>r&&(r=f.peakActivation);for(let D of f.activatedNodes)a.add(D.nodeId);for(let D of f.novelAssociations)n.push(D)}if(Date.now()>=s)break;await this.sleep(50+M()*50)}let c=this.deduplicateAssociations(n),l=Array.from(a).map(d=>{let h=this.graph.getConcept(d);return{nodeId:d,activation:h?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,h)=>h.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:l.length,peakActivation:r,activatedNodes:l,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((a,o)=>o.activationLevel-a.activationLevel).slice(0,i));let r=[];for(let a=0;a<n.length;a++)for(let o=a+1;o<n.length;o++){let s=n[a],c=n[o],l=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),h=this.graph.getEdge(c.id,s.id),g=d!==void 0||h!==void 0,m=d?.weight??h?.weight??0,y=!g||m<.3;l>.3&&(r.push({source:s,target:c,coActivation:l,isNovel:y}),this.trackCoActivation(s.id,c.id))}return r.sort((a,o)=>a.isNovel!==o.isNovel?a.isNovel?-1:1:o.coActivation-a.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=B)return;let e=Math.floor(B*F),t=this.activationHistory.size-e,n=Array.from(this.activationHistory.keys()).slice(0,t);for(let i of n)this.activationHistory.delete(i)}trimCoActivationCounts(){if(this.coActivationCounts.size<=O)return;let e=Math.floor(O*F),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=ne(n,t-1),r=[];for(let[a,o]of this.coActivationCounts){if(r.length>=t)break;o<=i&&r.push(a)}for(let a of r)this.coActivationCounts.delete(a)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let r=this.graph.getEdges(i.id);for(let a of r){let o=this.graph.getConcept(a.target);if(!o)continue;let s=i.activationLevel*a.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,l=Math.min(1,c+s);n.push({nodeId:a.target,newActivation:l})}}}for(let i of n){let r=this.graph.getConcept(i.nodeId);r&&i.newActivation>r.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(M()-.5)*2*this.config.noiseLevel,i=Math.max(0,Math.min(1,t.activationLevel+n));this.graph.setActivation(t.id,i)}}recordActivation(e,t){let n=this.activationHistory.get(e)||[];n.push(t),n.length>50&&n.shift(),this.activationHistory.set(e,n)}trackCoActivation(e,t){let n=[e,t].sort().join(":"),i=this.coActivationCounts.get(n)||0;this.coActivationCounts.set(n,i+1)}deduplicateAssociations(e){let t=new Map;for(let n of e){let i=[n.source,n.target].sort().join(":"),r=t.get(i);(!r||n.strength>r.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ie}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},_=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let r=await this.detectPatternMerges(i);for(let c of r)c.cycleId=e,n.push(c);let a=await this.detectNovelAssociations(t.novelAssociations);for(let c of a)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,l)=>l.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let a=n[i],o=n[r],s=this.graph.getEdge(a.id,o.id),c=this.graph.getEdge(o.id,a.id),l=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(a.content,o.content),h=Math.sqrt(a.activationLevel*o.activationLevel),g=l*.4+d*.3+h*.3;if(g>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[a.id,o.id]}),y=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[a.id,o.id],edgeWeight:l,contentSimilarity:d,coActivation:h});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[a.id,o.id],description:this.generatePatternMergeDescription(a,o,g),noveltyScore:m,confidenceScore:y,actionable:y>=this.config.minConfidence,applied:!1,suggestedAction:y>=this.config.minConfidence?`Merge "${this.truncate(a.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),r=this.graph.getConcept(n.target);if(!i||!r)continue;let a=this.graph.getEdge(n.source,n.target);if(a&&a.weight>.5)continue;let o=i.conceptType!==r.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,r,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(r.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},r=i.successRate,a=i.executionCount,o=i.confidence,s=r!==void 0&&r<.7,c=a!==void 0&&a>10,l=o!==void 0&&o<.6;if(s||c&&l){let d=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),h=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,r,a),noveltyScore:d,confidenceScore:h,actionable:h>=this.config.minConfidence,applied:!1,suggestedAction:h>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let r=i.conceptType??"pattern";n[r]||(n[r]=[]),n[r].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(r=>r.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ie().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),r=new Set(n),a=new Set(i),o=n.filter(c=>a.has(c)),s=r.size+a.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let r=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${r}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};$();H();G();import{existsSync as re,unlinkSync as ae}from"fs";var A={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},b=class{constructor(e,t=A){this.db=e;this.thresholds=t}db;thresholds;activeBranches=new Map;listeners=[];rvfAdapter;useRvfFork=!1;_witnessChain=null;set witnessChain(e){this._witnessChain=e}setRvfAdapter(e,t=!0){this.rvfAdapter=e,this.useRvfFork=t,import("./feature-flags-7AC3XDZA.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-r/n.patternCount;d>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(d*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let d=o/n.highConfidenceCount;d>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(d*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let d=this.rvfAdapter.dimension?.()??384,h=new Float32Array(d);for(let m=0;m<d;m++)h[m]=Math.sin(m*.1);let g=this.rvfAdapter.search?.(h,10)??[];g.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${g.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let l=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:l,patternCountDelta:r,avgConfidenceDelta:a,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&re(n)&&ae(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var S=R.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...A}},k=class{constructor(e){this.graph=e}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},N=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase();try{this.db.pragma("busy_timeout = 60000")}catch{}this.migrateSchema(),this.graph=new T,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new b(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${C(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),S.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),S.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){S.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:v(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new k(this.graph);await a.loadIntoMemory(30);let s=await new w(a,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await a.persistActivations();let l=await new _(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=l.length;for(let h of l)await this.saveInsight(h);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let h=this.branchManager.validateBranch(i);if(h.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,h);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,h);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:h.reason},"dream-engine")}catch{}S.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:h.reason})}i=null}let d={cycle:{...this.currentCycle},insights:l,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(r){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=C(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async loadFailuresAsConcepts(e){return this.ensureInitialized(),this.graph.loadFailuresAsErrors(e)}async loadSuccessesAsConcepts(e){return this.ensureInitialized(),this.graph.loadSuccessesAsOutcomes(e)}async ensureConceptsLoaded(){this.ensureInitialized();try{let n=this.db.prepare(`SELECT n.id as id, n.pattern_id as sourcePatternId, p.qe_domain as domain, n.failure_mode as failureMode
66
+ `).run(s,e);r+=c.changes}return r})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,r=t.get().count,a={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)a[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:r,byType:a,avgEdgesPerNode:i>0?r/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?E(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function te(p){return new T(p)}ee();function ne(p,e){if(e<0||e>=p.length)return p[0]??0;let t=0,n=p.length-1;for(;t<n;){let i=t+n>>1;if(p[i]<p[t]){let s=p[t];p[t]=p[i],p[i]=s}if(p[n]<p[t]){let s=p[t];p[t]=p[n],p[n]=s}if(p[i]<p[n]){let s=p[i];p[i]=p[n],p[n]=s}let r=p[n],a=t;for(let s=t;s<n;s++)if(p[s]<=r){let c=p[a];p[a]=p[s],p[s]=c,a++}let o=p[a];if(p[a]=p[n],p[n]=o,a===e)return p[a];a<e?t=a+1:n=a-1}return p[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},w=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(d=>this.graph.getConcept(d)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let d of i)this.graph.setActivation(d,t),this.recordActivation(d,t);let r=0,a=t,o=0,s=0;for(;r<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),h=this.graph.getActiveNodes(this.config.threshold);for(let g of h)g.activationLevel>a&&(a=g.activationLevel);if(h.length===o&&d===0){if(s++,s>=3)break}else s=0;o=h.length,r++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,h)=>h.activation-d.activation),l=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:r,nodesActivated:c.length,peakActivation:a,activatedNodes:c,novelAssociations:l.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,r=0,a=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let d=U(0,o.length),h=o[d];if(h){let g=this.config.noiseLevel+M()*this.config.noiseLevel*2,m=h.activationLevel,y=Math.min(1,m+g+.3);this.graph.setActivation(h.id,y);let f=await this.spread([h.id],y,s);i+=f.iterations,f.peakActivation>r&&(r=f.peakActivation);for(let D of f.activatedNodes)a.add(D.nodeId);for(let D of f.novelAssociations)n.push(D)}if(Date.now()>=s)break;await this.sleep(50+M()*50)}let c=this.deduplicateAssociations(n),l=Array.from(a).map(d=>{let h=this.graph.getConcept(d);return{nodeId:d,activation:h?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,h)=>h.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:l.length,peakActivation:r,activatedNodes:l,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((a,o)=>o.activationLevel-a.activationLevel).slice(0,i));let r=[];for(let a=0;a<n.length;a++)for(let o=a+1;o<n.length;o++){let s=n[a],c=n[o],l=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),h=this.graph.getEdge(c.id,s.id),g=d!==void 0||h!==void 0,m=d?.weight??h?.weight??0,y=!g||m<.3;l>.3&&(r.push({source:s,target:c,coActivation:l,isNovel:y}),this.trackCoActivation(s.id,c.id))}return r.sort((a,o)=>a.isNovel!==o.isNovel?a.isNovel?-1:1:o.coActivation-a.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=B)return;let e=Math.floor(B*F),t=this.activationHistory.size-e,n=Array.from(this.activationHistory.keys()).slice(0,t);for(let i of n)this.activationHistory.delete(i)}trimCoActivationCounts(){if(this.coActivationCounts.size<=O)return;let e=Math.floor(O*F),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=ne(n,t-1),r=[];for(let[a,o]of this.coActivationCounts){if(r.length>=t)break;o<=i&&r.push(a)}for(let a of r)this.coActivationCounts.delete(a)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let r=this.graph.getEdges(i.id);for(let a of r){let o=this.graph.getConcept(a.target);if(!o)continue;let s=i.activationLevel*a.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,l=Math.min(1,c+s);n.push({nodeId:a.target,newActivation:l})}}}for(let i of n){let r=this.graph.getConcept(i.nodeId);r&&i.newActivation>r.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(M()-.5)*2*this.config.noiseLevel,i=Math.max(0,Math.min(1,t.activationLevel+n));this.graph.setActivation(t.id,i)}}recordActivation(e,t){let n=this.activationHistory.get(e)||[];n.push(t),n.length>50&&n.shift(),this.activationHistory.set(e,n)}trackCoActivation(e,t){let n=[e,t].sort().join(":"),i=this.coActivationCounts.get(n)||0;this.coActivationCounts.set(n,i+1)}deduplicateAssociations(e){let t=new Map;for(let n of e){let i=[n.source,n.target].sort().join(":"),r=t.get(i);(!r||n.strength>r.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ie}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},_=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let r=await this.detectPatternMerges(i);for(let c of r)c.cycleId=e,n.push(c);let a=await this.detectNovelAssociations(t.novelAssociations);for(let c of a)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,l)=>l.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let a=n[i],o=n[r],s=this.graph.getEdge(a.id,o.id),c=this.graph.getEdge(o.id,a.id),l=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(a.content,o.content),h=Math.sqrt(a.activationLevel*o.activationLevel),g=l*.4+d*.3+h*.3;if(g>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[a.id,o.id]}),y=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[a.id,o.id],edgeWeight:l,contentSimilarity:d,coActivation:h});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[a.id,o.id],description:this.generatePatternMergeDescription(a,o,g),noveltyScore:m,confidenceScore:y,actionable:y>=this.config.minConfidence,applied:!1,suggestedAction:y>=this.config.minConfidence?`Merge "${this.truncate(a.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),r=this.graph.getConcept(n.target);if(!i||!r)continue;let a=this.graph.getEdge(n.source,n.target);if(a&&a.weight>.5)continue;let o=i.conceptType!==r.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,r,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(r.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},r=i.successRate,a=i.executionCount,o=i.confidence,s=r!==void 0&&r<.7,c=a!==void 0&&a>10,l=o!==void 0&&o<.6;if(s||c&&l){let d=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),h=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,r,a),noveltyScore:d,confidenceScore:h,actionable:h>=this.config.minConfidence,applied:!1,suggestedAction:h>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let r=i.conceptType??"pattern";n[r]||(n[r]=[]),n[r].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(r=>r.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ie().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),r=new Set(n),a=new Set(i),o=n.filter(c=>a.has(c)),s=r.size+a.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let r=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${r}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};$();H();G();import{existsSync as re,unlinkSync as ae}from"fs";var A={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},b=class{constructor(e,t=A){this.db=e;this.thresholds=t}db;thresholds;activeBranches=new Map;listeners=[];rvfAdapter;useRvfFork=!1;_witnessChain=null;set witnessChain(e){this._witnessChain=e}setRvfAdapter(e,t=!0){this.rvfAdapter=e,this.useRvfFork=t,import("./feature-flags-NAHKLDRN.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-r/n.patternCount;d>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(d*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let d=o/n.highConfidenceCount;d>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(d*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let d=this.rvfAdapter.dimension?.()??384,h=new Float32Array(d);for(let m=0;m<d;m++)h[m]=Math.sin(m*.1);let g=this.rvfAdapter.search?.(h,10)??[];g.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${g.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let l=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:l,patternCountDelta:r,avgConfidenceDelta:a,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&re(n)&&ae(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var S=R.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...A}},k=class{constructor(e){this.graph=e}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},N=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase();try{this.db.pragma("busy_timeout = 60000")}catch{}this.migrateSchema(),this.graph=new T,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new b(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${C(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),S.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),S.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){S.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:v(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new k(this.graph);await a.loadIntoMemory(30);let s=await new w(a,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await a.persistActivations();let l=await new _(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=l.length;for(let h of l)await this.saveInsight(h);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let h=this.branchManager.validateBranch(i);if(h.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,h);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,h);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:h.reason},"dream-engine")}catch{}S.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:h.reason})}i=null}let d={cycle:{...this.currentCycle},insights:l,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(r){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=C(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async loadFailuresAsConcepts(e){return this.ensureInitialized(),this.graph.loadFailuresAsErrors(e)}async loadSuccessesAsConcepts(e){return this.ensureInitialized(),this.graph.loadSuccessesAsOutcomes(e)}async ensureConceptsLoaded(){this.ensureInitialized();try{let n=this.db.prepare(`SELECT n.id as id, n.pattern_id as sourcePatternId, p.qe_domain as domain, n.failure_mode as failureMode
67
67
  FROM qe_pattern_nulls n
68
68
  JOIN qe_patterns p ON p.id = n.pattern_id
69
69
  ORDER BY n.updated_at DESC
@@ -89,7 +89,7 @@ import{a as q}from"./chunk-KEY43ANX.js";import{c as V,d as W}from"./chunk-ZCWERU
89
89
  WHERE confidence >= 0.3 AND success_rate < 0.7
90
90
  ORDER BY usage_count DESC
91
91
  LIMIT 40
92
- )`).all();return t.length===0?0:this.graph.loadFromPatterns(t)}async applyInsight(e){this.ensureInitialized();try{let t=await this.getInsightRowById(e);if(!t)return{success:!1,error:`Insight not found: ${e}`};if(t.actionable!==1)return{success:!1,error:"Insight is not actionable"};if(t.applied===1)return{success:!0,patternId:t.pattern_id??void 0,error:"Insight already applied"};let{getSharedMemoryBackend:n}=await import("./base-P3Z4IKCT.js"),{createQEReasoningBank:i}=await import("./qe-reasoning-bank-DJ2JL6QB.js"),r=await n(),a=i(r);await a.initialize();try{let{getSharedRvfDualWriter:d}=await import("./shared-rvf-dual-writer-THFDYS2Z.js"),h=await d();h&&a.setRvfDualWriter(h)}catch(d){process.env.DEBUG&&S.debug("RVF wiring skipped",{error:C(d)})}let o=[];try{o=E(t.source_concepts)}catch{}let s=await a.storePattern({patternType:se(t.insight_type),name:`Dream Insight: ${t.insight_type}`,description:`${t.description} (confidence: ${t.confidence_score.toFixed(2)})`,template:{type:"workflow",content:t.suggested_action||t.description,variables:[]},context:{tags:["dream-generated",t.insight_type,...o.slice(0,3)],complexity:"medium"}});if(!s.success)return{success:!1,error:`Failed to create pattern: ${s.error?.message??"unknown error"}`};let c=s.value.id;return this.db.prepare(`
92
+ )`).all();return t.length===0?0:this.graph.loadFromPatterns(t)}async applyInsight(e){this.ensureInitialized();try{let t=await this.getInsightRowById(e);if(!t)return{success:!1,error:`Insight not found: ${e}`};if(t.actionable!==1)return{success:!1,error:"Insight is not actionable"};if(t.applied===1)return{success:!0,patternId:t.pattern_id??void 0,error:"Insight already applied"};let{getSharedMemoryBackend:n}=await import("./base-DRZ2LS6X.js"),{createQEReasoningBank:i}=await import("./qe-reasoning-bank-7IETWW6W.js"),r=await n(),a=i(r);await a.initialize();try{let{getSharedRvfDualWriter:d}=await import("./shared-rvf-dual-writer-UVWGDUWC.js"),h=await d();h&&a.setRvfDualWriter(h)}catch(d){process.env.DEBUG&&S.debug("RVF wiring skipped",{error:C(d)})}let o=[];try{o=E(t.source_concepts)}catch{}let s=await a.storePattern({patternType:se(t.insight_type),name:`Dream Insight: ${t.insight_type}`,description:`${t.description} (confidence: ${t.confidence_score.toFixed(2)})`,template:{type:"workflow",content:t.suggested_action||t.description,variables:[]},context:{tags:["dream-generated",t.insight_type,...o.slice(0,3)],complexity:"medium"}});if(!s.success)return{success:!1,error:`Failed to create pattern: ${s.error?.message??"unknown error"}`};let c=s.value.id;return this.db.prepare(`
93
93
  UPDATE dream_insights
94
94
  SET applied = 1, pattern_id = ?
95
95
  WHERE id = ?
@@ -117,4 +117,4 @@ import{a as q}from"./chunk-KEY43ANX.js";import{c as V,d as W}from"./chunk-ZCWERU
117
117
  (id, cycle_id, insight_type, source_concepts, description, novelty_score,
118
118
  confidence_score, actionable, applied, suggested_action, pattern_id)
119
119
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
120
- `).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:E(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function se(p){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[p]||"test-template"}function oe(p){let e=new N(p);return import("./feature-flags-7AC3XDZA.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-NFL6QSZ6.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var ce=N;G();var Y="learning:loop-health";async function J(p,e,t){try{let n=new Date().toISOString(),i=await p.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await p.set(Y,i)}catch{}}var u=R.create("DreamScheduler"),Z={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},K="dream-scheduler:hook-state",L=class p{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Z,...t},this.metaLearningEngine=new W}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,u.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),u.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),u.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,u.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(u.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{u.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,u.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&u.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){u.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),u.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&u.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){u.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-NFL6QSZ6.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&u.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){u.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-THFDYS2Z.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&u.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){u.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new q,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>p.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){u.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)u.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>p.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:v(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{u.debug("Failed to publish meta-learning insight event")}}}else u.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),u.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){u.info("Quality gate failed but cannot start dream yet");return}u.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){u.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){u.info("Milestone reached but cannot start dream yet");return}u.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:v(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){u.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(K),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(K,t)}catch(e){u.warn("Dream hook-state reconcile failed (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){u.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],u.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){u.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function de(p,e){return new L(p,e)}var pe=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],z=class{constructor(e,t){this.db=e;this.branchManager=new b(e,t??A)}db;branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,l)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(l.validation)>d?l:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,P as b,T as c,te as d,B as e,O as f,F as g,j as h,w as i,Q as j,_ as k,A as l,b as m,X as n,N as o,oe as p,ce as q,pe as r,z as s,Z as t,L as u,de as v};
120
+ `).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:E(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function se(p){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[p]||"test-template"}function oe(p){let e=new N(p);return import("./feature-flags-NAHKLDRN.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-VIJB7JUS.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var ce=N;G();var Y="learning:loop-health";async function J(p,e,t){try{let n=new Date().toISOString(),i=await p.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await p.set(Y,i)}catch{}}var u=R.create("DreamScheduler"),Z={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},K="dream-scheduler:hook-state",L=class p{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Z,...t},this.metaLearningEngine=new W}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,u.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),u.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),u.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,u.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(u.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{u.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,u.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&u.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){u.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),u.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&u.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){u.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-VIJB7JUS.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&u.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){u.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-UVWGDUWC.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&u.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){u.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new q,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>p.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){u.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)u.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>p.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:v(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{u.debug("Failed to publish meta-learning insight event")}}}else u.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),u.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){u.info("Quality gate failed but cannot start dream yet");return}u.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){u.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){u.info("Milestone reached but cannot start dream yet");return}u.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:v(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){u.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(K),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(K,t)}catch(e){u.warn("Dream hook-state reconcile failed (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){u.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],u.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){u.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function de(p,e){return new L(p,e)}var pe=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],z=class{constructor(e,t){this.db=e;this.branchManager=new b(e,t??A)}db;branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,l)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(l.validation)>d?l:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,P as b,T as c,te as d,B as e,O as f,F as g,j as h,w as i,Q as j,_ as k,A as l,b as m,X as n,N as o,oe as p,ce as q,pe as r,z as s,Z as t,L as u,de as v};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
- import{d as j,f as ze}from"./chunk-RKOUXVZZ.js";import{b as I,d as oe}from"./chunk-IJHCIXJC.js";import{a as z,c as He}from"./chunk-NQI7FWCS.js";import{a as H,b as D,c as We}from"./chunk-C3HQL6S4.js";import{a as qe}from"./chunk-J27F4NSB.js";import{c as re}from"./chunk-7CD7PBHY.js";import{a as X,c as ke}from"./chunk-J5UNP6W3.js";import{a as ie,b as je}from"./chunk-HVU64GP5.js";import{a as ae,d as U,e as ce,f as Te}from"./chunk-52L77RMG.js";import{a as b,b as se,e as Be}from"./chunk-CVMNJSCB.js";import{b as R,d as Pe}from"./chunk-JSZ663MU.js";import{createHash as ue}from"node:crypto";function $e(s){let e=Buffer.alloc(8);return e.writeBigUInt64LE(BigInt(s)),e}function Ke(s){return typeof s=="string"?Buffer.from(s,"utf8"):s instanceof Uint8Array?Buffer.from(s):Buffer.from(W(s),"utf8")}function W(s){return s===null||typeof s!="object"?JSON.stringify(s)??"null":Array.isArray(s)?`[${s.map(W).join(",")}]`:`{${Object.keys(s).sort().map(t=>`${JSON.stringify(t)}:${W(s[t])}`).join(",")}}`}function _e(...s){let e=ue("sha256");for(let t of s)e.update(t);return e.digest()}function de(s,e,t){return _e(Ye,s,e,$e(t))}var Ye,Ee,O,le=R(()=>{"use strict";Ye=Buffer.from("ruvector:chain:"),Ee=ue("sha256").update("ruvector-proof-gate-v1").digest();O=class s{seq=0;prev=Ee;chain=[];payloadHashes=[];admit(e){let t=_e(Ke(e)),n=de(this.prev,t,this.seq);this.prev=n,this.chain.push(n),this.payloadHashes.push(t);let a={sequence:this.seq,payloadHash:t.toString("hex"),chainCommitment:n.toString("hex")};return this.seq+=1,a}verifyReceipt(e){return e.sequence>=0&&e.sequence<this.chain.length&&this.chain[e.sequence].toString("hex")===e.chainCommitment}chainRoot(){return this.prev.toString("hex")}get length(){return this.seq}get isEmpty(){return this.seq===0}verifyIntegrity(){if(this.chain.length!==this.payloadHashes.length)return!1;let e=Ee;for(let t=0;t<this.chain.length;t++){if(!de(e,this.payloadHashes[t],t).equals(this.chain[t]))return!1;e=this.chain[t]}return e.equals(this.prev)}toJSON(){return{seq:this.seq,head:this.prev.toString("hex"),chain:this.chain.map(e=>e.toString("hex")),payloadHashes:this.payloadHashes.map(e=>e.toString("hex"))}}static fromJSON(e){let t=new s;t.seq=e.seq,t.prev=Buffer.from(e.head,"hex");for(let n of e.chain)t.chain.push(Buffer.from(n,"hex"));for(let n of e.payloadHashes)t.payloadHashes.push(Buffer.from(n,"hex"));return t}}});function A(s){if(!Y.has(s))throw new Error(`Invalid table name: "${s}" is not in the allowlist`);return s}function ot(s){let e=s.split(".");if(e.length>2)throw new Error(`Invalid SQL identifier: "${s}" has too many parts (max: schema.table)`);for(let t of e)if(!pe.test(t))throw new Error(`Invalid SQL identifier: "${s}" \u2014 part "${t}" does not match pattern ${pe}`);return s}var Y,pe,$=R(()=>{"use strict";Y=new Set(["schema_version","kv_store","vectors","rl_q_values","goap_goals","goap_actions","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","sona_patterns","sona_fisher_matrices","test_outcomes","routing_outcomes","coverage_sessions","patterns","hypergraph_nodes","hypergraph_edges","hypergraph_vertices","hypergraph_hyperedges","hypergraph_edge_vertices","hypergraph_vertex_properties","hypergraph_edge_properties","captured_experiences","experience_applications","witness_chain","witness_chain_receipts","witness_chain_archive","trajectories","trajectory_steps","pattern_evolution_events","pattern_relationships","pattern_versions","learning_daily_snapshots","metrics_outcomes","experience_consolidation_log","qe_pattern_reuse","learning_evidence_manifests","learning_evidence_segments","learning_segment_edges","learning_evidence_admissions","pattern_manifest_lineage","pattern_segment_lineage","qe_agent_co_execution"]);pe=/^[a-z_][a-z0-9_]{0,62}$/});function me(s){s.exec(ge),s.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.6");process.exit(0)}
2
+ import{d as j,f as ze}from"./chunk-Q5XTSMWR.js";import{b as I,d as oe}from"./chunk-AIRGNL55.js";import{a as z,c as He}from"./chunk-QW6VMTBR.js";import{a as H,b as D,c as We}from"./chunk-SDRHUMJB.js";import{a as qe}from"./chunk-TCHGOB2N.js";import{e as re}from"./chunk-FBMN7B46.js";import{a as X,c as ke}from"./chunk-MJS53PRX.js";import{a as ie,b as je}from"./chunk-PI7TJS62.js";import{a as ae,d as U,e as ce,f as Te}from"./chunk-C6KWXUFJ.js";import{a as b,b as se,e as Be}from"./chunk-6SH5VZUD.js";import{b as R,d as Pe}from"./chunk-64VGZQLB.js";import{createHash as ue}from"node:crypto";function $e(s){let e=Buffer.alloc(8);return e.writeBigUInt64LE(BigInt(s)),e}function Ke(s){return typeof s=="string"?Buffer.from(s,"utf8"):s instanceof Uint8Array?Buffer.from(s):Buffer.from(W(s),"utf8")}function W(s){return s===null||typeof s!="object"?JSON.stringify(s)??"null":Array.isArray(s)?`[${s.map(W).join(",")}]`:`{${Object.keys(s).sort().map(t=>`${JSON.stringify(t)}:${W(s[t])}`).join(",")}}`}function _e(...s){let e=ue("sha256");for(let t of s)e.update(t);return e.digest()}function de(s,e,t){return _e(Ye,s,e,$e(t))}var Ye,Ee,O,le=R(()=>{"use strict";Ye=Buffer.from("ruvector:chain:"),Ee=ue("sha256").update("ruvector-proof-gate-v1").digest();O=class s{seq=0;prev=Ee;chain=[];payloadHashes=[];admit(e){let t=_e(Ke(e)),n=de(this.prev,t,this.seq);this.prev=n,this.chain.push(n),this.payloadHashes.push(t);let a={sequence:this.seq,payloadHash:t.toString("hex"),chainCommitment:n.toString("hex")};return this.seq+=1,a}verifyReceipt(e){return e.sequence>=0&&e.sequence<this.chain.length&&this.chain[e.sequence].toString("hex")===e.chainCommitment}chainRoot(){return this.prev.toString("hex")}get length(){return this.seq}get isEmpty(){return this.seq===0}verifyIntegrity(){if(this.chain.length!==this.payloadHashes.length)return!1;let e=Ee;for(let t=0;t<this.chain.length;t++){if(!de(e,this.payloadHashes[t],t).equals(this.chain[t]))return!1;e=this.chain[t]}return e.equals(this.prev)}toJSON(){return{seq:this.seq,head:this.prev.toString("hex"),chain:this.chain.map(e=>e.toString("hex")),payloadHashes:this.payloadHashes.map(e=>e.toString("hex"))}}static fromJSON(e){let t=new s;t.seq=e.seq,t.prev=Buffer.from(e.head,"hex");for(let n of e.chain)t.chain.push(Buffer.from(n,"hex"));for(let n of e.payloadHashes)t.payloadHashes.push(Buffer.from(n,"hex"));return t}}});function A(s){if(!Y.has(s))throw new Error(`Invalid table name: "${s}" is not in the allowlist`);return s}function ot(s){let e=s.split(".");if(e.length>2)throw new Error(`Invalid SQL identifier: "${s}" has too many parts (max: schema.table)`);for(let t of e)if(!pe.test(t))throw new Error(`Invalid SQL identifier: "${s}" \u2014 part "${t}" does not match pattern ${pe}`);return s}var Y,pe,$=R(()=>{"use strict";Y=new Set(["schema_version","kv_store","vectors","rl_q_values","goap_goals","goap_actions","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","sona_patterns","sona_fisher_matrices","test_outcomes","routing_outcomes","coverage_sessions","patterns","hypergraph_nodes","hypergraph_edges","hypergraph_vertices","hypergraph_hyperedges","hypergraph_edge_vertices","hypergraph_vertex_properties","hypergraph_edge_properties","captured_experiences","experience_applications","witness_chain","witness_chain_receipts","witness_chain_archive","trajectories","trajectory_steps","pattern_evolution_events","pattern_relationships","pattern_versions","learning_daily_snapshots","metrics_outcomes","experience_consolidation_log","qe_pattern_reuse","learning_evidence_manifests","learning_evidence_segments","learning_segment_edges","learning_evidence_admissions","pattern_manifest_lineage","pattern_segment_lineage","qe_agent_co_execution"]);pe=/^[a-z_][a-z0-9_]{0,62}$/});function me(s){s.exec(ge),s.exec(`
3
3
  INSERT OR IGNORE INTO learning_evidence_manifests (
4
4
  id, trajectory_id, trajectory_hash, manifest_hash, task_family,
5
5
  outcome, oracle_refs_json, source_kind, process_signals_json