agentic-qe 3.11.4 → 3.12.0

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 (449) hide show
  1. package/.claude/helpers/.helpers-version +1 -0
  2. package/.claude/helpers/auto-memory-hook.mjs +35 -3
  3. package/.claude/helpers/brain-checkpoint.cjs +16 -1
  4. package/.claude/helpers/helpers.manifest.json +12 -0
  5. package/.claude/helpers/hook-handler.cjs +26 -5
  6. package/.claude/helpers/intelligence.cjs +14 -1
  7. package/.claude/hooks/aqe-hook.cjs +57 -10
  8. package/.claude/skills/skills-manifest.json +1 -1
  9. package/CHANGELOG.md +110 -0
  10. package/assets/skills/skills-manifest.json +1 -1
  11. package/dist/adapters/a2a/auth/routes.js +59 -28
  12. package/dist/audit/witness-chain.d.ts +25 -0
  13. package/dist/audit/witness-chain.js +69 -22
  14. package/dist/audit/witness-key-manager.d.ts +11 -0
  15. package/dist/audit/witness-key-manager.js +24 -0
  16. package/dist/cli/brain-commands.js +2 -1
  17. package/dist/cli/bundle.js +6 -6
  18. package/dist/cli/chunks/adapter-6IWRIHF3.js +2 -0
  19. package/dist/cli/chunks/{agent-booster-wasm-62I6ZNRW.js → agent-booster-wasm-IO54X6IQ.js} +2 -2
  20. package/dist/cli/chunks/{agent-handler-E2TZKKBS.js → agent-handler-A57SZUCW.js} +2 -2
  21. package/dist/cli/chunks/{agent-memory-branch-JHAHC2NH.js → agent-memory-branch-BX7LRFGN.js} +2 -2
  22. package/dist/cli/chunks/aqe-learning-engine-FSF5U67K.js +2 -0
  23. package/dist/cli/chunks/{arena-72ZV65BR.js → arena-UTC4YY6Y.js} +4 -4
  24. package/dist/cli/chunks/{arena-KLG3YSSR.js → arena-Y3XTX6O7.js} +2 -2
  25. package/dist/cli/chunks/audit-L4RL2AOY.js +3 -0
  26. package/dist/cli/chunks/base-2CKCJU3O.js +2 -0
  27. package/dist/cli/chunks/{hnswlib-node-LAFK5QZ4.js → better-sqlite3-LRDXKYOJ.js} +2 -2
  28. package/dist/cli/chunks/brain-handler-OHDPI5TQ.js +89 -0
  29. package/dist/cli/chunks/{branch-enumerator-C7MPNYT7.js → branch-enumerator-ZRXE2CQ7.js} +2 -2
  30. package/dist/cli/chunks/{browser-UUDUDYLR.js → browser-NT33FG76.js} +2 -2
  31. package/dist/cli/chunks/browser-workflow-UGYJE64S.js +2 -0
  32. package/dist/cli/chunks/{chunk-7QTB5XIQ.js → chunk-27JCWG5J.js} +2 -2
  33. package/dist/cli/chunks/{chunk-3FJZMQJ7.js → chunk-2ALNNXFF.js} +2 -2
  34. package/dist/cli/chunks/{chunk-LMJUMUQJ.js → chunk-2AOOIAW3.js} +4 -4
  35. package/dist/cli/chunks/{chunk-CNF3ZWLM.js → chunk-2AR4B3DI.js} +2 -2
  36. package/dist/cli/chunks/{chunk-7ADD2ZQL.js → chunk-2KHDGC7N.js} +2 -2
  37. package/dist/cli/chunks/{chunk-P6S6ZVB5.js → chunk-2UMCB7AH.js} +1 -1
  38. package/dist/cli/chunks/{chunk-HH6NCBSP.js → chunk-335GHVJV.js} +22 -22
  39. package/dist/cli/chunks/{chunk-2WPSMQIL.js → chunk-36MPDANH.js} +1 -1
  40. package/dist/cli/chunks/{chunk-Y4AXOHW4.js → chunk-3AFNXU45.js} +1 -1
  41. package/dist/cli/chunks/{chunk-SL3SNOO2.js → chunk-3B4XXFKD.js} +2 -2
  42. package/dist/cli/chunks/{chunk-7IKWF2AD.js → chunk-4GU656WM.js} +1 -1
  43. package/dist/cli/chunks/{chunk-IQBZBUP5.js → chunk-4SALW7OT.js} +2 -2
  44. package/dist/cli/chunks/{chunk-TCVEKRPI.js → chunk-5FR5GBUT.js} +2 -2
  45. package/dist/cli/chunks/chunk-5VBPIJUZ.js +65 -0
  46. package/dist/cli/chunks/chunk-5XFX25AJ.js +4 -0
  47. package/dist/cli/chunks/{chunk-QSDIY3E2.js → chunk-5YGESYBC.js} +1 -1
  48. package/dist/cli/chunks/{chunk-5U2WHPXL.js → chunk-62RELCU6.js} +1 -1
  49. package/dist/cli/chunks/{chunk-QJ5NCYJ3.js → chunk-64M3FFM4.js} +2 -2
  50. package/dist/cli/chunks/{chunk-BMQDELPA.js → chunk-6JNNZGI2.js} +1 -1
  51. package/dist/cli/chunks/{chunk-U34OZXD6.js → chunk-6X3RJBA3.js} +2 -2
  52. package/dist/cli/chunks/{chunk-AE6HXMOG.js → chunk-72VZGAMJ.js} +1 -1
  53. package/dist/cli/chunks/{chunk-4JFH3MVA.js → chunk-7F7U2HUH.js} +1 -1
  54. package/dist/cli/chunks/{chunk-A4OMK3FO.js → chunk-7HJHXSYT.js} +2 -2
  55. package/dist/cli/chunks/chunk-7WX3MKRS.js +2 -0
  56. package/dist/cli/chunks/{chunk-O7PVZ32A.js → chunk-7ZIVDGSN.js} +1 -1
  57. package/dist/cli/chunks/{chunk-EZRHSHOQ.js → chunk-AAATFEIL.js} +2 -2
  58. package/dist/cli/chunks/{chunk-TQ373GGI.js → chunk-AEX75YGI.js} +2 -2
  59. package/dist/cli/chunks/chunk-BA6U7NSR.js +2 -0
  60. package/dist/cli/chunks/chunk-BB4OVXWF.js +14 -0
  61. package/dist/cli/chunks/{chunk-GRQ36XUH.js → chunk-BBC526PL.js} +2 -2
  62. package/dist/cli/chunks/{chunk-EONKMHKO.js → chunk-BGRJZH5Q.js} +2 -2
  63. package/dist/cli/chunks/{chunk-XQ6DW5FV.js → chunk-BUYPRUNY.js} +2 -2
  64. package/dist/cli/chunks/{chunk-TU6YN43Q.js → chunk-BZPF6GTL.js} +1 -1
  65. package/dist/cli/chunks/{chunk-TPMBFARK.js → chunk-C4SZSPXY.js} +67 -22
  66. package/dist/cli/chunks/{chunk-D6CKKNYC.js → chunk-C6GYLCTX.js} +2 -2
  67. package/dist/cli/chunks/{chunk-YNK6SUPU.js → chunk-CC5G3K4X.js} +2 -2
  68. package/dist/cli/chunks/{chunk-ADFKY3X2.js → chunk-CHO54B34.js} +2 -2
  69. package/dist/cli/chunks/{chunk-WQZ2WRO4.js → chunk-CMGYUCM7.js} +1 -1
  70. package/dist/cli/chunks/{chunk-QMC5MTBV.js → chunk-CSEEGX5T.js} +2 -2
  71. package/dist/cli/chunks/{chunk-FSGMRQFC.js → chunk-CVGXB7IX.js} +2 -2
  72. package/dist/cli/chunks/{chunk-5VSQAGA2.js → chunk-DQDFACYW.js} +1 -1
  73. package/dist/cli/chunks/chunk-DR7PCO3S.js +153 -0
  74. package/dist/cli/chunks/{chunk-D5S47YUS.js → chunk-DTOE3NYW.js} +3 -3
  75. package/dist/cli/chunks/{chunk-WZYNY3VF.js → chunk-DXOMRWDC.js} +1 -1
  76. package/dist/cli/chunks/{chunk-HJ24KMC2.js → chunk-EGH3H7QO.js} +1 -1
  77. package/dist/cli/chunks/{chunk-JFLSQH2X.js → chunk-EM2JIIAQ.js} +2 -2
  78. package/dist/cli/chunks/{chunk-MWFJC5HR.js → chunk-ESDGCTC4.js} +1 -1
  79. package/dist/cli/chunks/{chunk-SRVTNG6L.js → chunk-EZE2HRQB.js} +2 -2
  80. package/dist/cli/chunks/{chunk-ZFCVT43J.js → chunk-FEEMJDUF.js} +2 -2
  81. package/dist/cli/chunks/{chunk-HJO4RNOW.js → chunk-FI5SSLEF.js} +2 -2
  82. package/dist/cli/chunks/{chunk-XHRLBJTM.js → chunk-FKPUPQQT.js} +2 -2
  83. package/dist/cli/chunks/{chunk-ODZSQVEW.js → chunk-FOPS6DRZ.js} +1 -1
  84. package/dist/cli/chunks/{chunk-AQIEK4SY.js → chunk-FU5RNEXV.js} +2 -2
  85. package/dist/cli/chunks/{chunk-PQUXFSN6.js → chunk-FZIHOMGY.js} +2 -2
  86. package/dist/cli/chunks/{chunk-Z2REKBD6.js → chunk-FZRU73M4.js} +2 -2
  87. package/dist/cli/chunks/{chunk-NBBLPDJX.js → chunk-G5JQLUUO.js} +2 -2
  88. package/dist/cli/chunks/{chunk-4BFCLSDN.js → chunk-G6LR7FK7.js} +2 -2
  89. package/dist/cli/chunks/{chunk-QEVX4GWF.js → chunk-G6RKUEGL.js} +2 -2
  90. package/dist/cli/chunks/{chunk-HWBMYR5W.js → chunk-GCF42L7M.js} +5 -5
  91. package/dist/cli/chunks/{chunk-TSWF3AGQ.js → chunk-GGMQOEZZ.js} +2 -2
  92. package/dist/cli/chunks/{chunk-PFWJQPUC.js → chunk-HAEUPIKW.js} +2 -2
  93. package/dist/cli/chunks/{chunk-63QUN3JK.js → chunk-HDJMD6UH.js} +1 -1
  94. package/dist/cli/chunks/{chunk-JPENUVCI.js → chunk-HW62TB4T.js} +1 -1
  95. package/dist/cli/chunks/{chunk-WMIRAD3J.js → chunk-I6WHYRWB.js} +2 -2
  96. package/dist/cli/chunks/{chunk-YZ5EQR37.js → chunk-ICK3B24H.js} +2 -2
  97. package/dist/cli/chunks/{chunk-FRFVN6AA.js → chunk-IDLNLSQI.js} +2 -2
  98. package/dist/cli/chunks/{chunk-VQU7DMEY.js → chunk-IJUYHIKN.js} +2 -2
  99. package/dist/cli/chunks/{chunk-6JUOH6L4.js → chunk-IKVNYK7Y.js} +2 -2
  100. package/dist/cli/chunks/{chunk-ZKCKOQJI.js → chunk-JOBCMNTP.js} +2 -2
  101. package/dist/cli/chunks/{chunk-ARPBG6FQ.js → chunk-JYX7AZHE.js} +2 -2
  102. package/dist/cli/chunks/{chunk-SFDUT5WM.js → chunk-JYXSVSH2.js} +2 -2
  103. package/dist/cli/chunks/{chunk-VJGHRWMH.js → chunk-K5SN66B4.js} +2 -2
  104. package/dist/cli/chunks/{chunk-DNOU2HVQ.js → chunk-KDLYTJ5C.js} +2 -2
  105. package/dist/cli/chunks/{chunk-T76RFXQX.js → chunk-KI5BP4X5.js} +2 -2
  106. package/dist/cli/chunks/{chunk-7AWK43JN.js → chunk-KJWQ7ENF.js} +2 -2
  107. package/dist/cli/chunks/{chunk-BRLUNIR4.js → chunk-KN5GOEYK.js} +2 -2
  108. package/dist/cli/chunks/{chunk-VKJQAKYG.js → chunk-KZ37VHMJ.js} +2 -2
  109. package/dist/cli/chunks/{chunk-NV3TXXOW.js → chunk-KZMRU7DL.js} +2 -2
  110. package/dist/cli/chunks/{chunk-LLUPRGOR.js → chunk-L5ZLOW3K.js} +2 -2
  111. package/dist/cli/chunks/{chunk-THKZVOZV.js → chunk-LMJUQWR7.js} +1 -1
  112. package/dist/cli/chunks/{chunk-2KNFS3L5.js → chunk-MBF3Q7FQ.js} +1 -1
  113. package/dist/cli/chunks/chunk-MDT3LIXS.js +2 -0
  114. package/dist/cli/chunks/{chunk-B5XUWHKQ.js → chunk-MJPYNGZ7.js} +1 -1
  115. package/dist/cli/chunks/{chunk-UCYTY4LG.js → chunk-MK3J7JVZ.js} +2 -2
  116. package/dist/cli/chunks/{chunk-MCT4CD5M.js → chunk-MUAHFGIX.js} +2 -2
  117. package/dist/cli/chunks/{chunk-3SBUL72V.js → chunk-MUV56BPK.js} +2 -2
  118. package/dist/cli/chunks/{chunk-WNMDWP5A.js → chunk-NLHISTL2.js} +2 -2
  119. package/dist/cli/chunks/{chunk-UJMTKXPI.js → chunk-NNGCUJWQ.js} +2 -2
  120. package/dist/cli/chunks/chunk-NW7G57NR.js +27 -0
  121. package/dist/cli/chunks/{chunk-3SRPFBU7.js → chunk-O3C5RRDQ.js} +3 -3
  122. package/dist/cli/chunks/{chunk-AYGEWPN4.js → chunk-OHSVDMF7.js} +1 -1
  123. package/dist/cli/chunks/{chunk-AJXGGTX7.js → chunk-OPIWFXME.js} +1 -1
  124. package/dist/cli/chunks/{chunk-ZSBJNE35.js → chunk-P52YORQG.js} +2 -2
  125. package/dist/cli/chunks/chunk-PM566XEO.js +2 -0
  126. package/dist/cli/chunks/chunk-POKMJTD2.js +2 -0
  127. package/dist/cli/chunks/{chunk-GOQ4P2PB.js → chunk-PQMLIVGV.js} +2 -2
  128. package/dist/cli/chunks/{chunk-IB3ZPLFA.js → chunk-PT3FTGKZ.js} +2 -2
  129. package/dist/cli/chunks/{chunk-U3AVZGQA.js → chunk-Q5YRPS4P.js} +1 -1
  130. package/dist/cli/chunks/{chunk-5Z4FBCBK.js → chunk-QJ6H2HQQ.js} +1 -1
  131. package/dist/cli/chunks/{chunk-DRMHVY4T.js → chunk-RG552ROA.js} +4 -4
  132. package/dist/cli/chunks/{chunk-PEIQDQXN.js → chunk-RHC7TFPU.js} +2 -2
  133. package/dist/cli/chunks/{chunk-JNQN5DNS.js → chunk-RMFRFING.js} +1 -1
  134. package/dist/cli/chunks/{chunk-4YT5YN5G.js → chunk-RQN4HWGV.js} +2 -2
  135. package/dist/cli/chunks/{chunk-5P7Q5YNC.js → chunk-RYUSZ43T.js} +1 -1
  136. package/dist/cli/chunks/{chunk-O5NEJIHB.js → chunk-RZDNCTOA.js} +2 -2
  137. package/dist/cli/chunks/chunk-SCMXIBI7.js +2 -0
  138. package/dist/cli/chunks/{chunk-6545AS2J.js → chunk-SPEUF7ZL.js} +2 -2
  139. package/dist/cli/chunks/{chunk-LW5DHT3Z.js → chunk-SSXAW3ER.js} +2 -2
  140. package/dist/cli/chunks/{chunk-Q7ORVHJB.js → chunk-TC2JE5OK.js} +3 -3
  141. package/dist/cli/chunks/{chunk-MALOUGSF.js → chunk-TED4KOSK.js} +2 -2
  142. package/dist/cli/chunks/{chunk-ICCTQ5LO.js → chunk-TJ6N4CCX.js} +2 -2
  143. package/dist/cli/chunks/{chunk-6GYGAW53.js → chunk-TJEJ4UVX.js} +2 -2
  144. package/dist/cli/chunks/{chunk-VO6YJGB4.js → chunk-TO5PQSDD.js} +2 -2
  145. package/dist/cli/chunks/{chunk-LKURMUBU.js → chunk-TR5GOGH3.js} +37 -12
  146. package/dist/cli/chunks/{chunk-JCTCM6IR.js → chunk-UGJQJSPB.js} +1 -1
  147. package/dist/cli/chunks/{chunk-4RHNPRAP.js → chunk-USB44IHJ.js} +2 -2
  148. package/dist/cli/chunks/{chunk-JDFPAJGB.js → chunk-UUOXV3NS.js} +92 -92
  149. package/dist/cli/chunks/chunk-UVVKFBF7.js +2 -0
  150. package/dist/cli/chunks/{chunk-VCUCD3B5.js → chunk-V2MD5EDD.js} +2 -2
  151. package/dist/cli/chunks/{chunk-RFQBDMAP.js → chunk-VA7TEOPM.js} +1 -1
  152. package/dist/cli/chunks/{chunk-IF3HPQNV.js → chunk-VMP4M5PB.js} +1 -1
  153. package/dist/cli/chunks/{chunk-KUZMVH6N.js → chunk-VS4GMNJK.js} +3 -3
  154. package/dist/cli/chunks/{chunk-ZYZT2CDX.js → chunk-VWJSWXHG.js} +1 -1
  155. package/dist/cli/chunks/{chunk-54B6P2WS.js → chunk-VZ67ZDB3.js} +3 -3
  156. package/dist/cli/chunks/{chunk-NSPCZPTB.js → chunk-W2OMW6UU.js} +2 -2
  157. package/dist/cli/chunks/{chunk-3SKIZDKL.js → chunk-W766S4SK.js} +1 -1
  158. package/dist/cli/chunks/{chunk-N2BJN6AO.js → chunk-WJYTLRA5.js} +3 -3
  159. package/dist/cli/chunks/{chunk-X64BEXUY.js → chunk-WNASEUBW.js} +117 -113
  160. package/dist/cli/chunks/{chunk-HT6WAYIR.js → chunk-WT4ZDDFM.js} +1 -1
  161. package/dist/cli/chunks/chunk-XEYW3V5I.js +2 -0
  162. package/dist/cli/chunks/{chunk-6W3QHS45.js → chunk-XIFPIVZI.js} +2 -2
  163. package/dist/cli/chunks/{chunk-3E7D3A35.js → chunk-Y2MCIIJD.js} +1 -1
  164. package/dist/cli/chunks/{chunk-YUHM72VQ.js → chunk-YKOTOCO6.js} +2 -2
  165. package/dist/cli/chunks/{chunk-YKSWC7I4.js → chunk-Z3W3R4CW.js} +8 -20
  166. package/dist/cli/chunks/chunk-ZT2WHCVM.js +2 -0
  167. package/dist/cli/chunks/{chunk-G3TFNY4T.js → chunk-ZVPAFX4I.js} +2 -2
  168. package/dist/cli/chunks/{chunk-NFJT7XXR.js → chunk-ZWC6CM4R.js} +1 -1
  169. package/dist/cli/chunks/{ci-HQCRSCC7.js → ci-RJH5LAL3.js} +2 -2
  170. package/dist/cli/chunks/{ci-output-YBVXLA6O.js → ci-output-62SGMGB2.js} +2 -2
  171. package/dist/cli/chunks/{circuit-breaker-ULGMF2QN.js → circuit-breaker-QXTS5ZAW.js} +2 -2
  172. package/dist/cli/chunks/{claude-flow-setup-MKZ2LJXK.js → claude-flow-setup-BBCCT5WV.js} +2 -2
  173. package/dist/cli/chunks/client-E2XUBCLK.js +2 -0
  174. package/dist/cli/chunks/{cline-installer-WZQ6XBWN.js → cline-installer-IZCUJJ3I.js} +2 -2
  175. package/dist/cli/chunks/{code-H3KGH45S.js → code-AWNVOZ7S.js} +2 -2
  176. package/dist/cli/chunks/{code-index-extractor-NUVEAJ7C.js → code-index-extractor-MX65BKMI.js} +2 -2
  177. package/dist/cli/chunks/{codex-installer-JQI6E6CV.js → codex-installer-EQT6JVLM.js} +2 -2
  178. package/dist/cli/chunks/{completions-NDF4PFE7.js → completions-WOJAM45W.js} +2 -2
  179. package/dist/cli/chunks/{complexity-analyzer-XCZH66HG.js → complexity-analyzer-3DJB7V3K.js} +2 -2
  180. package/dist/cli/chunks/{continuedev-installer-Z4AJGZ7S.js → continuedev-installer-P4KWUTCJ.js} +2 -2
  181. package/dist/cli/chunks/{copilot-installer-K4IPAL7C.js → copilot-installer-FFZWTMWQ.js} +2 -2
  182. package/dist/cli/chunks/core-handlers-46Z5VOO6.js +2 -0
  183. package/dist/cli/chunks/{cost-tracker-35KXAB23.js → cost-tracker-CYBOV3NI.js} +2 -2
  184. package/dist/cli/chunks/{coverage-QW5I4TYZ.js → coverage-GTZJBSC4.js} +3 -3
  185. package/dist/cli/chunks/cross-domain-router-SXQ3HFRY.js +2 -0
  186. package/dist/cli/chunks/{cursor-installer-P4Z7RMIZ.js → cursor-installer-WZIVXGGB.js} +2 -2
  187. package/dist/cli/chunks/daemon-JWMHEJEN.js +10 -0
  188. package/dist/cli/chunks/{daemon-WQWTCYBM.js → daemon-MSFN2LXY.js} +3 -3
  189. package/dist/cli/chunks/{dag-attention-scheduler-7XD2VGON.js → dag-attention-scheduler-4TWOTTQE.js} +2 -2
  190. package/dist/cli/chunks/{detect-GZ3P4DI7.js → detect-YZ6AGQPB.js} +2 -2
  191. package/dist/cli/chunks/{dist-node-6WWAW7OP.js → dist-node-3EM2XH54.js} +2 -2
  192. package/dist/cli/chunks/{domain-handler-3GTLWARQ.js → domain-handler-4XU5BINU.js} +2 -2
  193. package/dist/cli/chunks/domain-transfer-HUFC7I52.js +2 -0
  194. package/dist/cli/chunks/dream-R6MQQQ3N.js +2 -0
  195. package/dist/cli/chunks/{embed-and-insert-pattern-BGIMA77V.js → embed-and-insert-pattern-J5ZFM6YX.js} +2 -2
  196. package/dist/cli/chunks/{eval-SXV6DRDD.js → eval-XYOA3EH2.js} +2 -2
  197. package/dist/cli/chunks/{experience-capture-middleware-TT6WCT2S.js → experience-capture-middleware-E3RYQB6Z.js} +3 -3
  198. package/dist/cli/chunks/{fast-paths-HTAZHEQP.js → fast-paths-DKIYN2YS.js} +2 -2
  199. package/dist/cli/chunks/{feature-flags-DIE3Z2B4.js → feature-flags-S2RNZATS.js} +2 -2
  200. package/dist/cli/chunks/{feature-flags-WBUKU54W.js → feature-flags-ZB63Z7N5.js} +2 -2
  201. package/dist/cli/chunks/{file-discovery-SKDETFS3.js → file-discovery-USJJLYQU.js} +2 -2
  202. package/dist/cli/chunks/{fleet-WCWEPAVU.js → fleet-4MUPHSF5.js} +4 -4
  203. package/dist/cli/chunks/{gnn-wrapper-KWZOWBYS.js → gnn-wrapper-PYOQZKX6.js} +2 -2
  204. package/dist/cli/chunks/{heartbeat-handler-3AGYHVG2.js → heartbeat-handler-HLO5XCG7.js} +4 -4
  205. package/dist/cli/chunks/heartbeat-scheduler-OSDPJT6A.js +2 -0
  206. package/dist/cli/chunks/hnsw-adapter-KMGSHBIN.js +2 -0
  207. package/dist/cli/chunks/hnsw-index-IMFRAOPE.js +2 -0
  208. package/dist/cli/chunks/{hnsw-legacy-bridge-6OJJDZHL.js → hnsw-legacy-bridge-FZEH2KLM.js} +2 -2
  209. package/dist/cli/chunks/{better-sqlite3-URULPKRF.js → hnswlib-node-VS6L5VUG.js} +2 -2
  210. package/dist/cli/chunks/{hooks-OXEBTLXV.js → hooks-R2757K57.js} +48 -52
  211. package/dist/cli/chunks/hybrid-router-57QSWSWC.js +2 -0
  212. package/dist/cli/chunks/{hypergraph-engine-NL74PRHD.js → hypergraph-engine-EAV3GJ5D.js} +2 -2
  213. package/dist/cli/chunks/{hypergraph-handler-KZ54AEEL.js → hypergraph-handler-5ERXAVGH.js} +3 -3
  214. package/dist/cli/chunks/impact-analyzer-OC4MPBGA.js +2 -0
  215. package/dist/cli/chunks/{init-handler-XKZXRXPG.js → init-handler-RXUSEMG7.js} +6 -6
  216. package/dist/cli/chunks/init-wizard-CDBRL4PO.js +2 -0
  217. package/dist/cli/chunks/kernel-CQ7R3AAV.js +2 -0
  218. package/dist/cli/chunks/{kilocode-installer-WISQMJK7.js → kilocode-installer-ZUBVBHGT.js} +2 -2
  219. package/dist/cli/chunks/{kiro-installer-O7TBB3GM.js → kiro-installer-TRTRQDGL.js} +2 -2
  220. package/dist/cli/chunks/knowledge-graph-UXNH7RY4.js +2 -0
  221. package/dist/cli/chunks/{learning-6IZBGVRU.js → learning-UYXWAU5D.js} +3 -3
  222. package/dist/cli/chunks/{llm-router-QDMQPPQ7.js → llm-router-TB5OJPEV.js} +4 -4
  223. package/dist/cli/chunks/llm-router-service-UV34YXBE.js +2 -0
  224. package/dist/cli/chunks/{load-KLAJJGL5.js → load-ELPSUIPV.js} +2 -2
  225. package/dist/cli/chunks/load-test-2VEN3PQZ.js +2 -0
  226. package/dist/cli/chunks/{mcp-SZOPQZIZ.js → mcp-UX7TK3XV.js} +2 -2
  227. package/dist/cli/chunks/{memory-G3WY74C6.js → memory-W3LG6H6N.js} +5 -5
  228. package/dist/cli/chunks/memory-backend-TZL5U6F3.js +2 -0
  229. package/dist/cli/chunks/memory-handlers-BNXAYS2P.js +2 -0
  230. package/dist/cli/chunks/{multi-model-executor-TDNQGTOT.js → multi-model-executor-227LWZRY.js} +2 -2
  231. package/dist/cli/chunks/{opencode-installer-NGYGEDMV.js → opencode-installer-F4WKVWDL.js} +2 -2
  232. package/dist/cli/chunks/{orchestrator-KPI5DY2C.js → orchestrator-V4DBMGK6.js} +5 -5
  233. package/dist/cli/chunks/pattern-null-store-KLX2RNHM.js +2 -0
  234. package/dist/cli/chunks/pattern-usage-recorder-BY3HEWSU.js +2 -0
  235. package/dist/cli/chunks/{pipeline-CSDCC675.js → pipeline-3F5RIESX.js} +2 -2
  236. package/dist/cli/chunks/{platform-Q5XKEVKH.js → platform-KCGXTZO3.js} +2 -2
  237. package/dist/cli/chunks/{plugin-XKKR3GVL.js → plugin-2H552KOV.js} +2 -2
  238. package/dist/cli/chunks/{prime-radiant-advanced-wasm-22QVNKEN.js → prime-radiant-advanced-wasm-EFKVL7VN.js} +2 -2
  239. package/dist/cli/chunks/protocol-executor-5HJKW6MC.js +2 -0
  240. package/dist/cli/chunks/{protocol-handler-REQKTJGG.js → protocol-handler-ELGYV7D2.js} +2 -2
  241. package/dist/cli/chunks/{prove-NOFUFSQN.js → prove-AYJCQYNI.js} +2 -2
  242. package/dist/cli/chunks/provider-manager-TRZSBXD3.js +2 -0
  243. package/dist/cli/chunks/qe-reasoning-bank-RCEYSLVV.js +2 -0
  244. package/dist/cli/chunks/{quality-3DQ2H5TK.js → quality-HH7L5A7V.js} +2 -2
  245. package/dist/cli/chunks/quality-gate-NAQLXE4C.js +7 -0
  246. package/dist/cli/chunks/queen-coordinator-6JFZD54W.js +2 -0
  247. package/dist/cli/chunks/{real-embeddings-FCGNYWLL.js → real-embeddings-IO3F4ZFR.js} +2 -2
  248. package/dist/cli/chunks/{roocode-installer-HX3CNRIR.js → roocode-installer-X4TU5HO4.js} +2 -2
  249. package/dist/cli/chunks/router-KRLC46NS.js +2 -0
  250. package/dist/cli/chunks/routing-feedback-WW26H6SA.js +2 -0
  251. package/dist/cli/chunks/{routing-handler-YRZ2LDCR.js → routing-handler-ZJKGDDMT.js} +2 -2
  252. package/dist/cli/chunks/{ruvector-commands-GCQVBJ4E.js → ruvector-commands-NXCSUBN2.js} +2 -2
  253. package/dist/cli/chunks/{rvf-dual-writer-B562P3ZC.js → rvf-dual-writer-JMA74SKP.js} +2 -2
  254. package/dist/cli/chunks/{rvf-migration-adapter-NAGFKCMD.js → rvf-migration-adapter-BNTGH2KU.js} +2 -2
  255. package/dist/cli/chunks/{rvf-migration-coordinator-WWFBEJ5Q.js → rvf-migration-coordinator-7T2HHUOH.js} +2 -2
  256. package/dist/cli/chunks/rvf-native-adapter-OVQKPQUH.js +2 -0
  257. package/dist/cli/chunks/safe-db-UQOCQIH2.js +2 -0
  258. package/dist/cli/chunks/schedule-EUX7ZQUK.js +2 -0
  259. package/dist/cli/chunks/scheduler-MALHQKNR.js +2 -0
  260. package/dist/cli/chunks/{security-IFOYTD75.js → security-XSK2QHB3.js} +3 -3
  261. package/dist/cli/chunks/{shared-rvf-adapter-TYD5TQ35.js → shared-rvf-adapter-WLRKI7RY.js} +2 -2
  262. package/dist/cli/chunks/{shared-rvf-dual-writer-YGOOVDQZ.js → shared-rvf-dual-writer-SZW3J7ZK.js} +2 -2
  263. package/dist/cli/chunks/sqlite-persistence-OBCLRP4L.js +2 -0
  264. package/dist/cli/chunks/status-handler-HGCKYJX2.js +46 -0
  265. package/dist/cli/chunks/{structural-health-KZI6YMKV.js → structural-health-4SJCFX63.js} +2 -2
  266. package/dist/cli/chunks/{sync-Z5BDDBMK.js → sync-7WAVNZGL.js} +2 -2
  267. package/dist/cli/chunks/{sync-ABZNNYRC.js → sync-ATR4DUSA.js} +2 -2
  268. package/dist/cli/chunks/{task-handler-5ACZEPJ7.js → task-handler-O6REL34Y.js} +2 -2
  269. package/dist/cli/chunks/{task-handlers-UZWDPL6A.js → task-handlers-WFV2ZYWW.js} +3 -3
  270. package/dist/cli/chunks/{test-APO3MCVV.js → test-4LXUVHEU.js} +4 -4
  271. package/dist/cli/chunks/{test-scheduling-EFZA5G5C.js → test-scheduling-OTN3DMKY.js} +3 -3
  272. package/dist/cli/chunks/{token-bootstrap-J2OPLNUK.js → token-bootstrap-VA7T4P42.js} +2 -2
  273. package/dist/cli/chunks/{token-usage-VHWVNN4R.js → token-usage-TLT6OXXR.js} +2 -2
  274. package/dist/cli/chunks/{transformers-PX4HPO75.js → transformers-JI7LZRQ3.js} +2 -2
  275. package/dist/cli/chunks/{tree-sitter-wasm-parser-44HA2Z3F.js → tree-sitter-wasm-parser-QNIMHB4K.js} +2 -2
  276. package/dist/cli/chunks/{types-IMOP7F4R.js → types-DJNWOAC6.js} +2 -2
  277. package/dist/cli/chunks/unified-memory-A5BS3LGX.js +2 -0
  278. package/dist/cli/chunks/unified-memory-hnsw-WJLJO5MY.js +2 -0
  279. package/dist/cli/chunks/unified-persistence-CFC2BKI5.js +2 -0
  280. package/dist/cli/chunks/{upgrade-OZ3O6ZZI.js → upgrade-VEW4FL23.js} +2 -2
  281. package/dist/cli/chunks/{validate-DRY5BMWX.js → validate-O3P6PF7B.js} +2 -2
  282. package/dist/cli/chunks/{validate-swarm-QD3LYPUF.js → validate-swarm-M2HXHZVC.js} +2 -2
  283. package/dist/cli/chunks/{vibium-2J3H2ITD.js → vibium-GOU55LUO.js} +2 -2
  284. package/dist/cli/chunks/visual-security-VPB6KVYJ.js +2 -0
  285. package/dist/cli/chunks/{web-tree-sitter-KRNUOGKI.js → web-tree-sitter-MXOI4GH3.js} +2 -2
  286. package/dist/cli/chunks/{windsurf-installer-PQIPH3WP.js → windsurf-installer-6GKT53IH.js} +2 -2
  287. package/dist/cli/chunks/{witness-chain-HPLOYPS7.js → witness-chain-OXGQGL26.js} +2 -2
  288. package/dist/cli/chunks/witness-chain-ZZAUAXDY.js +2 -0
  289. package/dist/cli/chunks/witness-key-manager-PGFSQXUJ.js +2 -0
  290. package/dist/cli/chunks/{workflow-OAQ3FWCY.js → workflow-ENBWRMBA.js} +4 -4
  291. package/dist/cli/chunks/workflow-orchestrator-S4LBFTYD.js +2 -0
  292. package/dist/cli/chunks/{wrappers-UPIU6S5S.js → wrappers-MHLNYANQ.js} +2 -2
  293. package/dist/cli/commands/audit.d.ts +12 -0
  294. package/dist/cli/commands/audit.js +64 -4
  295. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +45 -19
  296. package/dist/cli/commands/hooks-handlers/hooks-shared.d.ts +13 -0
  297. package/dist/cli/commands/hooks-handlers/hooks-shared.js +38 -0
  298. package/dist/cli/commands/hooks-handlers/task-hooks.js +19 -1
  299. package/dist/cli/commands/quality-gate.d.ts +24 -0
  300. package/dist/cli/commands/quality-gate.js +135 -0
  301. package/dist/cli/handlers/status-handler.d.ts +18 -0
  302. package/dist/cli/handlers/status-handler.js +47 -0
  303. package/dist/cli/index.js +5 -0
  304. package/dist/coordination/mincut/dream-integration.d.ts +11 -0
  305. package/dist/coordination/mincut/dream-integration.js +39 -12
  306. package/dist/coordination/mincut/queen-integration.js +24 -7
  307. package/dist/coordination/protocol-executor.js +2 -1
  308. package/dist/coordination/queen-lifecycle.js +4 -1
  309. package/dist/domains/code-intelligence/coordinator.js +10 -6
  310. package/dist/domains/code-intelligence/services/product-factors-bridge.js +3 -1
  311. package/dist/domains/defect-intelligence/services/defect-predictor.d.ts +6 -0
  312. package/dist/domains/defect-intelligence/services/defect-predictor.js +21 -0
  313. package/dist/domains/learning-optimization/interfaces.d.ts +7 -0
  314. package/dist/domains/learning-optimization/plugin.js +5 -0
  315. package/dist/domains/learning-optimization/services/learning-coordinator.d.ts +10 -0
  316. package/dist/domains/learning-optimization/services/learning-coordinator.js +57 -0
  317. package/dist/domains/test-execution/plugin.js +2 -2
  318. package/dist/domains/test-execution/services/flaky-detector.js +1 -1
  319. package/dist/domains/test-generation/coordinator.js +22 -8
  320. package/dist/domains/test-generation/interfaces.d.ts +3 -0
  321. package/dist/domains/test-generation/services/test-generator.js +9 -1
  322. package/dist/integrations/ruvector/delta-tracker.js +10 -1
  323. package/dist/integrations/ruvector/feature-flags.js +7 -0
  324. package/dist/integrations/ruvector/sona-persistence.d.ts +24 -0
  325. package/dist/integrations/ruvector/sona-persistence.js +76 -0
  326. package/dist/integrations/ruvector/sona-three-loop.d.ts +15 -0
  327. package/dist/integrations/ruvector/sona-three-loop.js +17 -0
  328. package/dist/kernel/unified-memory-schemas.d.ts +2 -2
  329. package/dist/kernel/unified-memory-schemas.js +48 -2
  330. package/dist/kernel/unified-memory.d.ts +22 -0
  331. package/dist/kernel/unified-memory.js +43 -0
  332. package/dist/learning/aqe-learning-engine.js +3 -1
  333. package/dist/learning/dream/concept-graph.d.ts +31 -1
  334. package/dist/learning/dream/concept-graph.js +109 -3
  335. package/dist/learning/dream/dream-engine.d.ts +13 -1
  336. package/dist/learning/dream/dream-engine.js +146 -10
  337. package/dist/learning/dream/index.d.ts +1 -1
  338. package/dist/learning/dream/types.d.ts +23 -0
  339. package/dist/learning/pattern-lifecycle.d.ts +16 -0
  340. package/dist/learning/pattern-lifecycle.js +77 -1
  341. package/dist/learning/pattern-store.d.ts +2 -2
  342. package/dist/learning/pattern-store.js +14 -3
  343. package/dist/learning/provenance-tier.d.ts +52 -0
  344. package/dist/learning/provenance-tier.js +64 -0
  345. package/dist/learning/qe-flywheel/corpus-scorer.d.ts +55 -0
  346. package/dist/learning/qe-flywheel/corpus-scorer.js +293 -0
  347. package/dist/learning/qe-flywheel/coupled-anchor.d.ts +91 -0
  348. package/dist/learning/qe-flywheel/coupled-anchor.js +181 -0
  349. package/dist/learning/qe-flywheel/generation.d.ts +121 -0
  350. package/dist/learning/qe-flywheel/generation.js +167 -0
  351. package/dist/learning/qe-flywheel/policy.d.ts +37 -0
  352. package/dist/learning/qe-flywheel/policy.js +66 -0
  353. package/dist/learning/qe-flywheel/receipt-store.d.ts +31 -0
  354. package/dist/learning/qe-flywheel/receipt-store.js +89 -0
  355. package/dist/learning/qe-flywheel/receipt.d.ts +62 -0
  356. package/dist/learning/qe-flywheel/receipt.js +97 -0
  357. package/dist/learning/qe-reasoning-bank.js +34 -31
  358. package/dist/learning/routing-topology-gate.d.ts +12 -2
  359. package/dist/learning/routing-topology-gate.js +15 -3
  360. package/dist/learning/rvf-pattern-store.d.ts +1 -1
  361. package/dist/learning/rvf-pattern-store.js +21 -8
  362. package/dist/learning/sqlite-persistence.js +12 -9
  363. package/dist/mcp/bundle.js +540 -460
  364. package/dist/mcp/qe-tool-bridge.js +7 -2
  365. package/dist/mcp/tools/base.d.ts +29 -0
  366. package/dist/mcp/tools/base.js +25 -0
  367. package/dist/mcp/tools/coverage-analysis/index.js +6 -4
  368. package/dist/mcp/tools/learning-optimization/dream.d.ts +4 -13
  369. package/dist/mcp/tools/learning-optimization/dream.js +10 -96
  370. package/dist/mcp/tools/planning/goap-execute.d.ts +13 -1
  371. package/dist/mcp/tools/planning/goap-execute.js +33 -18
  372. package/dist/mcp/tools/quality-assessment/gate.d.ts +38 -0
  373. package/dist/mcp/tools/quality-assessment/gate.js +86 -0
  374. package/dist/mcp/tools/registry.d.ts +1 -0
  375. package/dist/mcp/tools/registry.js +10 -2
  376. package/dist/persistence/rvf-migration-coordinator.js +2 -1
  377. package/dist/planning/actions/qe-action-library.js +124 -1
  378. package/dist/planning/goap-planner.d.ts +14 -2
  379. package/dist/planning/goap-planner.js +51 -9
  380. package/dist/planning/index.d.ts +1 -1
  381. package/dist/planning/plan-executor.d.ts +84 -4
  382. package/dist/planning/plan-executor.js +221 -56
  383. package/dist/planning/types.d.ts +27 -0
  384. package/dist/shared/events/domain-events.d.ts +2 -0
  385. package/dist/shared/safe-db.js +23 -4
  386. package/dist/validation/anchor-set.d.ts +74 -0
  387. package/dist/validation/anchor-set.js +78 -0
  388. package/dist/validation/frontier-judge.d.ts +99 -0
  389. package/dist/validation/frontier-judge.js +234 -0
  390. package/dist/validation/gate-reexecute.d.ts +165 -0
  391. package/dist/validation/gate-reexecute.js +255 -0
  392. package/dist/validation/quality-gate-runner.d.ts +49 -0
  393. package/dist/validation/quality-gate-runner.js +62 -0
  394. package/dist/validation/quality-verdict.d.ts +94 -0
  395. package/dist/validation/quality-verdict.js +120 -0
  396. package/dist/workers/workers/learning-consolidation.js +21 -1
  397. package/package.json +1 -1
  398. package/dist/cli/chunks/adapter-2HMUXHWY.js +0 -2
  399. package/dist/cli/chunks/aqe-learning-engine-M2NKRVRE.js +0 -2
  400. package/dist/cli/chunks/audit-EPB7ETMT.js +0 -3
  401. package/dist/cli/chunks/base-CCHC2DAC.js +0 -2
  402. package/dist/cli/chunks/brain-handler-FBMYEERK.js +0 -89
  403. package/dist/cli/chunks/browser-workflow-4DGHFYY3.js +0 -2
  404. package/dist/cli/chunks/chunk-37ZDGJ3H.js +0 -2
  405. package/dist/cli/chunks/chunk-5AQ7FXYG.js +0 -27
  406. package/dist/cli/chunks/chunk-KYTFIP6R.js +0 -2
  407. package/dist/cli/chunks/chunk-MYMIEQSZ.js +0 -65
  408. package/dist/cli/chunks/chunk-RCPD6F4R.js +0 -2
  409. package/dist/cli/chunks/chunk-TCWR6TDN.js +0 -2
  410. package/dist/cli/chunks/chunk-UQ72K44T.js +0 -149
  411. package/dist/cli/chunks/chunk-XXRTWG7O.js +0 -2
  412. package/dist/cli/chunks/chunk-ZSA6V5FH.js +0 -2
  413. package/dist/cli/chunks/client-2OVEDWGU.js +0 -2
  414. package/dist/cli/chunks/core-handlers-UXRRYP52.js +0 -2
  415. package/dist/cli/chunks/cross-domain-router-PV3VQVLO.js +0 -2
  416. package/dist/cli/chunks/daemon-ESUEM6VB.js +0 -10
  417. package/dist/cli/chunks/domain-transfer-TQYO3SVG.js +0 -2
  418. package/dist/cli/chunks/dream-UFUXVJQC.js +0 -2
  419. package/dist/cli/chunks/heartbeat-scheduler-MBG3SARO.js +0 -2
  420. package/dist/cli/chunks/hnsw-adapter-5HXA3QB3.js +0 -2
  421. package/dist/cli/chunks/hnsw-index-PZRQWBRG.js +0 -2
  422. package/dist/cli/chunks/hybrid-router-NQRIE2GG.js +0 -2
  423. package/dist/cli/chunks/impact-analyzer-46347ZDV.js +0 -2
  424. package/dist/cli/chunks/init-wizard-CJYP4WKO.js +0 -2
  425. package/dist/cli/chunks/kernel-22KQZ56U.js +0 -2
  426. package/dist/cli/chunks/knowledge-graph-KM3JDBGR.js +0 -2
  427. package/dist/cli/chunks/llm-router-service-IFO6GRRO.js +0 -2
  428. package/dist/cli/chunks/load-test-TTKCYAPB.js +0 -2
  429. package/dist/cli/chunks/memory-backend-ELHCX2ZT.js +0 -2
  430. package/dist/cli/chunks/memory-handlers-3SKYQZTL.js +0 -2
  431. package/dist/cli/chunks/pattern-null-store-TMXAYD43.js +0 -2
  432. package/dist/cli/chunks/protocol-executor-BPLR5EJC.js +0 -2
  433. package/dist/cli/chunks/provider-manager-4MMD5QKL.js +0 -2
  434. package/dist/cli/chunks/qe-reasoning-bank-P7KNT3WZ.js +0 -2
  435. package/dist/cli/chunks/queen-coordinator-NBZZ4MGC.js +0 -2
  436. package/dist/cli/chunks/router-2RXR6J2Q.js +0 -2
  437. package/dist/cli/chunks/routing-feedback-AVAA76TK.js +0 -2
  438. package/dist/cli/chunks/rvf-native-adapter-X2YDJA55.js +0 -2
  439. package/dist/cli/chunks/safe-db-4PRU65BK.js +0 -2
  440. package/dist/cli/chunks/schedule-2AST5CHW.js +0 -2
  441. package/dist/cli/chunks/scheduler-SW6II7OU.js +0 -2
  442. package/dist/cli/chunks/sqlite-persistence-OB5NEGAK.js +0 -2
  443. package/dist/cli/chunks/status-handler-HFPWSCBY.js +0 -45
  444. package/dist/cli/chunks/unified-memory-X7OJYGSD.js +0 -2
  445. package/dist/cli/chunks/unified-memory-hnsw-O6HOD5YL.js +0 -2
  446. package/dist/cli/chunks/unified-persistence-C332CER2.js +0 -2
  447. package/dist/cli/chunks/visual-security-MPUG5HPI.js +0 -2
  448. package/dist/cli/chunks/witness-chain-Q4BZHPDF.js +0 -2
  449. package/dist/cli/chunks/workflow-orchestrator-4NDWECYK.js +0 -2
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.4");process.exit(0)}
2
- import{e as a}from"./chunk-ARPBG6FQ.js";import{b as w,d as y}from"./chunk-VJGHRWMH.js";import{a as f,c as P}from"./chunk-PEIQDQXN.js";import{randomUUID as v}from"crypto";import*as i from"fs";import*as n from"path";import*as c from"os";y();P();var k=".aqe",b="schedules.json",F="1.0.0",g=5e3,x=50,p=10*1024*1024,d=class{schedulesPath;debug;lockFile;initialized=!1;constructor(e={}){e.schedulesPath&&this.validateSchedulesPath(e.schedulesPath),this.schedulesPath=e.schedulesPath??this.getDefaultSchedulesPath(),this.lockFile=`${this.schedulesPath}.lock`,this.debug=e.debug??!1}validateSchedulesPath(e){let s=c.homedir(),t=n.resolve(e),r=n.resolve(s);if(t.startsWith(r+n.sep)||t===r)return;let l=process.cwd(),h=n.resolve(l);if(t.startsWith(h+n.sep)||t===h)return;let u=c.tmpdir(),S=n.resolve(u);if(!(t.startsWith(S+n.sep)||t===S))throw new Error(`Security: Custom schedulesPath must be within home directory (${s}), current working directory (${l}), or temp directory (${u}). Provided path: ${e}`)}getDefaultSchedulesPath(){let e=c.homedir();return n.join(e,k,b)}async initialize(){if(this.initialized)return;let e=n.dirname(this.schedulesPath);i.existsSync(e)||(i.mkdirSync(e,{recursive:!0}),this.log(`Created directory: ${e}`)),this.initialized=!0}async loadSchedules(){if(await this.initialize(),!i.existsSync(this.schedulesPath))return this.log("Schedules file does not exist, returning empty array"),[];try{let e=i.readFileSync(this.schedulesPath,"utf-8"),s=this.parseSchedulesFile(e);return this.log(`Loaded ${s.schedules.length} schedules`),s.schedules}catch(e){return await this.handleCorruptFile(e),[]}}async saveSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.findIndex(r=>r.id===e.id);t>=0?(s[t]=e,this.log(`Updated schedule: ${e.id}`)):(s.push(e),this.log(`Added schedule: ${e.id}`)),await this.writeSchedules(s)})}async removeSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.filter(r=>r.id!==e);if(t.length===s.length){this.log(`Schedule not found: ${e}`);return}await this.writeSchedules(t),this.log(`Removed schedule: ${e}`)})}async getSchedules(){return this.loadSchedules()}async getSchedule(e){return(await this.loadSchedules()).find(t=>t.id===e)}async getDueSchedules(){let e=await this.loadSchedules(),s=new Date;return e.filter(t=>t.enabled?new Date(t.nextRun)<=s:!1)}async markExecuted(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.find(l=>l.id===e);if(!t)throw new Error(`Schedule not found: ${e}`);let r=new Date;t.lastRun=r.toISOString(),t.nextRun=a(t.schedule,r).toISOString(),await this.writeSchedules(s),this.log(`Marked executed: ${e}, next run: ${t.nextRun}`)})}async setEnabled(e,s){await this.initialize(),await this.withFileLock(async()=>{let t=await this.loadSchedulesUnsafe(),r=t.find(l=>l.id===e);if(!r)throw new Error(`Schedule not found: ${e}`);r.enabled=s,s&&(r.nextRun=a(r.schedule,new Date).toISOString()),await this.writeSchedules(t),this.log(`Set enabled=${s}: ${e}`)})}async getEnabledSchedules(){return(await this.loadSchedules()).filter(s=>s.enabled)}async getSchedulesByWorkflow(e){return(await this.loadSchedules()).filter(t=>t.workflowId===e)}async clearAll(){await this.initialize(),await this.withFileLock(async()=>{await this.writeSchedules([]),this.log("Cleared all schedules")})}async getStats(){let e=await this.loadSchedules(),s=new Date;return{total:e.length,enabled:e.filter(t=>t.enabled).length,disabled:e.filter(t=>!t.enabled).length,due:e.filter(t=>t.enabled&&new Date(t.nextRun)<=s).length}}async loadSchedulesUnsafe(){if(!i.existsSync(this.schedulesPath))return[];try{let e=i.readFileSync(this.schedulesPath,"utf-8");return this.parseSchedulesFile(e).schedules}catch{return[]}}parseSchedulesFile(e){let s=Buffer.byteLength(e,"utf-8");if(s>p)throw new Error(`Schedules file exceeds maximum allowed size (${p/(1024*1024)}MB). File is ${(s/(1024*1024)).toFixed(2)}MB.`);let t=w(e);if(!t.schedules||!Array.isArray(t.schedules))throw new Error("Invalid schedules file: missing schedules array");for(let r of t.schedules)if(!r.id||!r.workflowId||!r.schedule)throw new Error("Invalid schedule entry: missing required fields");return t}async writeSchedules(e){let s={version:F,updatedAt:new Date().toISOString(),schedules:e},t=JSON.stringify(s,null,2);i.writeFileSync(this.schedulesPath,t,"utf-8"),this.log(`Wrote ${e.length} schedules to disk`)}async handleCorruptFile(e){let s=f(e);this.log(`Corrupt schedules file detected: ${s}`);let t=`${this.schedulesPath}.corrupt.${Date.now()}`;try{i.existsSync(this.schedulesPath)&&(i.copyFileSync(this.schedulesPath,t),this.log(`Backed up corrupt file to: ${t}`))}catch(r){this.log(`Failed to backup corrupt file: ${r}`)}try{i.existsSync(this.schedulesPath)&&(i.unlinkSync(this.schedulesPath),this.log("Removed corrupt schedules file"))}catch(r){this.log(`Failed to remove corrupt file: ${r}`)}}async withFileLock(e){await this.acquireLock();try{return await e()}finally{this.releaseLock()}}async acquireLock(){let e=Date.now();for(;i.existsSync(this.lockFile);){try{let s=i.statSync(this.lockFile);if(Date.now()-s.mtimeMs>g){i.unlinkSync(this.lockFile),this.log("Removed stale lock file");break}}catch{break}if(Date.now()-e>g)throw new Error("Timeout waiting for scheduler lock");await this.sleep(x)}try{i.writeFileSync(this.lockFile,`${process.pid}:${Date.now()}`,{flag:"wx"})}catch(s){if(s.code==="EEXIST")return this.acquireLock();throw s}}releaseLock(){try{i.existsSync(this.lockFile)&&i.unlinkSync(this.lockFile)}catch(e){console.debug("[PersistentScheduler] Lock release error:",e instanceof Error?e.message:e)}}sleep(e){return new Promise(s=>setTimeout(s,e))}log(e){this.debug&&console.log(`[PersistentScheduler] ${e}`)}};function E(o={}){return new d(o)}function m(){let o=Date.now().toString(36),e=v().slice(0,8);return`sched-${o}-${e}`}function $(o){let e=new Date;return{id:m(),workflowId:o.workflowId,pipelinePath:o.pipelinePath,schedule:o.schedule,scheduleDescription:o.scheduleDescription,nextRun:a(o.schedule,e).toISOString(),enabled:o.enabled??!0,createdAt:e.toISOString()}}export{d as a,E as b,m as c,$ as d};
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.12.0");process.exit(0)}
2
+ import{e as a}from"./chunk-JYX7AZHE.js";import{b as w,d as y}from"./chunk-K5SN66B4.js";import{a as f,c as P}from"./chunk-RHC7TFPU.js";import{randomUUID as v}from"crypto";import*as i from"fs";import*as n from"path";import*as c from"os";y();P();var k=".aqe",b="schedules.json",F="1.0.0",g=5e3,x=50,p=10*1024*1024,d=class{schedulesPath;debug;lockFile;initialized=!1;constructor(e={}){e.schedulesPath&&this.validateSchedulesPath(e.schedulesPath),this.schedulesPath=e.schedulesPath??this.getDefaultSchedulesPath(),this.lockFile=`${this.schedulesPath}.lock`,this.debug=e.debug??!1}validateSchedulesPath(e){let s=c.homedir(),t=n.resolve(e),r=n.resolve(s);if(t.startsWith(r+n.sep)||t===r)return;let l=process.cwd(),h=n.resolve(l);if(t.startsWith(h+n.sep)||t===h)return;let u=c.tmpdir(),S=n.resolve(u);if(!(t.startsWith(S+n.sep)||t===S))throw new Error(`Security: Custom schedulesPath must be within home directory (${s}), current working directory (${l}), or temp directory (${u}). Provided path: ${e}`)}getDefaultSchedulesPath(){let e=c.homedir();return n.join(e,k,b)}async initialize(){if(this.initialized)return;let e=n.dirname(this.schedulesPath);i.existsSync(e)||(i.mkdirSync(e,{recursive:!0}),this.log(`Created directory: ${e}`)),this.initialized=!0}async loadSchedules(){if(await this.initialize(),!i.existsSync(this.schedulesPath))return this.log("Schedules file does not exist, returning empty array"),[];try{let e=i.readFileSync(this.schedulesPath,"utf-8"),s=this.parseSchedulesFile(e);return this.log(`Loaded ${s.schedules.length} schedules`),s.schedules}catch(e){return await this.handleCorruptFile(e),[]}}async saveSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.findIndex(r=>r.id===e.id);t>=0?(s[t]=e,this.log(`Updated schedule: ${e.id}`)):(s.push(e),this.log(`Added schedule: ${e.id}`)),await this.writeSchedules(s)})}async removeSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.filter(r=>r.id!==e);if(t.length===s.length){this.log(`Schedule not found: ${e}`);return}await this.writeSchedules(t),this.log(`Removed schedule: ${e}`)})}async getSchedules(){return this.loadSchedules()}async getSchedule(e){return(await this.loadSchedules()).find(t=>t.id===e)}async getDueSchedules(){let e=await this.loadSchedules(),s=new Date;return e.filter(t=>t.enabled?new Date(t.nextRun)<=s:!1)}async markExecuted(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.find(l=>l.id===e);if(!t)throw new Error(`Schedule not found: ${e}`);let r=new Date;t.lastRun=r.toISOString(),t.nextRun=a(t.schedule,r).toISOString(),await this.writeSchedules(s),this.log(`Marked executed: ${e}, next run: ${t.nextRun}`)})}async setEnabled(e,s){await this.initialize(),await this.withFileLock(async()=>{let t=await this.loadSchedulesUnsafe(),r=t.find(l=>l.id===e);if(!r)throw new Error(`Schedule not found: ${e}`);r.enabled=s,s&&(r.nextRun=a(r.schedule,new Date).toISOString()),await this.writeSchedules(t),this.log(`Set enabled=${s}: ${e}`)})}async getEnabledSchedules(){return(await this.loadSchedules()).filter(s=>s.enabled)}async getSchedulesByWorkflow(e){return(await this.loadSchedules()).filter(t=>t.workflowId===e)}async clearAll(){await this.initialize(),await this.withFileLock(async()=>{await this.writeSchedules([]),this.log("Cleared all schedules")})}async getStats(){let e=await this.loadSchedules(),s=new Date;return{total:e.length,enabled:e.filter(t=>t.enabled).length,disabled:e.filter(t=>!t.enabled).length,due:e.filter(t=>t.enabled&&new Date(t.nextRun)<=s).length}}async loadSchedulesUnsafe(){if(!i.existsSync(this.schedulesPath))return[];try{let e=i.readFileSync(this.schedulesPath,"utf-8");return this.parseSchedulesFile(e).schedules}catch{return[]}}parseSchedulesFile(e){let s=Buffer.byteLength(e,"utf-8");if(s>p)throw new Error(`Schedules file exceeds maximum allowed size (${p/(1024*1024)}MB). File is ${(s/(1024*1024)).toFixed(2)}MB.`);let t=w(e);if(!t.schedules||!Array.isArray(t.schedules))throw new Error("Invalid schedules file: missing schedules array");for(let r of t.schedules)if(!r.id||!r.workflowId||!r.schedule)throw new Error("Invalid schedule entry: missing required fields");return t}async writeSchedules(e){let s={version:F,updatedAt:new Date().toISOString(),schedules:e},t=JSON.stringify(s,null,2);i.writeFileSync(this.schedulesPath,t,"utf-8"),this.log(`Wrote ${e.length} schedules to disk`)}async handleCorruptFile(e){let s=f(e);this.log(`Corrupt schedules file detected: ${s}`);let t=`${this.schedulesPath}.corrupt.${Date.now()}`;try{i.existsSync(this.schedulesPath)&&(i.copyFileSync(this.schedulesPath,t),this.log(`Backed up corrupt file to: ${t}`))}catch(r){this.log(`Failed to backup corrupt file: ${r}`)}try{i.existsSync(this.schedulesPath)&&(i.unlinkSync(this.schedulesPath),this.log("Removed corrupt schedules file"))}catch(r){this.log(`Failed to remove corrupt file: ${r}`)}}async withFileLock(e){await this.acquireLock();try{return await e()}finally{this.releaseLock()}}async acquireLock(){let e=Date.now();for(;i.existsSync(this.lockFile);){try{let s=i.statSync(this.lockFile);if(Date.now()-s.mtimeMs>g){i.unlinkSync(this.lockFile),this.log("Removed stale lock file");break}}catch{break}if(Date.now()-e>g)throw new Error("Timeout waiting for scheduler lock");await this.sleep(x)}try{i.writeFileSync(this.lockFile,`${process.pid}:${Date.now()}`,{flag:"wx"})}catch(s){if(s.code==="EEXIST")return this.acquireLock();throw s}}releaseLock(){try{i.existsSync(this.lockFile)&&i.unlinkSync(this.lockFile)}catch(e){console.debug("[PersistentScheduler] Lock release error:",e instanceof Error?e.message:e)}}sleep(e){return new Promise(s=>setTimeout(s,e))}log(e){this.debug&&console.log(`[PersistentScheduler] ${e}`)}};function E(o={}){return new d(o)}function m(){let o=Date.now().toString(36),e=v().slice(0,8);return`sched-${o}-${e}`}function $(o){let e=new Date;return{id:m(),workflowId:o.workflowId,pipelinePath:o.pipelinePath,schedule:o.schedule,scheduleDescription:o.scheduleDescription,nextRun:a(o.schedule,e).toISOString(),enabled:o.enabled??!0,createdAt:e.toISOString()}}export{d as a,E as b,m as c,$ as d};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.4");process.exit(0)}
2
- import{c as t}from"./chunk-Y4AXOHW4.js";function o(e){try{return 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.12.0");process.exit(0)}
2
+ import{c as t}from"./chunk-3AFNXU45.js";function o(e){try{return e.prepare(`
3
3
  SELECT COUNT(*) as count FROM sqlite_master
4
4
  WHERE type='table' AND name IN ('hypergraph_nodes', 'hypergraph_edges')
5
5
  `).get().count===2}catch{return!1}}var r,a,E,n,p=t(()=>{"use strict";r=`
@@ -1,6 +1,6 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.4");process.exit(0)}
2
- import{e as x,f as C,j as y,k as R,q as F}from"./chunk-O5NEJIHB.js";import{b as I,c as k}from"./chunk-PEIQDQXN.js";import{c as w}from"./chunk-Y4AXOHW4.js";var P,S=w(()=>{"use strict";P={enabled:!0,headless:!0,timeout:3e4,retryAttempts:3,fallbackEnabled:!0,browserType:"chromium",viewport:{width:1280,height:720},userAgent:"",devtools:!1,slowMo:0,screenshotDir:".agentic-qe/screenshots"}});function B(i){return i instanceof o}function a(i,e="Unknown Vibium error"){return B(i)?i:i instanceof Error?new o(i.message||e,"UNKNOWN_ERROR",i):new o(typeof i=="string"?i:e,"UNKNOWN_ERROR")}var o,c,f,g,l,p,m,b,A=w(()=>{"use strict";o=class i extends Error{constructor(t,r,s){super(t);this.code=r;this.cause=s;this.name="VibiumError",Error.captureStackTrace&&Error.captureStackTrace(this,i),s?.stack&&(this.stack+=`
3
- Caused by: ${s.stack}`)}code;cause},c=class extends o{constructor(e="Vibium MCP server is unavailable",t){super(e,"VIBIUM_UNAVAILABLE",t),this.name="VibiumUnavailableError"}},f=class extends o{constructor(e="Browser operation timed out",t){super(e,"VIBIUM_TIMEOUT",t),this.name="VibiumTimeoutError"}},g=class extends o{selector;constructor(e,t){super(`Element not found: ${e}`,"ELEMENT_NOT_FOUND",t),this.name="VibiumElementNotFoundError",this.selector=e}},l=class extends o{constructor(e="Failed to connect to browser",t){super(e,"CONNECTION_ERROR",t),this.name="VibiumConnectionError"}},p=class extends o{url;statusCode;constructor(e,t,r){let s=t?`Navigation failed: ${e} (HTTP ${t})`:`Navigation failed: ${e}`;super(s,"NAVIGATION_ERROR",r),this.name="VibiumNavigationError",this.url=e,this.statusCode=t}},m=class extends o{constructor(e="Failed to capture screenshot",t){super(e,"SCREENSHOT_ERROR",t),this.name="VibiumScreenshotError"}},b=class extends o{action;selector;constructor(e,t,r){super(`Failed to ${e} element: ${t}`,"INTERACTION_ERROR",r),this.name="VibiumInteractionError",this.action=e,this.selector=t}}});import{randomUUID as _}from"crypto";async function V(){if(v!==null)return v;try{return v=(await import("./vibium-2J3H2ITD.js")).browser,O=!0,v}catch(i){return console.warn("[Vibium] Failed to load vibium package:",i),O=!1,null}}async function T(i,e,t){let r;for(let s=1;s<=e;s++)try{return await i()}catch(n){if(r=I(n),s<e){let u=Math.min(100*Math.pow(2,s-1),2e3);await new Promise(d=>setTimeout(d,u))}}throw new o(`${t} failed after ${e} attempts`,"RETRY_EXHAUSTED",r)}async function h(i,e){let t=Date.now();try{let r=await i();return R()&&console.log(`[Vibium] ${e}: ${Date.now()-t}ms`),r}catch(r){throw R()&&console.log(`[Vibium] ${e} failed: ${Date.now()-t}ms`,r),r}}var v,O,E,N,M=w(()=>{S();A();k();F();v=null,O=!1;E=class{config;currentSession=null;lastHealthCheck=null;_initialized=!1;_available=null;vibeInstance=null;constructor(e={}){this.config={...P,...e}}async isAvailable(){if(!this.config.enabled)return!1;if(this._available!==null)return this._available;try{let e=await V();return this._available=e!==null,this._available}catch{return this._available=!1,!1}}async getHealth(){let e=new Date;if(!this.config.enabled)return{status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium is disabled by configuration",sessionActive:!1};try{await this.isAvailable()?this.lastHealthCheck={status:this.vibeInstance?"connected":"disconnected",version:"0.1.2",browserType:this.config.browserType,features:["browser-launch","navigation","element-interaction","screenshots","script-evaluation","accessibility-testing"],latencyMs:10,lastChecked:e,sessionActive:this.vibeInstance!==null}:this.lastHealthCheck={status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium package not available - install with: npm install vibium",sessionActive:!1}}catch(t){this.lastHealthCheck={status:"error",features:["fallback-only"],lastChecked:e,error:t instanceof Error?t.message:"Unknown error",sessionActive:!1}}return this.lastHealthCheck}async getSession(){return this.currentSession}async launch(e){if(!x())return{success:!1,error:new c("Browser mode is disabled by feature flags")};let t=async()=>{let r=await V();if(!r)throw new c("Vibium package not available. Install with: npm install vibium");let s=e?.headless??this.config.headless;this.vibeInstance=await r.launch({headless:s});let n={id:this.generateSessionId(),browserType:this.config.browserType,launchedAt:new Date,status:"connected",viewport:e?.viewport??this.config.viewport,headless:s};return this.currentSession=n,n};try{return{success:!0,value:y()?await T(()=>h(t,"browser_launch"),this.config.retryAttempts,"browser_launch"):await h(t,"browser_launch")}}catch(r){return{success:!1,error:a(r,"Failed to launch browser")}}}async quit(){if(!this.vibeInstance)return{success:!1,error:new l("No active browser session")};let e=async()=>{this.vibeInstance&&(await this.vibeInstance.quit(),this.vibeInstance=null),this.currentSession=null};try{return await h(e,"browser_quit"),{success:!0,value:void 0}}catch(t){return{success:!1,error:a(t,"Failed to quit browser")}}}async navigate(e){this.ensureSession();let t=async()=>{let r=Date.now();await this.vibeInstance.go(e.url);let s="";try{s=await this.vibeInstance.evaluate("document.title")}catch{s="Unknown"}let n={url:e.url,statusCode:200,title:s,durationMs:Date.now()-r,success:!0};return this.currentSession&&(this.currentSession.currentUrl=e.url),n};try{return{success:!0,value:y()?await T(()=>h(t,"page_navigate"),this.config.retryAttempts,"page_navigate"):await h(t,"page_navigate")}}catch(r){return{success:!1,error:new p(e.url,void 0,r instanceof Error?r:void 0)}}}async getPageInfo(){this.ensureSession();try{let e=await this.vibeInstance.evaluate("window.location.href"),t=await this.vibeInstance.evaluate("document.title");return{success:!0,value:{url:e,title:t,viewport:this.config.viewport,loadState:"loaded"}}}catch(e){return{success:!1,error:a(e,"Failed to get page info")}}}async goBack(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.back()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go back")}}}async goForward(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.forward()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go forward")}}}async reload(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.location.reload()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to reload page")}}}async findElement(e){this.ensureSession();try{let t=await this.vibeInstance.find(e.selector,{timeout:e.timeout??this.config.timeout});return{success:!0,value:{selector:e.selector,tagName:t.info.tag,textContent:t.info.text,attributes:{},boundingBox:t.info.box,visible:!0,enabled:!0}}}catch(t){return{success:!1,error:new g(e.selector,t instanceof Error?t:void 0)}}}async findElements(e){this.ensureSession();try{let t=e.selector.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return{success:!0,value:(await this.vibeInstance.evaluate(`
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.12.0");process.exit(0)}
2
+ import{e as x,f as C,j as y,k as R,q as F}from"./chunk-RZDNCTOA.js";import{b as I,c as k}from"./chunk-RHC7TFPU.js";import{c as w}from"./chunk-3AFNXU45.js";var P,S=w(()=>{"use strict";P={enabled:!0,headless:!0,timeout:3e4,retryAttempts:3,fallbackEnabled:!0,browserType:"chromium",viewport:{width:1280,height:720},userAgent:"",devtools:!1,slowMo:0,screenshotDir:".agentic-qe/screenshots"}});function B(i){return i instanceof o}function a(i,e="Unknown Vibium error"){return B(i)?i:i instanceof Error?new o(i.message||e,"UNKNOWN_ERROR",i):new o(typeof i=="string"?i:e,"UNKNOWN_ERROR")}var o,c,f,g,l,p,m,b,A=w(()=>{"use strict";o=class i extends Error{constructor(t,r,s){super(t);this.code=r;this.cause=s;this.name="VibiumError",Error.captureStackTrace&&Error.captureStackTrace(this,i),s?.stack&&(this.stack+=`
3
+ Caused by: ${s.stack}`)}code;cause},c=class extends o{constructor(e="Vibium MCP server is unavailable",t){super(e,"VIBIUM_UNAVAILABLE",t),this.name="VibiumUnavailableError"}},f=class extends o{constructor(e="Browser operation timed out",t){super(e,"VIBIUM_TIMEOUT",t),this.name="VibiumTimeoutError"}},g=class extends o{selector;constructor(e,t){super(`Element not found: ${e}`,"ELEMENT_NOT_FOUND",t),this.name="VibiumElementNotFoundError",this.selector=e}},l=class extends o{constructor(e="Failed to connect to browser",t){super(e,"CONNECTION_ERROR",t),this.name="VibiumConnectionError"}},p=class extends o{url;statusCode;constructor(e,t,r){let s=t?`Navigation failed: ${e} (HTTP ${t})`:`Navigation failed: ${e}`;super(s,"NAVIGATION_ERROR",r),this.name="VibiumNavigationError",this.url=e,this.statusCode=t}},m=class extends o{constructor(e="Failed to capture screenshot",t){super(e,"SCREENSHOT_ERROR",t),this.name="VibiumScreenshotError"}},b=class extends o{action;selector;constructor(e,t,r){super(`Failed to ${e} element: ${t}`,"INTERACTION_ERROR",r),this.name="VibiumInteractionError",this.action=e,this.selector=t}}});import{randomUUID as _}from"crypto";async function V(){if(v!==null)return v;try{return v=(await import("./vibium-GOU55LUO.js")).browser,O=!0,v}catch(i){return console.warn("[Vibium] Failed to load vibium package:",i),O=!1,null}}async function T(i,e,t){let r;for(let s=1;s<=e;s++)try{return await i()}catch(n){if(r=I(n),s<e){let u=Math.min(100*Math.pow(2,s-1),2e3);await new Promise(d=>setTimeout(d,u))}}throw new o(`${t} failed after ${e} attempts`,"RETRY_EXHAUSTED",r)}async function h(i,e){let t=Date.now();try{let r=await i();return R()&&console.log(`[Vibium] ${e}: ${Date.now()-t}ms`),r}catch(r){throw R()&&console.log(`[Vibium] ${e} failed: ${Date.now()-t}ms`,r),r}}var v,O,E,N,M=w(()=>{S();A();k();F();v=null,O=!1;E=class{config;currentSession=null;lastHealthCheck=null;_initialized=!1;_available=null;vibeInstance=null;constructor(e={}){this.config={...P,...e}}async isAvailable(){if(!this.config.enabled)return!1;if(this._available!==null)return this._available;try{let e=await V();return this._available=e!==null,this._available}catch{return this._available=!1,!1}}async getHealth(){let e=new Date;if(!this.config.enabled)return{status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium is disabled by configuration",sessionActive:!1};try{await this.isAvailable()?this.lastHealthCheck={status:this.vibeInstance?"connected":"disconnected",version:"0.1.2",browserType:this.config.browserType,features:["browser-launch","navigation","element-interaction","screenshots","script-evaluation","accessibility-testing"],latencyMs:10,lastChecked:e,sessionActive:this.vibeInstance!==null}:this.lastHealthCheck={status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium package not available - install with: npm install vibium",sessionActive:!1}}catch(t){this.lastHealthCheck={status:"error",features:["fallback-only"],lastChecked:e,error:t instanceof Error?t.message:"Unknown error",sessionActive:!1}}return this.lastHealthCheck}async getSession(){return this.currentSession}async launch(e){if(!x())return{success:!1,error:new c("Browser mode is disabled by feature flags")};let t=async()=>{let r=await V();if(!r)throw new c("Vibium package not available. Install with: npm install vibium");let s=e?.headless??this.config.headless;this.vibeInstance=await r.launch({headless:s});let n={id:this.generateSessionId(),browserType:this.config.browserType,launchedAt:new Date,status:"connected",viewport:e?.viewport??this.config.viewport,headless:s};return this.currentSession=n,n};try{return{success:!0,value:y()?await T(()=>h(t,"browser_launch"),this.config.retryAttempts,"browser_launch"):await h(t,"browser_launch")}}catch(r){return{success:!1,error:a(r,"Failed to launch browser")}}}async quit(){if(!this.vibeInstance)return{success:!1,error:new l("No active browser session")};let e=async()=>{this.vibeInstance&&(await this.vibeInstance.quit(),this.vibeInstance=null),this.currentSession=null};try{return await h(e,"browser_quit"),{success:!0,value:void 0}}catch(t){return{success:!1,error:a(t,"Failed to quit browser")}}}async navigate(e){this.ensureSession();let t=async()=>{let r=Date.now();await this.vibeInstance.go(e.url);let s="";try{s=await this.vibeInstance.evaluate("document.title")}catch{s="Unknown"}let n={url:e.url,statusCode:200,title:s,durationMs:Date.now()-r,success:!0};return this.currentSession&&(this.currentSession.currentUrl=e.url),n};try{return{success:!0,value:y()?await T(()=>h(t,"page_navigate"),this.config.retryAttempts,"page_navigate"):await h(t,"page_navigate")}}catch(r){return{success:!1,error:new p(e.url,void 0,r instanceof Error?r:void 0)}}}async getPageInfo(){this.ensureSession();try{let e=await this.vibeInstance.evaluate("window.location.href"),t=await this.vibeInstance.evaluate("document.title");return{success:!0,value:{url:e,title:t,viewport:this.config.viewport,loadState:"loaded"}}}catch(e){return{success:!1,error:a(e,"Failed to get page info")}}}async goBack(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.back()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go back")}}}async goForward(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.forward()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go forward")}}}async reload(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.location.reload()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to reload page")}}}async findElement(e){this.ensureSession();try{let t=await this.vibeInstance.find(e.selector,{timeout:e.timeout??this.config.timeout});return{success:!0,value:{selector:e.selector,tagName:t.info.tag,textContent:t.info.text,attributes:{},boundingBox:t.info.box,visible:!0,enabled:!0}}}catch(t){return{success:!1,error:new g(e.selector,t instanceof Error?t:void 0)}}}async findElements(e){this.ensureSession();try{let t=e.selector.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return{success:!0,value:(await this.vibeInstance.evaluate(`
4
4
  Array.from(document.querySelectorAll('${t}'))
5
5
  .map(el => ({
6
6
  tag: el.tagName.toLowerCase(),
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.4");process.exit(0)}
2
- import{a as w,b as A,c as O,e as D,f as z}from"./chunk-LW5DHT3Z.js";import{b as S,d as $}from"./chunk-VJGHRWMH.js";import{a as N,c as F}from"./chunk-PEIQDQXN.js";import{i as v}from"./chunk-BMQDELPA.js";import*as I from"node:path";z();$();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],b=class{ensureSchema(e){e.transaction(()=>{e.exec(w),e.exec(A),e.exec(O)})()}schemaExists(e){return D(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function C(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function T(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function H(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},R=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new b}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=v(),r={id:t,...e},s=C(r);return this.config.db.prepare(`
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.12.0");process.exit(0)}
2
+ import{a as w,b as A,c as O,e as D,f as z}from"./chunk-SSXAW3ER.js";import{b as S,d as $}from"./chunk-K5SN66B4.js";import{a as N,c as F}from"./chunk-RHC7TFPU.js";import{i as v}from"./chunk-6JNNZGI2.js";import*as I from"node:path";z();$();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],b=class{ensureSchema(e){e.transaction(()=>{e.exec(w),e.exec(A),e.exec(O)})()}schemaExists(e){return D(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function C(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function T(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function H(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},R=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new b}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=v(),r={id:t,...e},s=C(r);return this.config.db.prepare(`
3
3
  INSERT INTO hypergraph_nodes (id, type, name, file_path, line_start, line_end, complexity, coverage, metadata, embedding)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5
5
  `).run(s.id,s.type,s.name,s.file_path,s.line_start,s.line_end,s.complexity,s.coverage,s.metadata,s.embedding),t}async addEdge(e){this.ensureInitialized();let t=x(e.sourceId,e.targetId,e.type),r={id:t,...e},s=M(r);return this.config.db.prepare(`
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.4");process.exit(0)}
2
- import{a as o,e as p}from"./chunk-VCUCD3B5.js";import{a as l,d}from"./chunk-QJ5NCYJ3.js";d();p();var u=class{store=new Map;vectors=new Map;cleanupInterval;async initialize(){this.cleanupInterval=setInterval(()=>this.cleanup(),o.CLEANUP_INTERVAL_MS),this.cleanupInterval.unref&&this.cleanupInterval.unref()}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.store.clear(),this.vectors.clear()}async set(t,r,e){let s={value:r,namespace:e?.namespace??"default",createdAt:Date.now()};e?.ttl&&(s.expiresAt=Date.now()+e.ttl*o.TTL_MULTIPLIER_MS);let n=this.buildKey(t,e?.namespace);this.store.set(n,s)}async get(t,r){let e=this.buildKey(t,r?.namespace),s=this.store.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.store.delete(e);return}return s.value}}async delete(t,r){let e=this.buildKey(t,r?.namespace);return this.store.delete(e)}async has(t,r){return await this.get(t,r)!==void 0}async search(t,r=o.DEFAULT_SEARCH_LIMIT,e){let s=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(s.replace(/\*/g,".*")),i=[],c=e?.namespace?`${e.namespace}:`:void 0;for(let a of this.store.keys())if(!(c&&!a.startsWith(c))&&n.test(a)&&(i.push(a),i.length>=r))break;return i}async vectorSearch(t,r){let e=[];for(let[s,n]of this.vectors.entries()){let i=l(t,n.embedding);e.push({key:s,score:i,metadata:n.metadata})}return e.sort((s,n)=>n.score-s.score).slice(0,r)}async storeVector(t,r,e){this.vectors.set(t,{embedding:r,metadata:e})}buildKey(t,r){return r?`${r}:${t}`:t}cleanup(){let t=Date.now();for(let[r,e]of this.store.entries())e.expiresAt&&t>e.expiresAt&&this.store.delete(r)}getStats(){return{entries:this.store.size,vectors:this.vectors.size}}async clear(t){if(t){let r=`${t}:`;for(let e of this.store.keys())e.startsWith(r)&&this.store.delete(e)}else this.store.clear()}async count(t){let r=0,e=`${t}:`;for(let s of this.store.keys())if(s.startsWith(e)){let n=this.store.get(s);n&&(!n.expiresAt||Date.now()<=n.expiresAt)&&r++}return r}async hasCodeIntelligenceIndex(){return await this.count("code-intelligence:kg")>0}};export{u as a};
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.12.0");process.exit(0)}
2
+ import{a as o,e as p}from"./chunk-V2MD5EDD.js";import{a as l,d}from"./chunk-64M3FFM4.js";d();p();var u=class{store=new Map;vectors=new Map;cleanupInterval;async initialize(){this.cleanupInterval=setInterval(()=>this.cleanup(),o.CLEANUP_INTERVAL_MS),this.cleanupInterval.unref&&this.cleanupInterval.unref()}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.store.clear(),this.vectors.clear()}async set(t,r,e){let s={value:r,namespace:e?.namespace??"default",createdAt:Date.now()};e?.ttl&&(s.expiresAt=Date.now()+e.ttl*o.TTL_MULTIPLIER_MS);let n=this.buildKey(t,e?.namespace);this.store.set(n,s)}async get(t,r){let e=this.buildKey(t,r?.namespace),s=this.store.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.store.delete(e);return}return s.value}}async delete(t,r){let e=this.buildKey(t,r?.namespace);return this.store.delete(e)}async has(t,r){return await this.get(t,r)!==void 0}async search(t,r=o.DEFAULT_SEARCH_LIMIT,e){let s=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(s.replace(/\*/g,".*")),i=[],c=e?.namespace?`${e.namespace}:`:void 0;for(let a of this.store.keys())if(!(c&&!a.startsWith(c))&&n.test(a)&&(i.push(a),i.length>=r))break;return i}async vectorSearch(t,r){let e=[];for(let[s,n]of this.vectors.entries()){let i=l(t,n.embedding);e.push({key:s,score:i,metadata:n.metadata})}return e.sort((s,n)=>n.score-s.score).slice(0,r)}async storeVector(t,r,e){this.vectors.set(t,{embedding:r,metadata:e})}buildKey(t,r){return r?`${r}:${t}`:t}cleanup(){let t=Date.now();for(let[r,e]of this.store.entries())e.expiresAt&&t>e.expiresAt&&this.store.delete(r)}getStats(){return{entries:this.store.size,vectors:this.vectors.size}}async clear(t){if(t){let r=`${t}:`;for(let e of this.store.keys())e.startsWith(r)&&this.store.delete(e)}else this.store.clear()}async count(t){let r=0,e=`${t}:`;for(let s of this.store.keys())if(s.startsWith(e)){let n=this.store.get(s);n&&(!n.expiresAt||Date.now()<=n.expiresAt)&&r++}return r}async hasCodeIntelligenceIndex(){return await this.count("code-intelligence:kg")>0}};export{u as a};
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.4");process.exit(0)}
2
- import{c}from"./chunk-Y4AXOHW4.js";function u(r){switch(r.toUpperCase()){case"DEBUG":return 0;case"INFO":return 1;case"WARN":case"WARNING":return 2;case"ERROR":return 3;case"SILENT":case"NONE":case"OFF":return 4;default:return 1}}var f,l=c(()=>{"use strict";f={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR",4:"SILENT"}});var a,s,g,d=c(()=>{"use strict";l();a={includeTimestamp:!0,includeLevel:!0,timestampFormat:"short",prettyPrint:!1,maxContextDepth:3},s=class r{domain;level;config;inheritedContext;constructor(e,n=1,o={},t={}){this.domain=e,this.level=n,this.config={...a,...o},this.inheritedContext=t}debug(e,n){this.level<=0&&this.output(0,e,n)}info(e,n){this.level<=1&&this.output(1,e,n)}warn(e,n){this.level<=2&&this.output(2,e,n)}error(e,n,o){if(this.level<=3){let t={...o};if(n){t.errorName=n.name,t.errorMessage=n.message,n.stack&&(t.stack=n.stack);let i=n;i.cause!==void 0&&(t.cause=String(i.cause))}this.output(3,e,t)}}isEnabled(e){return this.level<=e}getDomain(){return this.domain}child(e){return new r(this.domain,this.level,this.config,{...this.inheritedContext,...e})}output(e,n,o){let t=this.format(e,n,o);switch(e){case 0:console.debug(t);break;case 1:console.info(t);break;case 2:console.warn(t);break;case 3:console.error(t);break}}format(e,n,o){let t=[];this.config.includeTimestamp&&t.push(this.formatTimestamp()),this.config.includeLevel&&t.push(this.formatLevel(e)),t.push(`[${this.domain}]`),t.push(n);let i=this.mergeContext(o);return i&&Object.keys(i).length>0&&t.push(this.formatContext(i)),t.join(" ")}formatTimestamp(){let e=new Date;if(this.config.timestampFormat==="iso")return`[${e.toISOString()}]`;let n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),t=String(e.getSeconds()).padStart(2,"0"),i=String(e.getMilliseconds()).padStart(3,"0");return`[${n}:${o}:${t}.${i}]`}formatLevel(e){return`[${f[e].padEnd(5)}]`}mergeContext(e){if(!(!e&&Object.keys(this.inheritedContext).length===0))return{...this.inheritedContext,...e}}formatContext(e){try{return this.config.prettyPrint?`
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.12.0");process.exit(0)}
2
+ import{c}from"./chunk-3AFNXU45.js";function u(r){switch(r.toUpperCase()){case"DEBUG":return 0;case"INFO":return 1;case"WARN":case"WARNING":return 2;case"ERROR":return 3;case"SILENT":case"NONE":case"OFF":return 4;default:return 1}}var f,l=c(()=>{"use strict";f={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR",4:"SILENT"}});var a,s,g,d=c(()=>{"use strict";l();a={includeTimestamp:!0,includeLevel:!0,timestampFormat:"short",prettyPrint:!1,maxContextDepth:3},s=class r{domain;level;config;inheritedContext;constructor(e,n=1,o={},t={}){this.domain=e,this.level=n,this.config={...a,...o},this.inheritedContext=t}debug(e,n){this.level<=0&&this.output(0,e,n)}info(e,n){this.level<=1&&this.output(1,e,n)}warn(e,n){this.level<=2&&this.output(2,e,n)}error(e,n,o){if(this.level<=3){let t={...o};if(n){t.errorName=n.name,t.errorMessage=n.message,n.stack&&(t.stack=n.stack);let i=n;i.cause!==void 0&&(t.cause=String(i.cause))}this.output(3,e,t)}}isEnabled(e){return this.level<=e}getDomain(){return this.domain}child(e){return new r(this.domain,this.level,this.config,{...this.inheritedContext,...e})}output(e,n,o){let t=this.format(e,n,o);switch(e){case 0:console.debug(t);break;case 1:console.info(t);break;case 2:console.warn(t);break;case 3:console.error(t);break}}format(e,n,o){let t=[];this.config.includeTimestamp&&t.push(this.formatTimestamp()),this.config.includeLevel&&t.push(this.formatLevel(e)),t.push(`[${this.domain}]`),t.push(n);let i=this.mergeContext(o);return i&&Object.keys(i).length>0&&t.push(this.formatContext(i)),t.join(" ")}formatTimestamp(){let e=new Date;if(this.config.timestampFormat==="iso")return`[${e.toISOString()}]`;let n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),t=String(e.getSeconds()).padStart(2,"0"),i=String(e.getMilliseconds()).padStart(3,"0");return`[${n}:${o}:${t}.${i}]`}formatLevel(e){return`[${f[e].padEnd(5)}]`}mergeContext(e){if(!(!e&&Object.keys(this.inheritedContext).length===0))return{...this.inheritedContext,...e}}formatContext(e){try{return this.config.prettyPrint?`
3
3
  `+JSON.stringify(e,this.createReplacer(),2):JSON.stringify(e,this.createReplacer())}catch{return"[unserializable context]"}}createReplacer(){let e=new WeakSet,n=0;return(o,t)=>{if(typeof t=="object"&&t!==null){if(n>=this.config.maxContextDepth)return"[object]";if(e.has(t))return"[circular]";e.add(t),n++}return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:typeof t=="bigint"?t.toString():typeof t=="function"?"[function]":typeof t=="symbol"?t.toString():t}}},g=class{domain;constructor(e="null"){this.domain=e}debug(e,n){}info(e,n){}warn(e,n){}error(e,n,o){}isEnabled(e){return!1}getDomain(){return this.domain}child(e){return this}}});function F(r,e){return L.create(r,e)}var v,L,m=c(()=>{"use strict";l();d();v={defaultLevel:1,domainLevels:new Map,consoleConfig:a,silent:!1},L=class{static config={...v};static customProvider=null;static instances=new Map;static setLevel(e){this.config.defaultLevel=e,this.instances.clear()}static setLevelFromString(e){this.setLevel(u(e))}static getLevel(){return this.config.defaultLevel}static setDomainLevel(e,n){this.config.domainLevels.set(e,n),this.instances.delete(e)}static getDomainLevel(e){return this.config.domainLevels.get(e)??this.config.defaultLevel}static clearDomainLevel(e){this.config.domainLevels.delete(e),this.instances.delete(e)}static configure(e){this.config.consoleConfig={...this.config.consoleConfig,...e},this.instances.clear()}static setSilent(e){this.config.silent=e,this.instances.clear()}static isSilent(){return this.config.silent}static setProvider(e){this.customProvider=e,this.instances.clear()}static create(e,n){if(!n&&this.instances.has(e))return this.instances.get(e);let o=this.getDomainLevel(e),t;return this.config.silent?t=new g(e):this.customProvider?t=this.customProvider(e,o,n):t=new s(e,o,this.config.consoleConfig,n),n||this.instances.set(e,t),t}static getLogger(e,n){return this.create(e,n)}static reset(){this.config={defaultLevel:1,domainLevels:new Map,consoleConfig:{...a},silent:!1},this.customProvider=null,this.instances.clear()}static initFromEnv(){let e=process.env.LOG_LEVEL;e&&this.setLevelFromString(e);let n=process.env.LOG_TIMESTAMP;n!==void 0&&this.configure({includeTimestamp:n.toLowerCase()==="true"});let o=process.env.LOG_PRETTY;o!==void 0&&this.configure({prettyPrint:o.toLowerCase()==="true"})}static getStats(){return{cachedLoggers:this.instances.size,domains:Array.from(this.instances.keys()),domainOverrides:this.config.domainLevels.size,currentLevel:this.config.defaultLevel,silent:this.config.silent}}}});export{l as a,d as b,L as c,F as d,m as e};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.4");process.exit(0)}
2
- import{a as F}from"./chunk-4JFH3MVA.js";import{a as q,e as C,f as B}from"./chunk-3FJZMQJ7.js";import{a as I}from"./chunk-NFJT7XXR.js";import{a as z,b as H,c as _,d as U}from"./chunk-QSDIY3E2.js";import{a as A,b as N,f as W,i as O}from"./chunk-IF3HPQNV.js";import{e as j}from"./chunk-YKSWC7I4.js";import{b as v,d as L,f as M,g as P}from"./chunk-54B6P2WS.js";import{a as K}from"./chunk-XXRTWG7O.js";import{c as D}from"./chunk-6GYGAW53.js";import{b as w,d as Y}from"./chunk-VJGHRWMH.js";import{b as f,c as h}from"./chunk-O7PVZ32A.js";import{a as Q,b,c as J}from"./chunk-PEIQDQXN.js";import{i as T}from"./chunk-BMQDELPA.js";K();J();Y();var o=D.create("RealQEReasoningBank"),V={sqlite:{dbPath:".agentic-qe/memory.db",walMode:!0,useUnified:!0},embeddings:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0},enableLearning:!0,enableRouting:!0,enableGuidance:!0,hnsw:{M:16,efConstruction:200,efSearch:100},routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4},R=class{constructor(e={},t){this.coherenceService=t;this.qeConfig={...V,...e},this.sqliteStore=j(this.qeConfig.sqlite),this.asymmetricEngine=new F}coherenceService;qeConfig;sqliteStore;hnswIndex=null;patternIdMap=new Map;initialized=!1;stats={routingRequests:0,totalRoutingLatency:0,learningOutcomes:0,successfulOutcomes:0};routingLatencies=new I(1e3);asymmetricEngine;agentCapabilities={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}};async initialize(){if(this.initialized)return;let e=performance.now();await this.sqliteStore.initialize(),o.info("SQLite persistence initialized"),await this.initializeHNSW(),o.info("HNSW index initialized"),await this.loadPatternsIntoHNSW(),this.sqliteStore.getStats().totalPatterns===0&&(this.sqliteStore.hasAnyHistoricalData?.()??!1?o.error("qe_patterns table is EMPTY but historical data exists \u2014 possible data loss! Restore from backup instead of loading seed patterns. Skipping foundational pattern load to avoid masking data loss."):await this.loadFoundationalPatterns()),this.initialized=!0;let i=performance.now()-e;o.info("Fully initialized",{durationMs:Math.round(i)})}async initializeHNSW(){try{let e=await import("./hnswlib-node-LAFK5QZ4.js"),i=e.default?.HierarchicalNSW||e.HierarchicalNSW;if(typeof i!="function")throw new Error("HierarchicalNSW not found in hnswlib-node module");let n=i,a=P();this.hnswIndex=new n("cosine",a),this.hnswIndex.initIndex(1e5,this.qeConfig.hnsw.M,this.qeConfig.hnsw.efConstruction),this.hnswIndex.setEf(this.qeConfig.hnsw.efSearch),o.info("HNSW initialized",{dimension:a,M:this.qeConfig.hnsw.M})}catch(e){throw o.error("HNSW initialization failed",e instanceof Error?e:void 0),e}}async loadPatternsIntoHNSW(){if(!this.hnswIndex)return;let e=this.sqliteStore.getAllEmbeddings(),t=P(),i=0,n=0;for(let{patternId:a,embedding:s}of e){if(!s||!Array.isArray(s)||s.length!==t){n++;continue}let r=this.hnswIndex.getCurrentCount();this.hnswIndex.addPoint(s,r),this.patternIdMap.set(r,a),i++}n>0&&o.warn("Skipped invalid embeddings",{skipped:n,expectedDim:t}),o.info("Loaded patterns into HNSW index",{count:i})}async loadFoundationalPatterns(){let e=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
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.12.0");process.exit(0)}
2
+ import{a as F}from"./chunk-7F7U2HUH.js";import{a as q,e as C,f as B}from"./chunk-2ALNNXFF.js";import{a as I}from"./chunk-ZWC6CM4R.js";import{a as z,b as H,c as _,d as U}from"./chunk-5YGESYBC.js";import{a as A,b as N,f as W,i as O}from"./chunk-VMP4M5PB.js";import{d as j}from"./chunk-Z3W3R4CW.js";import{b as v,d as L,f as M,g as P}from"./chunk-VZ67ZDB3.js";import{a as K}from"./chunk-MDT3LIXS.js";import{c as D}from"./chunk-TJEJ4UVX.js";import{b as w,d as Y}from"./chunk-K5SN66B4.js";import{b as f,c as h}from"./chunk-7ZIVDGSN.js";import{a as Q,b,c as J}from"./chunk-RHC7TFPU.js";import{i as T}from"./chunk-6JNNZGI2.js";K();J();Y();var o=D.create("RealQEReasoningBank"),V={sqlite:{dbPath:".agentic-qe/memory.db",walMode:!0,useUnified:!0},embeddings:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0},enableLearning:!0,enableRouting:!0,enableGuidance:!0,hnsw:{M:16,efConstruction:200,efSearch:100},routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4},R=class{constructor(e={},t){this.coherenceService=t;this.qeConfig={...V,...e},this.sqliteStore=j(this.qeConfig.sqlite),this.asymmetricEngine=new F}coherenceService;qeConfig;sqliteStore;hnswIndex=null;patternIdMap=new Map;initialized=!1;stats={routingRequests:0,totalRoutingLatency:0,learningOutcomes:0,successfulOutcomes:0};routingLatencies=new I(1e3);asymmetricEngine;agentCapabilities={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}};async initialize(){if(this.initialized)return;let e=performance.now();await this.sqliteStore.initialize(),o.info("SQLite persistence initialized"),await this.initializeHNSW(),o.info("HNSW index initialized"),await this.loadPatternsIntoHNSW(),this.sqliteStore.getStats().totalPatterns===0&&(this.sqliteStore.hasAnyHistoricalData?.()??!1?o.error("qe_patterns table is EMPTY but historical data exists \u2014 possible data loss! Restore from backup instead of loading seed patterns. Skipping foundational pattern load to avoid masking data loss."):await this.loadFoundationalPatterns()),this.initialized=!0;let i=performance.now()-e;o.info("Fully initialized",{durationMs:Math.round(i)})}async initializeHNSW(){try{let e=await import("./hnswlib-node-VS6L5VUG.js"),i=e.default?.HierarchicalNSW||e.HierarchicalNSW;if(typeof i!="function")throw new Error("HierarchicalNSW not found in hnswlib-node module");let n=i,a=P();this.hnswIndex=new n("cosine",a),this.hnswIndex.initIndex(1e5,this.qeConfig.hnsw.M,this.qeConfig.hnsw.efConstruction),this.hnswIndex.setEf(this.qeConfig.hnsw.efSearch),o.info("HNSW initialized",{dimension:a,M:this.qeConfig.hnsw.M})}catch(e){throw o.error("HNSW initialization failed",e instanceof Error?e:void 0),e}}async loadPatternsIntoHNSW(){if(!this.hnswIndex)return;let e=this.sqliteStore.getAllEmbeddings(),t=P(),i=0,n=0;for(let{patternId:a,embedding:s}of e){if(!s||!Array.isArray(s)||s.length!==t){n++;continue}let r=this.hnswIndex.getCurrentCount();this.hnswIndex.addPoint(s,r),this.patternIdMap.set(r,a),i++}n>0&&o.warn("Skipped invalid embeddings",{skipped:n,expectedDim:t}),o.info("Loaded patterns into HNSW index",{count:i})}async loadFoundationalPatterns(){let e=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
3
3
  describe('{{methodName}}', () => {
4
4
  it('should {{expectedBehavior}}', {{async}} () => {
5
5
  // Arrange
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.4");process.exit(0)}
2
- import{a as W}from"./chunk-XQ6DW5FV.js";import{c as V,d as q}from"./chunk-3SRPFBU7.js";import{c as M}from"./chunk-JFLSQH2X.js";import{a as G}from"./chunk-XXRTWG7O.js";import{c as N}from"./chunk-6GYGAW53.js";import{b as D,d as $}from"./chunk-VJGHRWMH.js";import{a as E,c as H}from"./chunk-PEIQDQXN.js";import{i as y}from"./chunk-BMQDELPA.js";import{a as R,b as U,d as ee}from"./chunk-7AWK43JN.js";var B={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};$();H();var A=class{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...B,...e}}async initialize(){if(!this.initialized)try{if(this.persistence=M(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.prepareStatements(),this.initialized=!0,this.config.debug){let e=await this.getStats();console.log(`[ConceptGraph] Initialized: ${this.persistence.getDbPath()}`,e)}}catch(e){throw new Error(`Failed to initialize ConceptGraph: ${E(e)}`)}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertNode",this.db.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.12.0");process.exit(0)}
2
+ import{a as q}from"./chunk-BUYPRUNY.js";import{c as V,d as W}from"./chunk-O3C5RRDQ.js";import{c as x}from"./chunk-EM2JIIAQ.js";import{a as G}from"./chunk-MDT3LIXS.js";import{c as R}from"./chunk-TJEJ4UVX.js";import{b as E,d as $}from"./chunk-K5SN66B4.js";import{a as C,c as H}from"./chunk-RHC7TFPU.js";import{i as v}from"./chunk-6JNNZGI2.js";import{a as M,b as U,d as ee}from"./chunk-KJWQ7ENF.js";var P={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};$();H();var T=class p{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...P,...e}}async initialize(){if(!this.initialized)try{if(this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.prepareStatements(),this.initialized=!0,this.config.debug){let e=await this.getStats();console.log(`[ConceptGraph] Initialized: ${this.persistence.getDbPath()}`,e)}}catch(e){throw new Error(`Failed to initialize ConceptGraph: ${C(e)}`)}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertNode",this.db.prepare(`
3
3
  INSERT INTO concept_nodes
4
4
  (id, concept_type, content, embedding, activation_level, last_activated, pattern_id, metadata)
5
5
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
@@ -37,11 +37,15 @@ import{a as W}from"./chunk-XQ6DW5FV.js";import{c as V,d as q}from"./chunk-3SRPFB
37
37
  SELECT COUNT(*) as count FROM concept_edges
38
38
  `)),this.prepared.set("countByType",this.db.prepare(`
39
39
  SELECT concept_type, COUNT(*) as count FROM concept_nodes GROUP BY concept_type
40
- `))}async addNode(e){this.ensureInitialized();let t=y(),n=new Date().toISOString(),i=this.prepared.get("insertNode");if(!i)throw new Error("Prepared statement not found: insertNode");let r=e.embedding?Buffer.from(new Float32Array(e.embedding).buffer):null;return i.run(t,e.conceptType,e.content,r,0,n,e.patternId||null,e.metadata?JSON.stringify(e.metadata):null),this.config.debug&&console.log(`[ConceptGraph] Added node: ${t} (${e.conceptType})`),t}async getNode(e){this.ensureInitialized();let t=this.prepared.get("getNode");if(!t)throw new Error("Prepared statement not found: getNode");let n=t.get(e);return n?this.rowToNode(n):null}async updateActivation(e,t){this.ensureInitialized();let n=this.prepared.get("updateActivation");if(!n)throw new Error("Prepared statement not found: updateActivation");let i=Math.max(0,Math.min(1,t));n.run(i,e)}async getActiveNodes(e=.1){this.ensureInitialized();let t=this.prepared.get("getActiveNodes");if(!t)throw new Error("Prepared statement not found: getActiveNodes");return t.all(e).map(i=>this.rowToNode(i))}async getNodesByType(e){this.ensureInitialized();let t=this.prepared.get("getNodesByType");if(!t)throw new Error("Prepared statement not found: getNodesByType");return t.all(e).map(i=>this.rowToNode(i))}async addEdge(e,t,n,i=1){this.ensureInitialized();let r=await this.getEdgeBetween(e,t);if(r)return await this.strengthenEdge(e,t,.1),r.id;let a=y(),o=this.prepared.get("insertEdge");if(!o)throw new Error("Prepared statement not found: insertEdge");return o.run(a,e,t,n,Math.max(0,Math.min(1,i)),1),this.config.debug&&console.log(`[ConceptGraph] Added edge: ${e} -> ${t} (${n})`),a}async strengthenEdge(e,t,n=.1){this.ensureInitialized();let i=await this.getEdgeBetween(e,t);if(!i)return;let r=Math.min(1,i.weight+n),a=this.prepared.get("updateEdge");if(!a)throw new Error("Prepared statement not found: updateEdge");a.run(r,e,t)}async getNeighbors(e){this.ensureInitialized();let t=[],n=this.prepared.get("getOutgoingEdges");if(!n)throw new Error("Prepared statement not found: getOutgoingEdges");let i=n.all(e);for(let o of i){let s=await this.getNode(o.target);s&&t.push({node:s,edge:this.rowToEdge(o)})}let r=this.prepared.get("getIncomingEdges");if(!r)throw new Error("Prepared statement not found: getIncomingEdges");let a=r.all(e);for(let o of a){let s=await this.getNode(o.source);s&&t.push({node:s,edge:this.rowToEdge(o)})}return t}async findPath(e,t,n=5){this.ensureInitialized();let i=new Set,r=[{nodeId:e,path:[e]}];for(;r.length>0;){let a=r.shift();if(a.nodeId===t){let s=[];for(let c of a.path){let h=await this.getNode(c);h&&s.push(h)}return s}if(a.path.length>n||i.has(a.nodeId))continue;i.add(a.nodeId);let o=await this.getNeighbors(a.nodeId);for(let{node:s}of o)i.has(s.id)||r.push({nodeId:s.id,path:[...a.path,s.id]})}return[]}async getCluster(e,t=2){this.ensureInitialized();let n=new Set,i=[],r=async(a,o)=>{if(n.has(a)||o>t)return;n.add(a);let s=await this.getNode(a);if(s&&(i.push(s),o<t)){let c=await this.getNeighbors(a);for(let{node:h}of c)await r(h.id,o+1)}};return await r(e,0),i}async loadFromPatterns(e){this.ensureInitialized();let t=0,n=[],i=new Map;for(let r of e)try{if(await this.findNodeByPatternId(r.id))continue;let o=await this.addNode({conceptType:"pattern",content:`${r.name}: ${r.description}`,patternId:r.id,metadata:{domain:r.domain,patternType:r.patternType,confidence:r.confidence,successRate:r.successRate}});t++,n.push(o);let s=r.domain||"unknown";i.has(s)||i.set(s,[]),i.get(s).push(o);let c=await this.findDomainNode(r.domain);if(!c){let h=await this.addNode({conceptType:"domain",content:r.domain,metadata:{patternCount:1}});c=await this.getNode(h)}c&&await this.addEdge(o,c.id,"co_occurrence",.8)}catch(a){this.config.debug&&console.error(`[ConceptGraph] Failed to load pattern: ${r.id}`,a)}if(t>0){let r=await this.discoverSameDomainEdges(i),a=await this.pruneEdges();this.config.debug&&console.log(`[ConceptGraph] Discovered ${r} same-domain edges, pruned ${a}`)}return console.log(`[ConceptGraph] Loaded ${t} new patterns (${e.length-t} already existed)`),t}async discoverSameDomainEdges(e){if(this.ensureInitialized(),!this.db)return 0;let t=15,n=5e3,i=0;if(e&&e.size>0)for(let[r,a]of e){let o=this.countDomainSimilarityEdges(r);if(o>=n){console.log(`[ConceptGraph] Domain '${r}' already at edge cap (${o}/${n}), skipping`);continue}let s=new Set(a),c=n-o,p=this.db.prepare("SELECT id, metadata FROM concept_nodes WHERE concept_type = 'pattern'").all().filter(u=>{if(s.has(u.id))return!1;let m=u.metadata?D(u.metadata):{};return String(m.domain||"unknown")===r}),l=this.db.transaction(()=>{let u=0;for(let m of a){let v=0;for(let f of p){if(v>=t||u>=c)break;if(!this.prepared.get("getEdge")?.get(m,f.id)){let S=y();this.prepared.get("insertEdge").run(S,m,f.id,"similarity",.6,1),u++,v++}}if(u>=c)break}for(let m=0;m<a.length&&u<c;m++){let v=0;for(let f=m+1;f<a.length&&u<c&&!(v>=t);f++)if(!this.prepared.get("getEdge")?.get(a[m],a[f])){let S=y();this.prepared.get("insertEdge").run(S,a[m],a[f],"similarity",.6,1),u++,v++}}return u});i+=l()}else{let r=this.db.prepare("SELECT id, metadata FROM concept_nodes WHERE concept_type = 'pattern'").all(),a=new Map;for(let s of r){let c=s.metadata?D(s.metadata):{},h=String(c.domain||"unknown");a.has(h)||a.set(h,[]),a.get(h).push(s)}let o=this.db.transaction(()=>{let s=0;for(let[c,h]of a){let p=this.countDomainSimilarityEdges(c);if(p>=n)continue;let l=0,u=n-p;for(let m=0;m<h.length&&l<u;m++){let v=0;for(let f=m+1;f<h.length&&l<u&&!(v>=t);f++)if(!this.prepared.get("getEdge")?.get(h[m].id,h[f].id)){let S=y();this.prepared.get("insertEdge").run(S,h[m].id,h[f].id,"similarity",.6,1),s++,l++,v++}}}return s});i+=o()}return i}countDomainSimilarityEdges(e){return this.db?this.db.prepare(`
40
+ `))}async addNode(e){this.ensureInitialized();let t=v(),n=new Date().toISOString(),i=this.prepared.get("insertNode");if(!i)throw new Error("Prepared statement not found: insertNode");let r=e.embedding?Buffer.from(new Float32Array(e.embedding).buffer):null;return i.run(t,e.conceptType,e.content,r,0,n,e.patternId||null,e.metadata?JSON.stringify(e.metadata):null),this.config.debug&&console.log(`[ConceptGraph] Added node: ${t} (${e.conceptType})`),t}async getNode(e){this.ensureInitialized();let t=this.prepared.get("getNode");if(!t)throw new Error("Prepared statement not found: getNode");let n=t.get(e);return n?this.rowToNode(n):null}async updateActivation(e,t){this.ensureInitialized();let n=this.prepared.get("updateActivation");if(!n)throw new Error("Prepared statement not found: updateActivation");let i=Math.max(0,Math.min(1,t));n.run(i,e)}async getActiveNodes(e=.1){this.ensureInitialized();let t=this.prepared.get("getActiveNodes");if(!t)throw new Error("Prepared statement not found: getActiveNodes");return t.all(e).map(i=>this.rowToNode(i))}async getNodesByType(e){this.ensureInitialized();let t=this.prepared.get("getNodesByType");if(!t)throw new Error("Prepared statement not found: getNodesByType");return t.all(e).map(i=>this.rowToNode(i))}async addEdge(e,t,n,i=1){this.ensureInitialized();let r=await this.getEdgeBetween(e,t);if(r)return await this.strengthenEdge(e,t,.1),r.id;let a=v(),o=this.prepared.get("insertEdge");if(!o)throw new Error("Prepared statement not found: insertEdge");return o.run(a,e,t,n,Math.max(0,Math.min(1,i)),1),this.config.debug&&console.log(`[ConceptGraph] Added edge: ${e} -> ${t} (${n})`),a}async strengthenEdge(e,t,n=.1){this.ensureInitialized();let i=await this.getEdgeBetween(e,t);if(!i)return;let r=Math.min(1,i.weight+n),a=this.prepared.get("updateEdge");if(!a)throw new Error("Prepared statement not found: updateEdge");a.run(r,e,t)}async getNeighbors(e){this.ensureInitialized();let t=[],n=this.prepared.get("getOutgoingEdges");if(!n)throw new Error("Prepared statement not found: getOutgoingEdges");let i=n.all(e);for(let o of i){let s=await this.getNode(o.target);s&&t.push({node:s,edge:this.rowToEdge(o)})}let r=this.prepared.get("getIncomingEdges");if(!r)throw new Error("Prepared statement not found: getIncomingEdges");let a=r.all(e);for(let o of a){let s=await this.getNode(o.source);s&&t.push({node:s,edge:this.rowToEdge(o)})}return t}async findPath(e,t,n=5){this.ensureInitialized();let i=new Set,r=[{nodeId:e,path:[e]}];for(;r.length>0;){let a=r.shift();if(a.nodeId===t){let s=[];for(let c of a.path){let l=await this.getNode(c);l&&s.push(l)}return s}if(a.path.length>n||i.has(a.nodeId))continue;i.add(a.nodeId);let o=await this.getNeighbors(a.nodeId);for(let{node:s}of o)i.has(s.id)||r.push({nodeId:s.id,path:[...a.path,s.id]})}return[]}async getCluster(e,t=2){this.ensureInitialized();let n=new Set,i=[],r=async(a,o)=>{if(n.has(a)||o>t)return;n.add(a);let s=await this.getNode(a);if(s&&(i.push(s),o<t)){let c=await this.getNeighbors(a);for(let{node:l}of c)await r(l.id,o+1)}};return await r(e,0),i}static TECHNIQUE_PATTERN_TYPES=new Set(["coverage-strategy","mutation-strategy","refactor-safe","error-handling","meta-optimization"]);async loadFromPatterns(e){this.ensureInitialized();let t=0,n=[],i=new Map;for(let r of e)try{if(await this.findNodeByPatternId(r.id))continue;let o=r.patternType&&p.TECHNIQUE_PATTERN_TYPES.has(r.patternType)?"technique":"pattern",s=await this.addNode({conceptType:o,content:`${r.name}: ${r.description}`,patternId:r.id,metadata:{domain:r.domain,patternType:r.patternType,confidence:r.confidence,successRate:r.successRate}});t++,n.push(s);let c=r.domain||"unknown";i.has(c)||i.set(c,[]),i.get(c).push(s);let l=await this.findDomainNode(r.domain);if(!l){let d=await this.addNode({conceptType:"domain",content:r.domain,metadata:{patternCount:1}});l=await this.getNode(d)}l&&await this.addEdge(s,l.id,"co_occurrence",.8)}catch(a){this.config.debug&&console.error(`[ConceptGraph] Failed to load pattern: ${r.id}`,a)}if(t>0){let r=await this.discoverSameDomainEdges(i),a=await this.pruneEdges();this.config.debug&&console.log(`[ConceptGraph] Discovered ${r} same-domain edges, pruned ${a}`)}return console.log(`[ConceptGraph] Loaded ${t} new patterns (${e.length-t} already existed)`),t}async discoverSameDomainEdges(e){if(this.ensureInitialized(),!this.db)return 0;let t=15,n=5e3,i=0;if(e&&e.size>0)for(let[r,a]of e){let o=this.countDomainSimilarityEdges(r);if(o>=n){console.log(`[ConceptGraph] Domain '${r}' already at edge cap (${o}/${n}), skipping`);continue}let s=new Set(a),c=n-o,d=this.db.prepare("SELECT id, metadata FROM concept_nodes WHERE concept_type IN ('pattern', 'technique')").all().filter(g=>{if(s.has(g.id))return!1;let m=g.metadata?E(g.metadata):{};return String(m.domain||"unknown")===r}),h=this.db.transaction(()=>{let g=0;for(let m of a){let y=0;for(let f of d){if(y>=t||g>=c)break;if(!this.prepared.get("getEdge")?.get(m,f.id)){let I=v();this.prepared.get("insertEdge").run(I,m,f.id,"similarity",.6,1),g++,y++}}if(g>=c)break}for(let m=0;m<a.length&&g<c;m++){let y=0;for(let f=m+1;f<a.length&&g<c&&!(y>=t);f++)if(!this.prepared.get("getEdge")?.get(a[m],a[f])){let I=v();this.prepared.get("insertEdge").run(I,a[m],a[f],"similarity",.6,1),g++,y++}}return g});i+=h()}else{let r=this.db.prepare("SELECT id, metadata FROM concept_nodes WHERE concept_type = 'pattern'").all(),a=new Map;for(let s of r){let c=s.metadata?E(s.metadata):{},l=String(c.domain||"unknown");a.has(l)||a.set(l,[]),a.get(l).push(s)}let o=this.db.transaction(()=>{let s=0;for(let[c,l]of a){let d=this.countDomainSimilarityEdges(c);if(d>=n)continue;let h=0,g=n-d;for(let m=0;m<l.length&&h<g;m++){let y=0;for(let f=m+1;f<l.length&&h<g&&!(y>=t);f++)if(!this.prepared.get("getEdge")?.get(l[m].id,l[f].id)){let I=v();this.prepared.get("insertEdge").run(I,l[m].id,l[f].id,"similarity",.6,1),s++,h++,y++}}}return s});i+=o()}return i}connectToDomainMates(e,t,n,i=10){if(!this.db)return;let r=this.db.prepare(`SELECT id FROM concept_nodes
41
+ WHERE concept_type IN ('pattern', 'technique')
42
+ AND json_extract(metadata, '$.domain') = ?
43
+ AND (pattern_id IS NULL OR pattern_id != ?)
44
+ LIMIT ?`).all(t,n,i);for(let a of r)this.prepared.get("getEdge")?.get(e,a.id)||this.prepared.get("insertEdge").run(v(),e,a.id,"co_occurrence",.4,1)}async loadFailuresAsErrors(e){this.ensureInitialized();let t=0;for(let n of e)try{let i=`error:${n.id}`;if(await this.findNodeByPatternId(i))continue;let a=await this.addNode({conceptType:"error",content:n.failureMode,patternId:i,metadata:{domain:n.domain,sourcePatternId:n.sourcePatternId}});t++,this.connectToDomainMates(a,n.domain,n.sourcePatternId)}catch(i){this.config.debug&&console.error(`[ConceptGraph] Failed to load failure: ${n.id}`,i)}return t}async loadSuccessesAsOutcomes(e){this.ensureInitialized();let t=0;for(let n of e)try{let i=`outcome:${n.id}`;if(await this.findNodeByPatternId(i))continue;let a=await this.addNode({conceptType:"outcome",content:n.description,patternId:i,metadata:{domain:n.domain,sourcePatternId:n.sourcePatternId}});t++,this.connectToDomainMates(a,n.domain,n.sourcePatternId)}catch(i){this.config.debug&&console.error(`[ConceptGraph] Failed to load success: ${n.id}`,i)}return t}countDomainSimilarityEdges(e){return this.db?this.db.prepare(`
41
45
  SELECT COUNT(*) as count FROM concept_edges e
42
46
  JOIN concept_nodes n ON e.source = n.id
43
47
  WHERE e.edge_type = 'similarity'
44
- AND n.concept_type = 'pattern'
48
+ AND n.concept_type IN ('pattern', 'technique')
45
49
  AND json_extract(n.metadata, '$.domain') = ?
46
50
  `).get(e).count:0}async pruneEdges(e=15,t=.3){if(this.ensureInitialized(),!this.db)return 0;let n=0;return n=this.db.transaction(()=>{let r=0,a=this.db.prepare(`
47
51
  DELETE FROM concept_edges
@@ -59,16 +63,37 @@ import{a as W}from"./chunk-XQ6DW5FV.js";import{c as V,d as q}from"./chunk-3SRPFB
59
63
  ORDER BY weight DESC
60
64
  LIMIT -1 OFFSET ?
61
65
  )
62
- `).run(s,e);r+=c.changes}return r})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,r=t.get().count,a={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)a[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:r,byType:a,avgEdgesPerNode:i>0?r/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?D(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function te(d){return new A(d)}ee();function ne(d,e){if(e<0||e>=d.length)return d[0]??0;let t=0,n=d.length-1;for(;t<n;){let i=t+n>>1;if(d[i]<d[t]){let s=d[t];d[t]=d[i],d[i]=s}if(d[n]<d[t]){let s=d[t];d[t]=d[n],d[n]=s}if(d[i]<d[n]){let s=d[i];d[i]=d[n],d[n]=s}let r=d[n],a=t;for(let s=t;s<n;s++)if(d[s]<=r){let c=d[a];d[a]=d[s],d[s]=c,a++}let o=d[a];if(d[a]=d[n],d[n]=o,a===e)return d[a];a<e?t=a+1:n=a-1}return d[t]}var P=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},w=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(p=>this.graph.getConcept(p)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let p of i)this.graph.setActivation(p,t),this.recordActivation(p,t);let r=0,a=t,o=0,s=0;for(;r<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let p=await this.spreadIteration(),l=this.graph.getActiveNodes(this.config.threshold);for(let u of l)u.activationLevel>a&&(a=u.activationLevel);if(l.length===o&&p===0){if(s++,s>=3)break}else s=0;o=l.length,r++}let c=this.graph.getActiveNodes(this.config.threshold).map(p=>({nodeId:p.id,activation:p.activationLevel})).sort((p,l)=>l.activation-p.activation),h=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:r,nodesActivated:c.length,peakActivation:a,activatedNodes:c,novelAssociations:h.map(p=>({source:p.source.id,target:p.target.id,strength:p.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,r=0,a=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let p=U(0,o.length),l=o[p];if(l){let u=this.config.noiseLevel+R()*this.config.noiseLevel*2,m=l.activationLevel,v=Math.min(1,m+u+.3);this.graph.setActivation(l.id,v);let f=await this.spread([l.id],v,s);i+=f.iterations,f.peakActivation>r&&(r=f.peakActivation);for(let b of f.activatedNodes)a.add(b.nodeId);for(let b of f.novelAssociations)n.push(b)}if(Date.now()>=s)break;await this.sleep(50+R()*50)}let c=this.deduplicateAssociations(n),h=Array.from(a).map(p=>{let l=this.graph.getConcept(p);return{nodeId:p,activation:l?.activationLevel??0}}).filter(p=>p.activation>0).sort((p,l)=>l.activation-p.activation);return this.trimHistory(),{iterations:i,nodesActivated:h.length,peakActivation:r,activatedNodes:h,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((a,o)=>o.activationLevel-a.activationLevel).slice(0,i));let r=[];for(let a=0;a<n.length;a++)for(let o=a+1;o<n.length;o++){let s=n[a],c=n[o],h=Math.sqrt(s.activationLevel*c.activationLevel),p=this.graph.getEdge(s.id,c.id),l=this.graph.getEdge(c.id,s.id),u=p!==void 0||l!==void 0,m=p?.weight??l?.weight??0,v=!u||m<.3;h>.3&&(r.push({source:s,target:c,coActivation:h,isNovel:v}),this.trackCoActivation(s.id,c.id))}return r.sort((a,o)=>a.isNovel!==o.isNovel?a.isNovel?-1:1:o.coActivation-a.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=P)return;let e=Math.floor(P*F),t=this.activationHistory.size-e,n=Array.from(this.activationHistory.keys()).slice(0,t);for(let i of n)this.activationHistory.delete(i)}trimCoActivationCounts(){if(this.coActivationCounts.size<=O)return;let e=Math.floor(O*F),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=ne(n,t-1),r=[];for(let[a,o]of this.coActivationCounts){if(r.length>=t)break;o<=i&&r.push(a)}for(let a of r)this.coActivationCounts.delete(a)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let r=this.graph.getEdges(i.id);for(let a of r){let o=this.graph.getConcept(a.target);if(!o)continue;let s=i.activationLevel*a.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,h=Math.min(1,c+s);n.push({nodeId:a.target,newActivation:h})}}}for(let i of n){let r=this.graph.getConcept(i.nodeId);r&&i.newActivation>r.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(R()-.5)*2*this.config.noiseLevel,i=Math.max(0,Math.min(1,t.activationLevel+n));this.graph.setActivation(t.id,i)}}recordActivation(e,t){let n=this.activationHistory.get(e)||[];n.push(t),n.length>50&&n.shift(),this.activationHistory.set(e,n)}trackCoActivation(e,t){let n=[e,t].sort().join(":"),i=this.coActivationCounts.get(n)||0;this.coActivationCounts.set(n,i+1)}deduplicateAssociations(e){let t=new Map;for(let n of e){let i=[n.source,n.target].sort().join(":"),r=t.get(i);(!r||n.strength>r.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ie}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},I=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let r=await this.detectPatternMerges(i);for(let c of r)c.cycleId=e,n.push(c);let a=await this.detectNovelAssociations(t.novelAssociations);for(let c of a)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,h)=>h.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let a=n[i],o=n[r],s=this.graph.getEdge(a.id,o.id),c=this.graph.getEdge(o.id,a.id),h=Math.max(s?.weight??0,c?.weight??0),p=this.calculateContentSimilarity(a.content,o.content),l=Math.sqrt(a.activationLevel*o.activationLevel),u=h*.4+p*.3+l*.3;if(u>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[a.id,o.id]}),v=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[a.id,o.id],edgeWeight:h,contentSimilarity:p,coActivation:l});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[a.id,o.id],description:this.generatePatternMergeDescription(a,o,u),noveltyScore:m,confidenceScore:v,actionable:v>=this.config.minConfidence,applied:!1,suggestedAction:v>=this.config.minConfidence?`Merge "${this.truncate(a.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),r=this.graph.getConcept(n.target);if(!i||!r)continue;let a=this.graph.getEdge(n.source,n.target);if(a&&a.weight>.5)continue;let o=i.conceptType!==r.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,r,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(r.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},r=i.successRate,a=i.executionCount,o=i.confidence,s=r!==void 0&&r<.7,c=a!==void 0&&a>10,h=o!==void 0&&o<.6;if(s||c&&h){let p=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),l=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,r,a),noveltyScore:p,confidenceScore:l,actionable:l>=this.config.minConfidence,applied:!1,suggestedAction:l>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let r=i.conceptType??"pattern";n[r]||(n[r]=[]),n[r].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(r=>r.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ie().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),r=new Set(n),a=new Set(i),o=n.filter(c=>a.has(c)),s=r.size+a.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let r=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${r}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};$();H();G();import{existsSync as re,unlinkSync as ae}from"fs";var T={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},C=class{constructor(e,t=T){this.db=e;this.thresholds=t}db;thresholds;activeBranches=new Map;listeners=[];rvfAdapter;useRvfFork=!1;_witnessChain=null;set witnessChain(e){this._witnessChain=e}setRvfAdapter(e,t=!0){this.rvfAdapter=e,this.useRvfFork=t,import("./feature-flags-DIE3Z2B4.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let p=-r/n.patternCount;p>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(p*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let p=o/n.highConfidenceCount;p>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(p*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let p=this.rvfAdapter.dimension?.()??384,l=new Float32Array(p);for(let m=0;m<p;m++)l[m]=Math.sin(m*.1);let u=this.rvfAdapter.search?.(l,10)??[];u.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${u.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let h=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:h,patternCountDelta:r,avgConfidenceDelta:a,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&re(n)&&ae(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var x=N.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...T}},k=class{constructor(e){this.graph=e}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},_=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=M(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase();try{this.db.pragma("busy_timeout = 60000")}catch{}this.migrateSchema(),this.graph=new A,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new C(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${E(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),x.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),x.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){x.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:y(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new k(this.graph);await a.loadIntoMemory(30);let s=await new w(a,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await a.persistActivations();let h=await new I(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=h.length;for(let l of h)await this.saveInsight(l);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let l=this.branchManager.validateBranch(i);if(l.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,l);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,l);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:l.reason},"dream-engine")}catch{}x.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:l.reason})}i=null}let p={cycle:{...this.currentCycle},insights:h,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,p}catch(r){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=E(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async ensureConceptsLoaded(){if(this.ensureInitialized(),(await this.graph.getActiveNodes(0)).length>=this.config.minConceptsRequired)return 0;let t=this.db.prepare(`SELECT id, name, description, qe_domain as domain, pattern_type as patternType,
63
- confidence, success_rate as successRate
64
- FROM qe_patterns
65
- WHERE confidence >= 0.3
66
- ORDER BY quality_score DESC
67
- LIMIT 200`).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 n=`dream-pattern-${y()}`;return this.db.prepare(`
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-S2RNZATS.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-r/n.patternCount;d>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(d*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let d=o/n.highConfidenceCount;d>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(d*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let d=this.rvfAdapter.dimension?.()??384,h=new Float32Array(d);for(let m=0;m<d;m++)h[m]=Math.sin(m*.1);let g=this.rvfAdapter.search?.(h,10)??[];g.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${g.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let l=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:l,patternCountDelta:r,avgConfidenceDelta:a,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&re(n)&&ae(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var S=R.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...A}},k=class{constructor(e){this.graph=e}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},N=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase();try{this.db.pragma("busy_timeout = 60000")}catch{}this.migrateSchema(),this.graph=new T,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new b(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${C(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),S.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),S.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){S.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:v(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new k(this.graph);await a.loadIntoMemory(30);let s=await new w(a,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await a.persistActivations();let l=await new _(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=l.length;for(let h of l)await this.saveInsight(h);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let h=this.branchManager.validateBranch(i);if(h.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,h);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,h);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:h.reason},"dream-engine")}catch{}S.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:h.reason})}i=null}let d={cycle:{...this.currentCycle},insights:l,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(r){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=C(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async loadFailuresAsConcepts(e){return this.ensureInitialized(),this.graph.loadFailuresAsErrors(e)}async loadSuccessesAsConcepts(e){return this.ensureInitialized(),this.graph.loadSuccessesAsOutcomes(e)}async ensureConceptsLoaded(){this.ensureInitialized();try{let n=this.db.prepare(`SELECT n.id as id, n.pattern_id as sourcePatternId, p.qe_domain as domain, n.failure_mode as failureMode
67
+ FROM qe_pattern_nulls n
68
+ JOIN qe_patterns p ON p.id = n.pattern_id
69
+ ORDER BY n.updated_at DESC
70
+ LIMIT 100`).all();n.length>0&&await this.graph.loadFailuresAsErrors(n);let i=this.db.prepare(`SELECT u.id as id, u.pattern_id as sourcePatternId, p.qe_domain as domain,
71
+ ('Pattern "' || p.name || '" applied successfully') as description
72
+ FROM qe_pattern_usage u
73
+ JOIN qe_patterns p ON p.id = u.pattern_id
74
+ WHERE u.success = 1
75
+ ORDER BY u.created_at DESC
76
+ LIMIT 100`).all();i.length>0&&await this.graph.loadSuccessesAsOutcomes(i)}catch(n){process.env.DEBUG&&S.debug("Error/outcome concept loading skipped",{error:C(n)})}if((await this.graph.getActiveNodes(0)).length>=this.config.minConceptsRequired)return 0;let t=this.db.prepare(`SELECT * FROM (
77
+ SELECT id, name, description, qe_domain as domain, pattern_type as patternType,
78
+ confidence, success_rate as successRate
79
+ FROM qe_patterns
80
+ WHERE confidence >= 0.3
81
+ ORDER BY quality_score DESC
82
+ LIMIT 160
83
+ )
84
+ UNION
85
+ SELECT * FROM (
86
+ SELECT id, name, description, qe_domain as domain, pattern_type as patternType,
87
+ confidence, success_rate as successRate
88
+ FROM qe_patterns
89
+ WHERE confidence >= 0.3 AND success_rate < 0.7
90
+ ORDER BY usage_count DESC
91
+ LIMIT 40
92
+ )`).all();return t.length===0?0:this.graph.loadFromPatterns(t)}async applyInsight(e){this.ensureInitialized();try{let t=await this.getInsightRowById(e);if(!t)return{success:!1,error:`Insight not found: ${e}`};if(t.actionable!==1)return{success:!1,error:"Insight is not actionable"};if(t.applied===1)return{success:!0,patternId:t.pattern_id??void 0,error:"Insight already applied"};let{getSharedMemoryBackend:n}=await import("./base-2CKCJU3O.js"),{createQEReasoningBank:i}=await import("./qe-reasoning-bank-RCEYSLVV.js"),r=await n(),a=i(r);await a.initialize();try{let{getSharedRvfDualWriter:d}=await import("./shared-rvf-dual-writer-SZW3J7ZK.js"),h=await d();h&&a.setRvfDualWriter(h)}catch(d){process.env.DEBUG&&S.debug("RVF wiring skipped",{error:C(d)})}let o=[];try{o=E(t.source_concepts)}catch{}let s=await a.storePattern({patternType:se(t.insight_type),name:`Dream Insight: ${t.insight_type}`,description:`${t.description} (confidence: ${t.confidence_score.toFixed(2)})`,template:{type:"workflow",content:t.suggested_action||t.description,variables:[]},context:{tags:["dream-generated",t.insight_type,...o.slice(0,3)],complexity:"medium"}});if(!s.success)return{success:!1,error:`Failed to create pattern: ${s.error?.message??"unknown error"}`};let c=s.value.id;return this.db.prepare(`
68
93
  UPDATE dream_insights
69
94
  SET applied = 1, pattern_id = ?
70
95
  WHERE id = ?
71
- `).run(n,e),{success:!0,patternId:n}}catch(t){return{success:!1,error:E(t)}}}async getPendingInsights(e){this.ensureInitialized();let t=e??20;return this.db.prepare(`
96
+ `).run(c,e),{success:!0,patternId:c}}catch(t){return{success:!1,error:C(t)}}}async getPendingInsights(e){this.ensureInitialized();let t=e??20;return this.db.prepare(`
72
97
  SELECT * FROM dream_insights
73
98
  WHERE applied = 0 AND actionable = 1
74
99
  ORDER BY novelty_score DESC, confidence_score DESC
@@ -92,4 +117,4 @@ import{a as W}from"./chunk-XQ6DW5FV.js";import{c as V,d as q}from"./chunk-3SRPFB
92
117
  (id, cycle_id, insight_type, source_concepts, description, novelty_score,
93
118
  confidence_score, actionable, applied, suggested_action, pattern_id)
94
119
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
95
- `).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:D(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function se(d){let e=new _(d);return import("./feature-flags-DIE3Z2B4.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-TYD5TQ35.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var oe=_;G();var Y="learning:loop-health";async function J(d,e,t){try{let n=new Date().toISOString(),i=await d.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await d.set(Y,i)}catch{}}var g=N.create("DreamScheduler"),Z={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},K="dream-scheduler:hook-state",L=class d{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Z,...t},this.metaLearningEngine=new q}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,g.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),g.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),g.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,g.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(g.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{g.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,g.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&g.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){g.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),g.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&g.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){g.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-TYD5TQ35.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&g.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){g.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-YGOOVDQZ.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&g.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){g.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new W,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>d.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){g.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)g.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>d.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:y(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{g.debug("Failed to publish meta-learning insight event")}}}else g.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),g.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){g.info("Quality gate failed but cannot start dream yet");return}g.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){g.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){g.info("Milestone reached but cannot start dream yet");return}g.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:y(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){g.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(K),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(K,t)}catch(e){g.warn("Dream hook-state reconcile failed (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){g.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],g.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){g.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function ce(d,e){return new L(d,e)}var de=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],z=class{constructor(e,t){this.db=e;this.branchManager=new C(e,t??T)}db;branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,h)=>{let p=this.scoreValidation(c.validation);return this.scoreValidation(h.validation)>p?h:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,Z as b,L as c,ce as d,B as e,A as f,te as g,P as h,O as i,F as j,j as k,w as l,Q as m,I as n,T as o,C as p,X as q,_ as r,se as s,oe as t,de as u,z as v};
120
+ `).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:E(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function se(p){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[p]||"test-template"}function oe(p){let e=new N(p);return import("./feature-flags-S2RNZATS.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-WLRKI7RY.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-WLRKI7RY.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-SZW3J7ZK.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&u.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){u.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new q,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>p.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){u.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)u.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>p.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:v(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{u.debug("Failed to publish meta-learning insight event")}}}else u.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),u.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){u.info("Quality gate failed but cannot start dream yet");return}u.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){u.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){u.info("Milestone reached but cannot start dream yet");return}u.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:v(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){u.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(K),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(K,t)}catch(e){u.warn("Dream hook-state reconcile failed (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){u.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],u.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){u.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function de(p,e){return new L(p,e)}var pe=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],z=class{constructor(e,t){this.db=e;this.branchManager=new b(e,t??A)}db;branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,l)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(l.validation)>d?l:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,P as b,T as c,te as d,B as e,O as f,F as g,j as h,w as i,Q as j,_ as k,A as l,b as m,X as n,N as o,oe as p,ce as q,pe as r,z as s,Z as t,L as u,de as v};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.4");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.12.0");process.exit(0)}
2
2
  function M(u){let e=u|0;return()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}var A=2,y=10,x=200,p=1e-8,b=class{epsilon;seed;constructor(e){if(this.epsilon=e?.epsilon??.3,this.seed=e?.seed,this.epsilon<=0||this.epsilon>=1)throw new Error("SparsifierConfig.epsilon must be in (0, 1)")}sparsify(e){if(e.nodeCount<=0||e.edges.length===0)return{nodeCount:e.nodeCount,edges:[]};let n=this.seed!==void 0?M(this.seed):Math.random,t=this.approximateEffectiveResistances(e),i=e.nodeCount,r=e.edges.length,o=Math.max(1,Math.log(i)),m=this.epsilon*this.epsilon,l=Math.min(r,Math.max(i-1,A*(i-1)*(1-this.epsilon))),s=new Float64Array(r),c=0;for(let a=0;a<r;a++){let d=e.edges[a][2];s[a]=d*t[a],c+=s[a]}if(c<=0)return{nodeCount:e.nodeCount,edges:[]};let f=[];for(let a=0;a<r;a++){let[d,C,E]=e.edges[a],g=Math.min(1,s[a]/c*l);if(n()<g){let w=E/g;f.push([d,C,w])}}return{nodeCount:e.nodeCount,edges:f}}validateSpectral(e,n){let t=Math.min(y,Math.max(1,e.nodeCount-1)),i=this.computeLaplacian(e),r=this.computeLaplacian(n),o=this.computeTopEigenvalues(i,t),m=this.computeTopEigenvalues(r,t),l=[],s=!0,c=this.epsilon;for(let f=0;f<o.length;f++){if(o[f]<1e-10)continue;let a=m[f]/o[f];l.push(a),(a<1-c||a>1+c)&&(s=!1)}return{isValid:s,eigenvalueRatios:l,originalEdgeCount:e.edges.length,sparsifiedEdgeCount:n.edges.length,compressionRatio:e.edges.length>0?n.edges.length/e.edges.length:0}}computeLaplacian(e){let n=e.nodeCount,t=Array.from({length:n},()=>new Array(n).fill(0));for(let[i,r,o]of e.edges)i<0||i>=n||r<0||r>=n||(t[i][i]+=o,t[r][r]+=o,t[i][r]-=o,t[r][i]-=o);return t}computeTopEigenvalues(e,n){let t=e.length;if(t===0)return[];let i=[],r=[],o=e.map(m=>[...m]);for(let m=0;m<Math.min(n,t);m++){let l=this.powerIteration(o,t,r);if(l===null)break;i.push(l.eigenvalue),r.push(l.eigenvector),V(o,l.eigenvalue,l.eigenvector)}return i}approximateEffectiveResistances(e){let n=e.nodeCount,t=new Float64Array(n);for(let[r,o,m]of e.edges)r>=0&&r<n&&(t[r]+=m),o>=0&&o<n&&(t[o]+=m);let i=new Array(e.edges.length);for(let r=0;r<e.edges.length;r++){let[o,m]=e.edges[r],l=t[o]||1,s=t[m]||1;i[r]=1/l+1/s}return i}powerIteration(e,n,t){let i=0;for(let s=0;s<n;s++)for(let c=0;c<n;c++)i+=e[s][c]*e[s][c];if(i<p*p)return null;let r=t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]=Math.sin((s+1)*(r+1)*1.618033988749895)+.1*(s-n/2);for(let s of t)h(o,s);if(R(o)<p)return null;let l=0;for(let s=0;s<x;s++){let c=L(e,o);for(let d of t)h(c,d);let f=S(c,o),a=v(c);if(a<p)return{eigenvalue:0,eigenvector:o};for(let d=0;d<n;d++)o[d]=c[d]/a;if(Math.abs(f-l)<p){l=f;break}l=f}return{eigenvalue:Math.abs(l),eigenvector:o}}};function L(u,e){let n=u.length,t=new Array(n).fill(0);for(let i=0;i<n;i++){let r=0;for(let o=0;o<n;o++)r+=u[i][o]*e[o];t[i]=r}return t}function v(u){let e=0;for(let n=0;n<u.length;n++)e+=u[n]*u[n];return Math.sqrt(e)}function R(u){let e=v(u);if(e>0)for(let n=0;n<u.length;n++)u[n]/=e;return e}function S(u,e){let n=0;for(let t=0;t<u.length;t++)n+=u[t]*e[t];return n}function h(u,e){let n=S(u,e);for(let t=0;t<u.length;t++)u[t]-=n*e[t]}function V(u,e,n){let t=n.length;for(let i=0;i<t;i++)for(let r=0;r<t;r++)u[i][r]-=e*n[i]*n[r]}export{b as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.4");process.exit(0)}
2
- import{e as l,k as i}from"./chunk-ZSA6V5FH.js";import{a as r,c as g}from"./chunk-PEIQDQXN.js";g();var c=class extends i{config={name:"qe/tests/schedule",description:"Schedule and execute tests using phase-based pipeline with git-aware selection and flaky tracking. Runs tests in phases (unit, integration, e2e), selects affected tests from git changes, and tracks flaky tests.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{cwd:{type:"string",description:"Working directory for test execution (defaults to project root)"},gitRef:{type:"string",description:'Git ref to compare for affected test selection (e.g., "main", "HEAD~3")'},useGitAware:{type:"boolean",description:"Enable git-aware test selection to only run affected tests",default:!0},trackFlaky:{type:"boolean",description:"Enable flaky test tracking and quarantine",default:!0}}}}async execute(s,o){try{let{runTestPipeline:n}=await import("./test-scheduling-EFZA5G5C.js"),d=await l(o),t=await n({cwd:s.cwd||process.cwd(),memory:d,baseRef:s.gitRef,flakyHistoryPath:s.trackFlaky!==!1?".agentic-qe/flaky-history.json":void 0,runAllTests:s.useGitAware===!1}),u=t.phaseResults.reduce((e,a)=>e+a.totalTests,0),f=t.phaseResults.reduce((e,a)=>e+a.passed,0),p=t.phaseResults.reduce((e,a)=>e+a.failed,0);return{success:!0,data:{pipelineId:o.requestId,phases:t.phaseResults.map(e=>({phaseId:e.phaseId,phaseName:e.phaseName,totalTests:e.totalTests,passed:e.passed,failed:e.failed,passRate:e.passRate,durationMs:e.durationMs})),gitAware:{enabled:!t.ranAllTests,selectedTests:t.selectedTests.length,gitRef:s.gitRef},flakyTracking:{enabled:s.trackFlaky!==!1},totalDuration:t.totalDurationMs,ranAllTests:t.ranAllTests,summary:`Executed ${t.phaseResults.length} phases, ${u} tests (${f} passed, ${p} failed) in ${t.totalDurationMs}ms`}}}catch(n){return{success:!1,error:r(n)}}}};export{c as a};
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.12.0");process.exit(0)}
2
+ import{e as l,l as i}from"./chunk-7WX3MKRS.js";import{a as r,c as g}from"./chunk-RHC7TFPU.js";g();var c=class extends i{config={name:"qe/tests/schedule",description:"Schedule and execute tests using phase-based pipeline with git-aware selection and flaky tracking. Runs tests in phases (unit, integration, e2e), selects affected tests from git changes, and tracks flaky tests.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{cwd:{type:"string",description:"Working directory for test execution (defaults to project root)"},gitRef:{type:"string",description:'Git ref to compare for affected test selection (e.g., "main", "HEAD~3")'},useGitAware:{type:"boolean",description:"Enable git-aware test selection to only run affected tests",default:!0},trackFlaky:{type:"boolean",description:"Enable flaky test tracking and quarantine",default:!0}}}}async execute(s,o){try{let{runTestPipeline:n}=await import("./test-scheduling-OTN3DMKY.js"),d=await l(o),t=await n({cwd:s.cwd||process.cwd(),memory:d,baseRef:s.gitRef,flakyHistoryPath:s.trackFlaky!==!1?".agentic-qe/flaky-history.json":void 0,runAllTests:s.useGitAware===!1}),u=t.phaseResults.reduce((e,a)=>e+a.totalTests,0),f=t.phaseResults.reduce((e,a)=>e+a.passed,0),p=t.phaseResults.reduce((e,a)=>e+a.failed,0);return{success:!0,data:{pipelineId:o.requestId,phases:t.phaseResults.map(e=>({phaseId:e.phaseId,phaseName:e.phaseName,totalTests:e.totalTests,passed:e.passed,failed:e.failed,passRate:e.passRate,durationMs:e.durationMs})),gitAware:{enabled:!t.ranAllTests,selectedTests:t.selectedTests.length,gitRef:s.gitRef},flakyTracking:{enabled:s.trackFlaky!==!1},totalDuration:t.totalDurationMs,ranAllTests:t.ranAllTests,summary:`Executed ${t.phaseResults.length} phases, ${u} tests (${f} passed, ${p} failed) in ${t.totalDurationMs}ms`}}}catch(n){return{success:!1,error:r(n)}}}};export{c as a};