agentic-qe 3.15.13 → 3.15.14

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 (409) hide show
  1. package/.claude/helpers/brain-checkpoint.cjs +124 -5
  2. package/.claude/skills/skills-manifest.json +1 -1
  3. package/CHANGELOG.md +78 -0
  4. package/assets/skills/skills-manifest.json +1 -1
  5. package/dist/cli/bundle.js +6 -6
  6. package/dist/cli/chunks/adapter-23KA2YW7.js +2 -0
  7. package/dist/cli/chunks/{agent-booster-wasm-6RRQWMNE.js → agent-booster-wasm-2DLAEZK6.js} +2 -2
  8. package/dist/cli/chunks/{agent-handler-AOH6TV7W.js → agent-handler-P3IY7XEE.js} +2 -2
  9. package/dist/cli/chunks/{agent-memory-branch-2P54SF5N.js → agent-memory-branch-WWKC2H3G.js} +2 -2
  10. package/dist/cli/chunks/aqe-learning-engine-MUICAXW5.js +2 -0
  11. package/dist/cli/chunks/{arena-X6MOGQHA.js → arena-4BMFF6BS.js} +4 -4
  12. package/dist/cli/chunks/{arena-NSVFCAF5.js → arena-EIV5OALF.js} +2 -2
  13. package/dist/cli/chunks/{audit-27DJLQNM.js → audit-DNTI453H.js} +3 -3
  14. package/dist/cli/chunks/base-XPWGYDKD.js +2 -0
  15. package/dist/cli/chunks/{better-sqlite3-BU5GXILS.js → better-sqlite3-TQBQGNC6.js} +2 -2
  16. package/dist/cli/chunks/brain-handler-HY57CNAO.js +95 -0
  17. package/dist/cli/chunks/{branch-enumerator-5CLULOCU.js → branch-enumerator-THPMZPHQ.js} +2 -2
  18. package/dist/cli/chunks/{browser-R4DMU3LN.js → browser-O6JJOZCK.js} +2 -2
  19. package/dist/cli/chunks/browser-workflow-UMQVBVGK.js +2 -0
  20. package/dist/cli/chunks/{chunk-VU5TBX2V.js → chunk-2HPNGK7A.js} +2 -2
  21. package/dist/cli/chunks/{chunk-5FKWCZNF.js → chunk-2IJO3657.js} +2 -2
  22. package/dist/cli/chunks/{chunk-K3TLLJMX.js → chunk-2QLE6NDW.js} +1 -1
  23. package/dist/cli/chunks/{chunk-J2ZIFFM6.js → chunk-2UZBLC5H.js} +2 -2
  24. package/dist/cli/chunks/{chunk-HD7YIFOI.js → chunk-2W5MQDHM.js} +2 -2
  25. package/dist/cli/chunks/{chunk-F3YS57NF.js → chunk-3FITMWWJ.js} +2 -2
  26. package/dist/cli/chunks/{chunk-K4CZA77U.js → chunk-3TF27MG5.js} +2 -2
  27. package/dist/cli/chunks/{chunk-BLSLEVDI.js → chunk-3XACRXBY.js} +2 -2
  28. package/dist/cli/chunks/{chunk-A64JFBWI.js → chunk-43XHGWYH.js} +2 -2
  29. package/dist/cli/chunks/{chunk-42J34YG4.js → chunk-4RPBODN5.js} +2 -2
  30. package/dist/cli/chunks/{chunk-W26B7ERY.js → chunk-4T7XV5KQ.js} +1 -1
  31. package/dist/cli/chunks/{chunk-SSU73QAX.js → chunk-4WLIOPHX.js} +2 -2
  32. package/dist/cli/chunks/{chunk-P7A4NKTZ.js → chunk-52KOPIMI.js} +2 -2
  33. package/dist/cli/chunks/{chunk-HQZGPJYG.js → chunk-56NSE3LJ.js} +2 -2
  34. package/dist/cli/chunks/{chunk-AQSVJNEH.js → chunk-57DRT6UA.js} +2 -2
  35. package/dist/cli/chunks/{chunk-M6AAGIG7.js → chunk-57FX3GP6.js} +1 -1
  36. package/dist/cli/chunks/{chunk-O6FGXMHD.js → chunk-5PLBQZ5J.js} +1 -1
  37. package/dist/cli/chunks/{chunk-ASQYASNV.js → chunk-5Y7UFHJD.js} +1 -1
  38. package/dist/cli/chunks/{chunk-5VMAV6T6.js → chunk-5Z4MO2F3.js} +1 -1
  39. package/dist/cli/chunks/chunk-65EE2EST.js +8 -0
  40. package/dist/cli/chunks/{chunk-7CMTY45A.js → chunk-6NIGSY5L.js} +2 -2
  41. package/dist/cli/chunks/chunk-6O63ZTVX.js +3 -0
  42. package/dist/cli/chunks/{chunk-FZ76G4QJ.js → chunk-6OI5SK7M.js} +1 -1
  43. package/dist/cli/chunks/{chunk-5ZGM3RMH.js → chunk-6P4Q4RTC.js} +1 -1
  44. package/dist/cli/chunks/{chunk-LUZNKJE6.js → chunk-7724KXM2.js} +3 -3
  45. package/dist/cli/chunks/{chunk-XPRVF4YE.js → chunk-7MISCSL5.js} +2 -2
  46. package/dist/cli/chunks/{chunk-TCBBNUBP.js → chunk-7MUO4DEH.js} +3 -3
  47. package/dist/cli/chunks/{chunk-NT4DBXSX.js → chunk-7QUSNBAA.js} +2 -2
  48. package/dist/cli/chunks/{chunk-TWDW32W2.js → chunk-7SQTLUEN.js} +2 -2
  49. package/dist/cli/chunks/{chunk-QPNG5ZN2.js → chunk-7T6L3LFN.js} +2 -2
  50. package/dist/cli/chunks/{chunk-E56B6IDX.js → chunk-7TH4PJSU.js} +2 -2
  51. package/dist/cli/chunks/{chunk-LZYQHVD4.js → chunk-7Y3LXH57.js} +2 -2
  52. package/dist/cli/chunks/{chunk-YQFLQE53.js → chunk-A2T56XVL.js} +2 -2
  53. package/dist/cli/chunks/{chunk-KV4T4MXK.js → chunk-AJVLVF7V.js} +2 -2
  54. package/dist/cli/chunks/{chunk-VTDFVFST.js → chunk-ARRBXCII.js} +2 -2
  55. package/dist/cli/chunks/{chunk-G6WDYBLQ.js → chunk-AYLEH2UF.js} +1 -1
  56. package/dist/cli/chunks/{chunk-526QYFJU.js → chunk-BBYJBZHG.js} +2 -2
  57. package/dist/cli/chunks/{chunk-CM4LSLKR.js → chunk-BM3EJLMV.js} +2 -2
  58. package/dist/cli/chunks/{chunk-DVGRPK7A.js → chunk-BNG4J3CE.js} +2 -2
  59. package/dist/cli/chunks/{chunk-BK577VL7.js → chunk-BPDAQB3F.js} +2 -2
  60. package/dist/cli/chunks/{chunk-C6JTLKG7.js → chunk-BQJ7CV53.js} +9 -9
  61. package/dist/cli/chunks/{chunk-GB6HBNH2.js → chunk-C3OIBFAA.js} +2 -2
  62. package/dist/cli/chunks/{chunk-RF7HWBHN.js → chunk-CAZM63TP.js} +2 -2
  63. package/dist/cli/chunks/{chunk-KWYH3FI4.js → chunk-CIINJHOX.js} +1 -1
  64. package/dist/cli/chunks/{chunk-ARJW4I2O.js → chunk-CPPYZYXC.js} +2 -2
  65. package/dist/cli/chunks/{chunk-CRWPZT74.js → chunk-D3ZZ2NLL.js} +2 -2
  66. package/dist/cli/chunks/{chunk-Q3UDLV5Z.js → chunk-D5GB5PUU.js} +1 -1
  67. package/dist/cli/chunks/{chunk-7PLIEBY7.js → chunk-DLTB5KCR.js} +2 -2
  68. package/dist/cli/chunks/{chunk-YZWBNBTW.js → chunk-DRLSJJIC.js} +2 -2
  69. package/dist/cli/chunks/{chunk-BEGR4D6N.js → chunk-DSQESXL4.js} +2 -2
  70. package/dist/cli/chunks/{chunk-72ASBE35.js → chunk-E2JLAW3U.js} +3 -3
  71. package/dist/cli/chunks/{chunk-MAMQA43L.js → chunk-E3QIQMMN.js} +1 -1
  72. package/dist/cli/chunks/{chunk-WOCGL4QP.js → chunk-E7OR6V3V.js} +2 -2
  73. package/dist/cli/chunks/{chunk-MVVB7C2E.js → chunk-E7QTWGPI.js} +156 -156
  74. package/dist/cli/chunks/{chunk-JQGMW45H.js → chunk-EC65UZ77.js} +1 -1
  75. package/dist/cli/chunks/{chunk-YXRASAPI.js → chunk-EIEEST4T.js} +2 -2
  76. package/dist/cli/chunks/{chunk-AL6FBH3E.js → chunk-FHPNWHY7.js} +2 -2
  77. package/dist/cli/chunks/{chunk-C7JM7CD3.js → chunk-FJOIBZUB.js} +2 -2
  78. package/dist/cli/chunks/{chunk-LL7LDPXS.js → chunk-FTYRPEJS.js} +1 -1
  79. package/dist/cli/chunks/{chunk-MFW5HSG4.js → chunk-G7HGUQAE.js} +2 -2
  80. package/dist/cli/chunks/{chunk-WQL7WCIZ.js → chunk-GY4P7KAI.js} +1 -1
  81. package/dist/cli/chunks/{chunk-3YNLWPBF.js → chunk-H3C5FJRH.js} +2 -2
  82. package/dist/cli/chunks/{chunk-W3INMZZ6.js → chunk-H4LYXLAT.js} +1 -1
  83. package/dist/cli/chunks/{chunk-W3PPFHI5.js → chunk-HAYKLXCT.js} +52 -50
  84. package/dist/cli/chunks/{chunk-XNBOGCF3.js → chunk-HEDGFKC5.js} +2 -2
  85. package/dist/cli/chunks/{chunk-SYV2V3PL.js → chunk-HHBF2BZC.js} +4 -4
  86. package/dist/cli/chunks/{chunk-75RDHBAX.js → chunk-HSDWPQQY.js} +3 -3
  87. package/dist/cli/chunks/{chunk-6KATY3KS.js → chunk-HTVGHHX2.js} +2 -2
  88. package/dist/cli/chunks/{chunk-VRVMIPTM.js → chunk-HV43NX4A.js} +2 -2
  89. package/dist/cli/chunks/{chunk-RFNW2LGD.js → chunk-IDBA5GK2.js} +2 -2
  90. package/dist/cli/chunks/{chunk-DNDL7SOS.js → chunk-INGXD5IX.js} +2 -2
  91. package/dist/cli/chunks/{chunk-IJUHSJ2U.js → chunk-IQRPR4KB.js} +2 -2
  92. package/dist/cli/chunks/{chunk-UOC3O6RP.js → chunk-IRPNEXOU.js} +2 -2
  93. package/dist/cli/chunks/{chunk-KDVZND5Q.js → chunk-J35JWDJE.js} +1 -1
  94. package/dist/cli/chunks/{chunk-CV77DMDQ.js → chunk-J6ASX536.js} +2 -2
  95. package/dist/cli/chunks/{chunk-7YTGHGK4.js → chunk-JAOCHPYX.js} +2 -2
  96. package/dist/cli/chunks/{chunk-HZ5NXFXH.js → chunk-JB7R77SH.js} +2 -2
  97. package/dist/cli/chunks/{chunk-PB6J6HAA.js → chunk-JI67T6Q2.js} +2 -2
  98. package/dist/cli/chunks/{chunk-E7CLYGS7.js → chunk-JJHLGGPP.js} +1 -1
  99. package/dist/cli/chunks/{chunk-3Y7TJFHU.js → chunk-JK6PMLQQ.js} +2 -2
  100. package/dist/cli/chunks/{chunk-CCMKSHAT.js → chunk-JO26SG47.js} +2 -2
  101. package/dist/cli/chunks/{chunk-NU3W5WFT.js → chunk-JSSU4RIK.js} +2 -2
  102. package/dist/cli/chunks/{chunk-756CGMEH.js → chunk-K2SMP4OD.js} +1 -1
  103. package/dist/cli/chunks/{chunk-OCAEXYFA.js → chunk-K7GFYFBO.js} +2 -2
  104. package/dist/cli/chunks/{chunk-VRHRBAEM.js → chunk-K7RT6ITZ.js} +1 -1
  105. package/dist/cli/chunks/{chunk-LFJALJOA.js → chunk-KJ5A54ZH.js} +2 -2
  106. package/dist/cli/chunks/{chunk-3Y2ROSCL.js → chunk-L5VSLPMW.js} +2 -2
  107. package/dist/cli/chunks/{chunk-WKGTGOYS.js → chunk-L752CNG3.js} +3 -3
  108. package/dist/cli/chunks/{chunk-IC3TQEOA.js → chunk-L7PC675Y.js} +1 -1
  109. package/dist/cli/chunks/{chunk-TOQWL2ZF.js → chunk-LTGQJYYO.js} +2 -2
  110. package/dist/cli/chunks/{chunk-SVLQRAMF.js → chunk-M2TG7VDK.js} +1 -1
  111. package/dist/cli/chunks/{chunk-X7N2JF2X.js → chunk-M5JEA6ZY.js} +2 -2
  112. package/dist/cli/chunks/{chunk-GHM6MQNK.js → chunk-MB4UKUBV.js} +2 -2
  113. package/dist/cli/chunks/{chunk-R7SYRCRP.js → chunk-MKYOE7NE.js} +1 -1
  114. package/dist/cli/chunks/{chunk-3AN5TNGD.js → chunk-MQXWG55U.js} +3 -3
  115. package/dist/cli/chunks/{chunk-3QZEGE67.js → chunk-MR2OPUSA.js} +1 -1
  116. package/dist/cli/chunks/{chunk-6Z7PRBSG.js → chunk-N736GLWZ.js} +2 -2
  117. package/dist/cli/chunks/{chunk-PIDQVU3L.js → chunk-NHEG2DLN.js} +2 -2
  118. package/dist/cli/chunks/chunk-NKOLILT7.js +86 -0
  119. package/dist/cli/chunks/{chunk-UXZSUMEA.js → chunk-NPCXGX7N.js} +2 -2
  120. package/dist/cli/chunks/{chunk-XEAEYC6Y.js → chunk-NZQYJCO6.js} +1 -1
  121. package/dist/cli/chunks/{chunk-G77ERMUD.js → chunk-O2AAYJUV.js} +1 -1
  122. package/dist/cli/chunks/{chunk-H4GG2NLO.js → chunk-O32BFQV4.js} +2 -2
  123. package/dist/cli/chunks/{chunk-3LJ7LQMV.js → chunk-O3ERGUXH.js} +1 -1
  124. package/dist/cli/chunks/{chunk-QDEJ4CI2.js → chunk-O5CEL447.js} +2 -2
  125. package/dist/cli/chunks/{chunk-W2QWSQVE.js → chunk-O756AOUX.js} +2 -2
  126. package/dist/cli/chunks/{chunk-PSFSPGUD.js → chunk-OCN53CCK.js} +2 -2
  127. package/dist/cli/chunks/{chunk-KCW47QR5.js → chunk-OGEIHS76.js} +1 -1
  128. package/dist/cli/chunks/{chunk-3RZV5DGO.js → chunk-OLUOVNUF.js} +2 -2
  129. package/dist/cli/chunks/{chunk-KADFXPPN.js → chunk-P2TPH3TC.js} +2 -2
  130. package/dist/cli/chunks/{chunk-7NA7JXNB.js → chunk-PCQZIAXB.js} +2 -2
  131. package/dist/cli/chunks/{chunk-HOAJUIBQ.js → chunk-PGN4TARY.js} +2 -2
  132. package/dist/cli/chunks/{chunk-KB56CPU4.js → chunk-PNRPVQGI.js} +2 -2
  133. package/dist/cli/chunks/{chunk-CE7B5LU7.js → chunk-PWQWKYBG.js} +1 -1
  134. package/dist/cli/chunks/{chunk-DLD7RUZ4.js → chunk-QNQE3EOH.js} +2 -2
  135. package/dist/cli/chunks/chunk-QP2HLKTS.js +2 -0
  136. package/dist/cli/chunks/{chunk-H4H2YSFH.js → chunk-QP6GL3O5.js} +1 -1
  137. package/dist/cli/chunks/{chunk-LWR3FV3Y.js → chunk-QUZ745UQ.js} +2 -2
  138. package/dist/cli/chunks/{chunk-X2Z7F4EU.js → chunk-R5RRWLRI.js} +2 -2
  139. package/dist/cli/chunks/{chunk-NURIILUB.js → chunk-RE6JTSDM.js} +1 -1
  140. package/dist/cli/chunks/{chunk-YSZ5OE3Z.js → chunk-TOJF3ZG4.js} +2 -2
  141. package/dist/cli/chunks/{chunk-7JUC2MVZ.js → chunk-TSP6SU5V.js} +2 -2
  142. package/dist/cli/chunks/{chunk-NW7IBHJA.js → chunk-TW6Z6W4X.js} +4 -4
  143. package/dist/cli/chunks/{chunk-UDQSYWVF.js → chunk-TWOV3I3A.js} +1 -1
  144. package/dist/cli/chunks/chunk-U4TML2VD.js +3 -0
  145. package/dist/cli/chunks/{chunk-WO274FRI.js → chunk-U6IOQKCT.js} +2 -2
  146. package/dist/cli/chunks/{chunk-KDNJ4F3P.js → chunk-UDSB3XCG.js} +2 -2
  147. package/dist/cli/chunks/{chunk-SG3NX7QE.js → chunk-UFP7SN5V.js} +2 -2
  148. package/dist/cli/chunks/{chunk-UTRV7T2N.js → chunk-UMHFTQTR.js} +2 -2
  149. package/dist/cli/chunks/{chunk-4OVC4RIL.js → chunk-UNYTHZDZ.js} +1 -1
  150. package/dist/cli/chunks/{chunk-32ZMWEP3.js → chunk-UPWLMIDY.js} +2 -2
  151. package/dist/cli/chunks/{chunk-T3PGQFDI.js → chunk-USAKCGHC.js} +2 -2
  152. package/dist/cli/chunks/{chunk-2G7TVT6W.js → chunk-V3MGY76S.js} +2 -2
  153. package/dist/cli/chunks/{chunk-ZAKQLAHT.js → chunk-V6SE2ZU2.js} +1 -1
  154. package/dist/cli/chunks/{chunk-SE4VNN4I.js → chunk-VCVRZD4Y.js} +3 -3
  155. package/dist/cli/chunks/{chunk-PHP5UBT4.js → chunk-VG32EEUG.js} +2 -2
  156. package/dist/cli/chunks/{chunk-YZEXYO4W.js → chunk-VGZOPQQY.js} +1 -1
  157. package/dist/cli/chunks/{chunk-OFACHK5O.js → chunk-VJBJRFUO.js} +2 -2
  158. package/dist/cli/chunks/{chunk-NZ3GUMB2.js → chunk-WBC6WB32.js} +2 -2
  159. package/dist/cli/chunks/{chunk-GHY6Z6KO.js → chunk-WCM6WE7G.js} +3 -3
  160. package/dist/cli/chunks/{chunk-NZD4DPSU.js → chunk-WCPSR4MJ.js} +2 -2
  161. package/dist/cli/chunks/{chunk-I3C7JOXC.js → chunk-WKI46WWN.js} +2 -2
  162. package/dist/cli/chunks/{chunk-5K26BEYB.js → chunk-WM2QRIRD.js} +2 -2
  163. package/dist/cli/chunks/{chunk-U2FUXDDJ.js → chunk-WRC3HLUY.js} +3 -3
  164. package/dist/cli/chunks/{chunk-GII6UM3F.js → chunk-WUGXXNK4.js} +1 -1
  165. package/dist/cli/chunks/{chunk-JGZ722G3.js → chunk-WZQADC5R.js} +2 -2
  166. package/dist/cli/chunks/{chunk-GU5HNCWI.js → chunk-X6NJOT3V.js} +1 -1
  167. package/dist/cli/chunks/{chunk-DFUASIKA.js → chunk-X6Q2N5S5.js} +2 -2
  168. package/dist/cli/chunks/{chunk-G2Q66Z23.js → chunk-X7CUI7KH.js} +2 -2
  169. package/dist/cli/chunks/{chunk-5MDERQH3.js → chunk-XMCSKYDE.js} +1 -1
  170. package/dist/cli/chunks/{chunk-VTOBUZL6.js → chunk-XN3KCKAM.js} +2 -2
  171. package/dist/cli/chunks/{chunk-KUAKV3IW.js → chunk-XSPMLJCQ.js} +1 -1
  172. package/dist/cli/chunks/{chunk-YBQH2VOP.js → chunk-XTZGAG6P.js} +2 -2
  173. package/dist/cli/chunks/{chunk-MGZ5FJUW.js → chunk-YE54T2NQ.js} +2 -2
  174. package/dist/cli/chunks/{chunk-BTVEYBW2.js → chunk-YEFTK4HD.js} +2 -2
  175. package/dist/cli/chunks/{chunk-CT6SAVXQ.js → chunk-YGC5QKQ4.js} +2 -2
  176. package/dist/cli/chunks/{chunk-TWJTK4CC.js → chunk-YGOSSVY5.js} +2 -2
  177. package/dist/cli/chunks/chunk-YKQWIXUY.js +2 -0
  178. package/dist/cli/chunks/{chunk-TSQC2KKZ.js → chunk-Z2S7DNFP.js} +2 -2
  179. package/dist/cli/chunks/{chunk-JRRXCODW.js → chunk-Z54G2YOL.js} +2 -2
  180. package/dist/cli/chunks/{chunk-EXGMJFAT.js → chunk-ZJGFQK27.js} +1 -1
  181. package/dist/cli/chunks/{chunk-WNQS4WTS.js → chunk-ZUE524JL.js} +2 -2
  182. package/dist/cli/chunks/{ci-ENOASTYB.js → ci-UMA2SMNW.js} +2 -2
  183. package/dist/cli/chunks/{ci-config-B26OXHQM.js → ci-config-UQSILJFQ.js} +2 -2
  184. package/dist/cli/chunks/{ci-output-JTCLLNOQ.js → ci-output-U6YZLLKH.js} +2 -2
  185. package/dist/cli/chunks/{circuit-breaker-23JMFNM5.js → circuit-breaker-ATYQP6X2.js} +2 -2
  186. package/dist/cli/chunks/{claude-flow-setup-ON6L462G.js → claude-flow-setup-6YHFD7AN.js} +2 -2
  187. package/dist/cli/chunks/client-E43GWLQH.js +2 -0
  188. package/dist/cli/chunks/{cline-installer-OWQ4D2FQ.js → cline-installer-EPE7IOZE.js} +2 -2
  189. package/dist/cli/chunks/{code-2ZRL7SEU.js → code-NUEJ4XYO.js} +3 -3
  190. package/dist/cli/chunks/{code-index-extractor-JXSQVM67.js → code-index-extractor-D4DBT6OL.js} +2 -2
  191. package/dist/cli/chunks/{codex-installer-7LXZYBSQ.js → codex-installer-633SM4LR.js} +2 -2
  192. package/dist/cli/chunks/{completions-C2LR623C.js → completions-WUKVIW3L.js} +2 -2
  193. package/dist/cli/chunks/{complexity-analyzer-TGQLHCYJ.js → complexity-analyzer-F73ACR5H.js} +2 -2
  194. package/dist/cli/chunks/{continuedev-installer-RUGD24D2.js → continuedev-installer-QH42TKMS.js} +2 -2
  195. package/dist/cli/chunks/{copilot-installer-ZLFVLEJP.js → copilot-installer-Y3XC7BTT.js} +2 -2
  196. package/dist/cli/chunks/core-handlers-R5A3SQDY.js +2 -0
  197. package/dist/cli/chunks/{cost-tracker-RT4QL745.js → cost-tracker-57QPV7E3.js} +2 -2
  198. package/dist/cli/chunks/coverage-IBCHMBCR.js +51 -0
  199. package/dist/cli/chunks/cross-domain-router-LLYVPZF6.js +2 -0
  200. package/dist/cli/chunks/{cursor-installer-LJKLNFF6.js → cursor-installer-F4UYQHIN.js} +2 -2
  201. package/dist/cli/chunks/{daemon-FBH3IRYN.js → daemon-BYYPIJ7G.js} +4 -4
  202. package/dist/cli/chunks/{daemon-BMDXCQT5.js → daemon-XR4Q6YZF.js} +3 -3
  203. package/dist/cli/chunks/{dag-attention-scheduler-JGDED55I.js → dag-attention-scheduler-ZR5ZD3TW.js} +2 -2
  204. package/dist/cli/chunks/{detect-SZIHIVCJ.js → detect-GEGYURLL.js} +2 -2
  205. package/dist/cli/chunks/{dist-node-FV3KWXQ6.js → dist-node-JU3KT2JO.js} +2 -2
  206. package/dist/cli/chunks/{domain-handler-GI5JWQOV.js → domain-handler-7QI3FJGE.js} +2 -2
  207. package/dist/cli/chunks/{domain-plugins-BUWY36TL.js → domain-plugins-O2YRM2PD.js} +2 -2
  208. package/dist/cli/chunks/{domain-transfer-GCY7W5DA.js → domain-transfer-7J3S2OS6.js} +2 -2
  209. package/dist/cli/chunks/dream-6C4NURSE.js +2 -0
  210. package/dist/cli/chunks/{embed-and-insert-pattern-GPRR3ZGD.js → embed-and-insert-pattern-URES5Q6J.js} +2 -2
  211. package/dist/cli/chunks/{eval-XPB3IGAP.js → eval-RVMCIUOR.js} +2 -2
  212. package/dist/cli/chunks/{experience-capture-middleware-2E554UB3.js → experience-capture-middleware-SYJQSBKE.js} +3 -3
  213. package/dist/cli/chunks/{fast-paths-ZSMWZPUC.js → fast-paths-QUKPKWKZ.js} +2 -2
  214. package/dist/cli/chunks/{feature-flags-N7EOGE5P.js → feature-flags-5JCSKL2P.js} +2 -2
  215. package/dist/cli/chunks/{feature-flags-GIWVDVVC.js → feature-flags-K7JXNKJI.js} +2 -2
  216. package/dist/cli/chunks/file-discovery-J5IE5KP7.js +2 -0
  217. package/dist/cli/chunks/{fleet-HCHDOUCX.js → fleet-II4Q6HXK.js} +3 -3
  218. package/dist/cli/chunks/{gnn-wrapper-CZNCNXXZ.js → gnn-wrapper-M7VO2EMS.js} +2 -2
  219. package/dist/cli/chunks/{heartbeat-handler-6YUIF2YQ.js → heartbeat-handler-ND5CY26N.js} +4 -4
  220. package/dist/cli/chunks/heartbeat-scheduler-FC5PBTMN.js +2 -0
  221. package/dist/cli/chunks/hnsw-adapter-47UIVOBG.js +2 -0
  222. package/dist/cli/chunks/hnsw-index-3AKVLOZQ.js +2 -0
  223. package/dist/cli/chunks/{hnsw-legacy-bridge-J3M3IK24.js → hnsw-legacy-bridge-N3AUUUU7.js} +2 -2
  224. package/dist/cli/chunks/{hnswlib-node-ULGTGDZW.js → hnswlib-node-NZY3E5EN.js} +2 -2
  225. package/dist/cli/chunks/{hooks-C4BUGYUQ.js → hooks-QVJDTII5.js} +10 -10
  226. package/dist/cli/chunks/hybrid-backend-YAOSNX47.js +2 -0
  227. package/dist/cli/chunks/{hypergraph-engine-WINGVMPG.js → hypergraph-engine-ZRY6MTDV.js} +2 -2
  228. package/dist/cli/chunks/{hypergraph-handler-GADMWKAU.js → hypergraph-handler-56DO4XZQ.js} +3 -3
  229. package/dist/cli/chunks/impact-analyzer-4FMJXM4M.js +2 -0
  230. package/dist/cli/chunks/{init-guard-K2T4QWAO.js → init-guard-DTF4EVUY.js} +2 -2
  231. package/dist/cli/chunks/{init-handler-PCZTDZYI.js → init-handler-M6CNQHMX.js} +6 -6
  232. package/dist/cli/chunks/init-wizard-RTLCRWDT.js +2 -0
  233. package/dist/cli/chunks/kernel-2OWIGGGT.js +2 -0
  234. package/dist/cli/chunks/{kilocode-installer-XENXNEIU.js → kilocode-installer-IJN7XKBH.js} +2 -2
  235. package/dist/cli/chunks/{kiro-installer-3PG2TJ67.js → kiro-installer-UKKPGPDC.js} +2 -2
  236. package/dist/cli/chunks/knowledge-graph-25XXKDJN.js +2 -0
  237. package/dist/cli/chunks/learning-W2HETWQ4.js +131 -0
  238. package/dist/cli/chunks/{llm-router-RKVDEWU2.js → llm-router-Y546K4VX.js} +4 -4
  239. package/dist/cli/chunks/llm-router-service-G3EIN4UB.js +2 -0
  240. package/dist/cli/chunks/{load-ITHC564X.js → load-MKAB2AXE.js} +2 -2
  241. package/dist/cli/chunks/load-test-D6QYNIVT.js +2 -0
  242. package/dist/cli/chunks/{mcp-TCL5UW3N.js → mcp-AZKUS6K3.js} +2 -2
  243. package/dist/cli/chunks/{memory-BKDAY2N2.js → memory-ZDOQN2KU.js} +5 -5
  244. package/dist/cli/chunks/memory-backend-LDFFZMEQ.js +2 -0
  245. package/dist/cli/chunks/{memory-handlers-WN4FXFOA.js → memory-handlers-3SQVY7FE.js} +2 -2
  246. package/dist/cli/chunks/{multi-model-executor-VHAT7ZPF.js → multi-model-executor-WWVXDHG4.js} +2 -2
  247. package/dist/cli/chunks/{opencode-installer-E3VM3EEY.js → opencode-installer-YUJNXXWS.js} +2 -2
  248. package/dist/cli/chunks/{orchestrator-BMQ6X762.js → orchestrator-Z6PWPLRE.js} +109 -25
  249. package/dist/cli/chunks/pattern-null-store-KDVRM7PW.js +2 -0
  250. package/dist/cli/chunks/{pattern-usage-recorder-GOOR2BV5.js → pattern-usage-recorder-TPWPX32U.js} +2 -2
  251. package/dist/cli/chunks/{pipeline-5NSFQQIX.js → pipeline-4BBGTE4M.js} +2 -2
  252. package/dist/cli/chunks/{platform-SQM34J5G.js → platform-5GSHXCV5.js} +2 -2
  253. package/dist/cli/chunks/{plugin-UQJZRMZG.js → plugin-OFDVF5HS.js} +2 -2
  254. package/dist/cli/chunks/{prime-radiant-advanced-wasm-WMDJOL4S.js → prime-radiant-advanced-wasm-NC6MUYGJ.js} +2 -2
  255. package/dist/cli/chunks/project-root-DDGBWDP6.js +2 -0
  256. package/dist/cli/chunks/protocol-executor-KBOLLCWA.js +2 -0
  257. package/dist/cli/chunks/{protocol-handler-OBDCVY6X.js → protocol-handler-MPOAAEPA.js} +2 -2
  258. package/dist/cli/chunks/{prove-XDC7I4XT.js → prove-CDKMAIVM.js} +2 -2
  259. package/dist/cli/chunks/qe-reasoning-bank-GRXBT7FC.js +2 -0
  260. package/dist/cli/chunks/{quality-L4GQ6WX4.js → quality-ZH4F7R7R.js} +2 -2
  261. package/dist/cli/chunks/{quality-gate-MJG66LKN.js → quality-gate-IDRMW6OE.js} +3 -3
  262. package/dist/cli/chunks/queen-coordinator-L2QWMJ5Q.js +2 -0
  263. package/dist/cli/chunks/{real-embeddings-HW4G2LWL.js → real-embeddings-I2UVNNB3.js} +2 -2
  264. package/dist/cli/chunks/{ref-validation-FC7JOJ2C.js → ref-validation-Z5GCGVXK.js} +2 -2
  265. package/dist/cli/chunks/{roocode-installer-KWS4CEIC.js → roocode-installer-IZ2S7PH2.js} +2 -2
  266. package/dist/cli/chunks/router-FT5WJPUH.js +2 -0
  267. package/dist/cli/chunks/routing-feedback-EO2MKOUX.js +2 -0
  268. package/dist/cli/chunks/{routing-handler-QF4WVB2S.js → routing-handler-NAX35VUW.js} +2 -2
  269. package/dist/cli/chunks/{ruvector-commands-2MTCOUK6.js → ruvector-commands-5YW2SOFF.js} +2 -2
  270. package/dist/cli/chunks/rvf-dual-writer-WHBFQJVU.js +2 -0
  271. package/dist/cli/chunks/rvf-migration-adapter-YT3APF2I.js +2 -0
  272. package/dist/cli/chunks/{rvf-migration-coordinator-BREJCXWN.js → rvf-migration-coordinator-VUIZHTVG.js} +2 -2
  273. package/dist/cli/chunks/rvf-native-adapter-37PUFKQD.js +2 -0
  274. package/dist/cli/chunks/{rvf-store-integrity-KKC6HOJD.js → rvf-store-integrity-IPGCAT6C.js} +2 -2
  275. package/dist/cli/chunks/safe-db-TDZKUOZJ.js +2 -0
  276. package/dist/cli/chunks/schedule-CRKTRY2A.js +2 -0
  277. package/dist/cli/chunks/scheduler-6ZBDVQWN.js +2 -0
  278. package/dist/cli/chunks/{security-OSAE7VAP.js → security-3IH4BO5Z.js} +3 -3
  279. package/dist/cli/chunks/{shared-rvf-adapter-COUOS665.js → shared-rvf-adapter-ABY7PAY2.js} +2 -2
  280. package/dist/cli/chunks/{shared-rvf-dual-writer-YXMPZKQE.js → shared-rvf-dual-writer-6KENLN2W.js} +2 -2
  281. package/dist/cli/chunks/sqlite-persistence-FFJQAIKW.js +2 -0
  282. package/dist/cli/chunks/{standalone-memory-E6JBMOIL.js → standalone-memory-RLFAUGOW.js} +2 -2
  283. package/dist/cli/chunks/{status-handler-AFTCIYIX.js → status-handler-FCOZBPE5.js} +2 -2
  284. package/dist/cli/chunks/{structural-health-2FROCEI4.js → structural-health-4RDA5UUM.js} +2 -2
  285. package/dist/cli/chunks/{sync-VAYTOWDC.js → sync-54LUAUTK.js} +2 -2
  286. package/dist/cli/chunks/{sync-YIQYOFGW.js → sync-KGEEXXCC.js} +2 -2
  287. package/dist/cli/chunks/{task-handler-KVQHDEX3.js → task-handler-K3OXHYKU.js} +2 -2
  288. package/dist/cli/chunks/{task-handlers-MVVECQA6.js → task-handlers-6H7L2UT4.js} +3 -3
  289. package/dist/cli/chunks/{test-5JSVTOMY.js → test-S7IG6EIX.js} +4 -4
  290. package/dist/cli/chunks/test-runner-process-OTQDAJLN.js +2 -0
  291. package/dist/cli/chunks/{test-scheduling-HBOHVLI3.js → test-scheduling-7XYXI4L2.js} +3 -3
  292. package/dist/cli/chunks/{token-bootstrap-5VEPTPFA.js → token-bootstrap-3QMABE45.js} +2 -2
  293. package/dist/cli/chunks/{token-usage-TBJHDLY6.js → token-usage-Y2YTPOFE.js} +2 -2
  294. package/dist/cli/chunks/{transformers-VAWYMHMZ.js → transformers-UCJ3HHHC.js} +2 -2
  295. package/dist/cli/chunks/tree-sitter-wasm-parser-D6JTTHTP.js +2 -0
  296. package/dist/cli/chunks/{types-R5SDZU2E.js → types-6CMFPETH.js} +2 -2
  297. package/dist/cli/chunks/unified-memory-QARWQKJ2.js +2 -0
  298. package/dist/cli/chunks/unified-memory-hnsw-LHY3DXCP.js +2 -0
  299. package/dist/cli/chunks/unified-persistence-WEYYGLHM.js +2 -0
  300. package/dist/cli/chunks/{upgrade-K5PIHXRB.js → upgrade-K25DN6WU.js} +2 -2
  301. package/dist/cli/chunks/{validate-RPTS7RYJ.js → validate-T4V3TBY3.js} +2 -2
  302. package/dist/cli/chunks/{validate-swarm-B2ZL556X.js → validate-swarm-XSRC576T.js} +2 -2
  303. package/dist/cli/chunks/visual-security-O4ALMCXQ.js +2 -0
  304. package/dist/cli/chunks/{web-tree-sitter-K4DUJC32.js → web-tree-sitter-YOZXHRTN.js} +2 -2
  305. package/dist/cli/chunks/{windsurf-installer-OK2AJN35.js → windsurf-installer-ITPU2IYL.js} +2 -2
  306. package/dist/cli/chunks/witness-chain-B3YW5NMS.js +2 -0
  307. package/dist/cli/chunks/witness-chain-PIYR72HJ.js +2 -0
  308. package/dist/cli/chunks/{witness-chain-repair-L6Y5RFXR.js → witness-chain-repair-YUG7E3UX.js} +2 -2
  309. package/dist/cli/chunks/{witness-chain-verifier-N4CW7FZX.js → witness-chain-verifier-DTDSVKOG.js} +2 -2
  310. package/dist/cli/chunks/{witness-key-manager-TDNPS3WD.js → witness-key-manager-EWACWGAW.js} +2 -2
  311. package/dist/cli/chunks/{workflow-XRZA3YCY.js → workflow-ZIQ4FV42.js} +4 -4
  312. package/dist/cli/chunks/workflow-orchestrator-3ZN2BCGY.js +2 -0
  313. package/dist/cli/chunks/{wrappers-5JIFWKN6.js → wrappers-PW2O27LL.js} +2 -2
  314. package/dist/cli/commands/coverage.js +6 -0
  315. package/dist/cli/commands/learning-prune.d.ts +14 -0
  316. package/dist/cli/commands/learning-prune.js +105 -0
  317. package/dist/cli/commands/learning.js +9 -0
  318. package/dist/cli/handlers/brain-handler.js +12 -1
  319. package/dist/cli/utils/coverage-verdict.js +14 -3
  320. package/dist/context/compaction/index.d.ts +7 -0
  321. package/dist/context/compaction/index.js +30 -6
  322. package/dist/coordination/handlers/coverage-evidence.d.ts +19 -0
  323. package/dist/coordination/handlers/coverage-evidence.js +31 -2
  324. package/dist/coordination/handlers/coverage-handlers.js +5 -1
  325. package/dist/coordination/handlers/coverage-target.js +8 -1
  326. package/dist/coordination/handlers/quality-handlers.js +9 -1
  327. package/dist/coordination/result-saver-adapters.js +1 -0
  328. package/dist/coordination/result-saver.js +9 -5
  329. package/dist/domains/chaos-resilience/services/chaos-engineer.d.ts +1 -0
  330. package/dist/domains/chaos-resilience/services/chaos-engineer.js +23 -45
  331. package/dist/domains/coverage-analysis/collected-metrics.d.ts +22 -6
  332. package/dist/domains/coverage-analysis/collected-metrics.js +37 -12
  333. package/dist/domains/coverage-analysis/services/coverage-analyzer.js +2 -0
  334. package/dist/domains/defect-intelligence/services/defect-predictor.js +3 -6
  335. package/dist/domains/quality-assessment/coverage-report-event.d.ts +8 -0
  336. package/dist/domains/quality-assessment/coverage-report-event.js +22 -1
  337. package/dist/domains/quality-assessment/interfaces.d.ts +6 -0
  338. package/dist/domains/quality-assessment/services/quality-analyzer.d.ts +4 -0
  339. package/dist/domains/quality-assessment/services/quality-analyzer.js +63 -17
  340. package/dist/domains/test-execution/interfaces.d.ts +5 -0
  341. package/dist/domains/test-execution/services/test-executor.js +6 -0
  342. package/dist/init/phases/07-hooks.js +90 -6
  343. package/dist/integrations/ruvector/brain-rvf-exporter.d.ts +25 -0
  344. package/dist/integrations/ruvector/brain-rvf-exporter.js +154 -61
  345. package/dist/learning/dream/dream-engine.d.ts +24 -1
  346. package/dist/learning/dream/dream-engine.js +57 -6
  347. package/dist/learning/learning-retention.d.ts +103 -0
  348. package/dist/learning/learning-retention.js +213 -0
  349. package/dist/mcp/bundle.js +494 -489
  350. package/dist/mcp/handlers/domain-handler-configs.d.ts +9 -1
  351. package/dist/mcp/handlers/domain-handler-configs.js +24 -14
  352. package/dist/mcp/protocol-server.js +1 -1
  353. package/dist/mcp/tools/chaos-resilience/inject.d.ts +3 -4
  354. package/dist/mcp/tools/chaos-resilience/inject.js +11 -81
  355. package/dist/mcp/tools/learning-optimization/dream.d.ts +8 -0
  356. package/dist/mcp/tools/learning-optimization/dream.js +4 -0
  357. package/package.json +1 -1
  358. package/dist/cli/chunks/adapter-KCQDVYY2.js +0 -2
  359. package/dist/cli/chunks/aqe-learning-engine-SAQOHSGN.js +0 -2
  360. package/dist/cli/chunks/base-WCACU3FN.js +0 -2
  361. package/dist/cli/chunks/brain-handler-GTQNHHZS.js +0 -94
  362. package/dist/cli/chunks/browser-workflow-G6IASEAP.js +0 -2
  363. package/dist/cli/chunks/chunk-K65CGKLD.js +0 -8
  364. package/dist/cli/chunks/chunk-MB46UBGY.js +0 -3
  365. package/dist/cli/chunks/chunk-N4CYAKOX.js +0 -79
  366. package/dist/cli/chunks/chunk-PT4FMJPQ.js +0 -3
  367. package/dist/cli/chunks/chunk-S5AZCIZS.js +0 -2
  368. package/dist/cli/chunks/chunk-UT2VZ33P.js +0 -2
  369. package/dist/cli/chunks/client-TV3V2YZ5.js +0 -2
  370. package/dist/cli/chunks/core-handlers-PZT4OLWR.js +0 -2
  371. package/dist/cli/chunks/coverage-NV3C4IMM.js +0 -50
  372. package/dist/cli/chunks/cross-domain-router-QOFCZ7G4.js +0 -2
  373. package/dist/cli/chunks/dream-TRFBGDSQ.js +0 -2
  374. package/dist/cli/chunks/file-discovery-WCKGMSPZ.js +0 -2
  375. package/dist/cli/chunks/heartbeat-scheduler-P44A2OX3.js +0 -2
  376. package/dist/cli/chunks/hnsw-adapter-ZJQIQJKC.js +0 -2
  377. package/dist/cli/chunks/hnsw-index-HMG2GH3Z.js +0 -2
  378. package/dist/cli/chunks/hybrid-backend-B7M74PZG.js +0 -2
  379. package/dist/cli/chunks/impact-analyzer-PZYOVKQO.js +0 -2
  380. package/dist/cli/chunks/init-wizard-TZDJQK3U.js +0 -2
  381. package/dist/cli/chunks/kernel-Y6RRIOKW.js +0 -2
  382. package/dist/cli/chunks/knowledge-graph-BVD5Z66M.js +0 -2
  383. package/dist/cli/chunks/learning-6KDH7FK4.js +0 -122
  384. package/dist/cli/chunks/llm-router-service-KHCAMSUU.js +0 -2
  385. package/dist/cli/chunks/load-test-RUF7DZA5.js +0 -2
  386. package/dist/cli/chunks/memory-backend-7ZLFOVGG.js +0 -2
  387. package/dist/cli/chunks/pattern-null-store-RY6CVYHP.js +0 -2
  388. package/dist/cli/chunks/project-root-IO5KRNGL.js +0 -2
  389. package/dist/cli/chunks/protocol-executor-U2CUDWDE.js +0 -2
  390. package/dist/cli/chunks/qe-reasoning-bank-DQSSX2IP.js +0 -2
  391. package/dist/cli/chunks/queen-coordinator-6FN4BZIX.js +0 -2
  392. package/dist/cli/chunks/router-YUO3I7RU.js +0 -2
  393. package/dist/cli/chunks/routing-feedback-36SLQGJE.js +0 -2
  394. package/dist/cli/chunks/rvf-dual-writer-FRYZH3WZ.js +0 -2
  395. package/dist/cli/chunks/rvf-migration-adapter-XXNITL5I.js +0 -2
  396. package/dist/cli/chunks/rvf-native-adapter-D2WWKJIV.js +0 -2
  397. package/dist/cli/chunks/safe-db-4RRIGRXD.js +0 -2
  398. package/dist/cli/chunks/schedule-25RTO4DQ.js +0 -2
  399. package/dist/cli/chunks/scheduler-BPIOJZ5P.js +0 -2
  400. package/dist/cli/chunks/sqlite-persistence-EDF47DDX.js +0 -2
  401. package/dist/cli/chunks/test-runner-process-LEPF2OSS.js +0 -2
  402. package/dist/cli/chunks/tree-sitter-wasm-parser-TSZTCMFV.js +0 -2
  403. package/dist/cli/chunks/unified-memory-TLGSSLMI.js +0 -2
  404. package/dist/cli/chunks/unified-memory-hnsw-MSUR7ZOO.js +0 -2
  405. package/dist/cli/chunks/unified-persistence-VFFOTWK7.js +0 -2
  406. package/dist/cli/chunks/visual-security-6Q44XNLB.js +0 -2
  407. package/dist/cli/chunks/witness-chain-KDOMXDQX.js +0 -2
  408. package/dist/cli/chunks/witness-chain-N3OY2RMH.js +0 -2
  409. package/dist/cli/chunks/workflow-orchestrator-CVNNT2RJ.js +0 -2
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.13");process.exit(0)}
2
- import{a as ie}from"./chunk-N4CYAKOX.js";import{c as te,d as ne}from"./chunk-3AN5TNGD.js";import{a as ee}from"./chunk-SYV2V3PL.js";import{c as R}from"./chunk-T3PGQFDI.js";import{b as A,d as Y}from"./chunk-VTOBUZL6.js";import{b as J,c as K,e as ue}from"./chunk-KDNJ4F3P.js";import{a as N,b as X,d as le}from"./chunk-KV4T4MXK.js";import{i as D}from"./chunk-H4H2YSFH.js";import{a as Z,d as he}from"./chunk-TOQWL2ZF.js";import{a as Q}from"./chunk-UT2VZ33P.js";import{c as _}from"./chunk-GB6HBNH2.js";import{a as C,e as F}from"./chunk-3Y2ROSCL.js";var k={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};Y();F();var T=class d{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...k,...e}}async initialize(){if(!this.initialized)try{if(this.persistence=R(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.prepareStatements(),this.initialized=!0,this.config.debug){let e=await this.getStats();console.log(`[ConceptGraph] Initialized: ${this.persistence.getDbPath()}`,e)}}catch(e){throw new Error(`Failed to initialize ConceptGraph: ${C(e)}`)}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertNode",this.db.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.14");process.exit(0)}
2
+ import{a as re,g as se,h as ae,j as oe}from"./chunk-NKOLILT7.js";import{c as ne,d as ie}from"./chunk-MQXWG55U.js";import{a as te}from"./chunk-HHBF2BZC.js";import{c as M}from"./chunk-USAKCGHC.js";import{b as A,d as X}from"./chunk-XN3KCKAM.js";import{b as K,c as Z,e as ve}from"./chunk-UDSB3XCG.js";import{a as N,b as J,d as fe}from"./chunk-AJVLVF7V.js";import{i as D}from"./chunk-QP6GL3O5.js";import{a as ee,d as ye}from"./chunk-LTGQJYYO.js";import{a as Y}from"./chunk-YKQWIXUY.js";import{c as R}from"./chunk-C3OIBFAA.js";import{a as C,e as F}from"./chunk-L5VSLPMW.js";var k={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};X();F();var T=class d{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...k,...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: ${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,7 +37,7 @@ import{a as ie}from"./chunk-N4CYAKOX.js";import{c as te,d as ne}from"./chunk-3AN
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=D(),n=new Date().toISOString(),i=this.prepared.get("insertNode");if(!i)throw new Error("Prepared statement not found: insertNode");let s=e.embedding?Buffer.from(new Float32Array(e.embedding).buffer):null;return i.run(t,e.conceptType,e.content,s,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 s=await this.getEdgeBetween(e,t);if(s)return await this.strengthenEdge(e,t,.1),s.id;let r=D(),o=this.prepared.get("insertEdge");if(!o)throw new Error("Prepared statement not found: insertEdge");return o.run(r,e,t,n,Math.max(0,Math.min(1,i)),1),this.config.debug&&console.log(`[ConceptGraph] Added edge: ${e} -> ${t} (${n})`),r}async strengthenEdge(e,t,n=.1){this.ensureInitialized();let i=await this.getEdgeBetween(e,t);if(!i)return;let s=Math.min(1,i.weight+n),r=this.prepared.get("updateEdge");if(!r)throw new Error("Prepared statement not found: updateEdge");r.run(s,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 a=await this.getNode(o.target);a&&t.push({node:a,edge:this.rowToEdge(o)})}let s=this.prepared.get("getIncomingEdges");if(!s)throw new Error("Prepared statement not found: getIncomingEdges");let r=s.all(e);for(let o of r){let a=await this.getNode(o.source);a&&t.push({node:a,edge:this.rowToEdge(o)})}return t}async findPath(e,t,n=5){this.ensureInitialized();let i=new Set,s=[{nodeId:e,path:[e]}];for(;s.length>0;){let r=s.shift();if(r.nodeId===t){let a=[];for(let c of r.path){let p=await this.getNode(c);p&&a.push(p)}return a}if(r.path.length>n||i.has(r.nodeId))continue;i.add(r.nodeId);let o=await this.getNeighbors(r.nodeId);for(let{node:a}of o)i.has(a.id)||s.push({nodeId:a.id,path:[...r.path,a.id]})}return[]}async getCluster(e,t=2){this.ensureInitialized();let n=new Set,i=[],s=async(r,o)=>{if(n.has(r)||o>t)return;n.add(r);let a=await this.getNode(r);if(a&&(i.push(a),o<t)){let c=await this.getNeighbors(r);for(let{node:p}of c)await s(p.id,o+1)}};return await s(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 s of e)try{if(await this.findNodeByPatternId(s.id))continue;let o=s.patternType&&d.TECHNIQUE_PATTERN_TYPES.has(s.patternType)?"technique":"pattern",a=await this.addNode({conceptType:o,content:`${s.name}: ${s.description}`,patternId:s.id,metadata:{domain:s.domain,patternType:s.patternType,confidence:s.confidence,successRate:s.successRate}});t++,n.push(a);let c=s.domain||"unknown";i.has(c)||i.set(c,[]),i.get(c).push(a);let p=await this.findDomainNode(s.domain);if(!p){let l=await this.addNode({conceptType:"domain",content:s.domain,metadata:{patternCount:1}});p=await this.getNode(l)}p&&await this.addEdge(a,p.id,"co_occurrence",.8)}catch(r){this.config.debug&&console.error(`[ConceptGraph] Failed to load pattern: ${s.id}`,r)}if(t>0){let s=await this.discoverSameDomainEdges(i),r=await this.pruneEdges();this.config.debug&&console.log(`[ConceptGraph] Discovered ${s} same-domain edges, pruned ${r}`)}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[s,r]of e){let o=this.countDomainSimilarityEdges(s);if(o>=n){console.log(`[ConceptGraph] Domain '${s}' already at edge cap (${o}/${n}), skipping`);continue}let a=new Set(r),c=n-o,l=this.db.prepare("SELECT id, metadata FROM concept_nodes WHERE concept_type IN ('pattern', 'technique')").all().filter(u=>{if(a.has(u.id))return!1;let g=u.metadata?A(u.metadata):{};return String(g.domain||"unknown")===s}),h=this.db.transaction(()=>{let u=0;for(let g of r){let f=0;for(let v of l){if(f>=t||u>=c)break;if(!this.prepared.get("getEdge")?.get(g,v.id)){let E=D();this.prepared.get("insertEdge").run(E,g,v.id,"similarity",.6,1),u++,f++}}if(u>=c)break}for(let g=0;g<r.length&&u<c;g++){let f=0;for(let v=g+1;v<r.length&&u<c&&!(f>=t);v++)if(!this.prepared.get("getEdge")?.get(r[g],r[v])){let E=D();this.prepared.get("insertEdge").run(E,r[g],r[v],"similarity",.6,1),u++,f++}}return u});i+=h()}else{let s=this.db.prepare("SELECT id, metadata FROM concept_nodes WHERE concept_type = 'pattern'").all(),r=new Map;for(let a of s){let c=a.metadata?A(a.metadata):{},p=String(c.domain||"unknown");r.has(p)||r.set(p,[]),r.get(p).push(a)}let o=this.db.transaction(()=>{let a=0;for(let[c,p]of r){let l=this.countDomainSimilarityEdges(c);if(l>=n)continue;let h=0,u=n-l;for(let g=0;g<p.length&&h<u;g++){let f=0;for(let v=g+1;v<p.length&&h<u&&!(f>=t);v++)if(!this.prepared.get("getEdge")?.get(p[g].id,p[v].id)){let E=D();this.prepared.get("insertEdge").run(E,p[g].id,p[v].id,"similarity",.6,1),a++,h++,f++}}}return a});i+=o()}return i}connectToDomainMates(e,t,n,i=10){if(!this.db)return;let s=this.db.prepare(`SELECT id FROM concept_nodes
40
+ `))}async addNode(e){this.ensureInitialized();let t=D(),n=new Date().toISOString(),i=this.prepared.get("insertNode");if(!i)throw new Error("Prepared statement not found: insertNode");let s=e.embedding?Buffer.from(new Float32Array(e.embedding).buffer):null;return i.run(t,e.conceptType,e.content,s,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 s=await this.getEdgeBetween(e,t);if(s)return await this.strengthenEdge(e,t,.1),s.id;let r=D(),o=this.prepared.get("insertEdge");if(!o)throw new Error("Prepared statement not found: insertEdge");return o.run(r,e,t,n,Math.max(0,Math.min(1,i)),1),this.config.debug&&console.log(`[ConceptGraph] Added edge: ${e} -> ${t} (${n})`),r}async strengthenEdge(e,t,n=.1){this.ensureInitialized();let i=await this.getEdgeBetween(e,t);if(!i)return;let s=Math.min(1,i.weight+n),r=this.prepared.get("updateEdge");if(!r)throw new Error("Prepared statement not found: updateEdge");r.run(s,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 a=await this.getNode(o.target);a&&t.push({node:a,edge:this.rowToEdge(o)})}let s=this.prepared.get("getIncomingEdges");if(!s)throw new Error("Prepared statement not found: getIncomingEdges");let r=s.all(e);for(let o of r){let a=await this.getNode(o.source);a&&t.push({node:a,edge:this.rowToEdge(o)})}return t}async findPath(e,t,n=5){this.ensureInitialized();let i=new Set,s=[{nodeId:e,path:[e]}];for(;s.length>0;){let r=s.shift();if(r.nodeId===t){let a=[];for(let c of r.path){let p=await this.getNode(c);p&&a.push(p)}return a}if(r.path.length>n||i.has(r.nodeId))continue;i.add(r.nodeId);let o=await this.getNeighbors(r.nodeId);for(let{node:a}of o)i.has(a.id)||s.push({nodeId:a.id,path:[...r.path,a.id]})}return[]}async getCluster(e,t=2){this.ensureInitialized();let n=new Set,i=[],s=async(r,o)=>{if(n.has(r)||o>t)return;n.add(r);let a=await this.getNode(r);if(a&&(i.push(a),o<t)){let c=await this.getNeighbors(r);for(let{node:p}of c)await s(p.id,o+1)}};return await s(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 s of e)try{if(await this.findNodeByPatternId(s.id))continue;let o=s.patternType&&d.TECHNIQUE_PATTERN_TYPES.has(s.patternType)?"technique":"pattern",a=await this.addNode({conceptType:o,content:`${s.name}: ${s.description}`,patternId:s.id,metadata:{domain:s.domain,patternType:s.patternType,confidence:s.confidence,successRate:s.successRate}});t++,n.push(a);let c=s.domain||"unknown";i.has(c)||i.set(c,[]),i.get(c).push(a);let p=await this.findDomainNode(s.domain);if(!p){let u=await this.addNode({conceptType:"domain",content:s.domain,metadata:{patternCount:1}});p=await this.getNode(u)}p&&await this.addEdge(a,p.id,"co_occurrence",.8)}catch(r){this.config.debug&&console.error(`[ConceptGraph] Failed to load pattern: ${s.id}`,r)}if(t>0){let s=await this.discoverSameDomainEdges(i),r=await this.pruneEdges();this.config.debug&&console.log(`[ConceptGraph] Discovered ${s} same-domain edges, pruned ${r}`)}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[s,r]of e){let o=this.countDomainSimilarityEdges(s);if(o>=n){console.log(`[ConceptGraph] Domain '${s}' already at edge cap (${o}/${n}), skipping`);continue}let a=new Set(r),c=n-o,u=this.db.prepare("SELECT id, metadata FROM concept_nodes WHERE concept_type IN ('pattern', 'technique')").all().filter(l=>{if(a.has(l.id))return!1;let g=l.metadata?A(l.metadata):{};return String(g.domain||"unknown")===s}),m=this.db.transaction(()=>{let l=0;for(let g of r){let f=0;for(let v of u){if(f>=t||l>=c)break;if(!this.prepared.get("getEdge")?.get(g,v.id)){let b=D();this.prepared.get("insertEdge").run(b,g,v.id,"similarity",.6,1),l++,f++}}if(l>=c)break}for(let g=0;g<r.length&&l<c;g++){let f=0;for(let v=g+1;v<r.length&&l<c&&!(f>=t);v++)if(!this.prepared.get("getEdge")?.get(r[g],r[v])){let b=D();this.prepared.get("insertEdge").run(b,r[g],r[v],"similarity",.6,1),l++,f++}}return l});i+=m()}else{let s=this.db.prepare("SELECT id, metadata FROM concept_nodes WHERE concept_type = 'pattern'").all(),r=new Map;for(let a of s){let c=a.metadata?A(a.metadata):{},p=String(c.domain||"unknown");r.has(p)||r.set(p,[]),r.get(p).push(a)}let o=this.db.transaction(()=>{let a=0;for(let[c,p]of r){let u=this.countDomainSimilarityEdges(c);if(u>=n)continue;let m=0,l=n-u;for(let g=0;g<p.length&&m<l;g++){let f=0;for(let v=g+1;v<p.length&&m<l&&!(f>=t);v++)if(!this.prepared.get("getEdge")?.get(p[g].id,p[v].id)){let b=D();this.prepared.get("insertEdge").run(b,p[g].id,p[v].id,"similarity",.6,1),a++,m++,f++}}}return a});i+=o()}return i}connectToDomainMates(e,t,n,i=10){if(!this.db)return;let s=this.db.prepare(`SELECT id FROM concept_nodes
41
41
  WHERE concept_type IN ('pattern', 'technique')
42
42
  AND json_extract(metadata, '$.domain') = ?
43
43
  AND (pattern_id IS NULL OR pattern_id != ?)
@@ -63,7 +63,7 @@ import{a as ie}from"./chunk-N4CYAKOX.js";import{c as te,d as ne}from"./chunk-3AN
63
63
  ORDER BY weight DESC
64
64
  LIMIT -1 OFFSET ?
65
65
  )
66
- `).run(a,e);s+=c.changes}return s})(),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,s=t.get().count,r={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)r[c.concept_type]=c.count;let a=0;return i>0&&(a=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:s,byType:r,avgEdgesPerNode:i>0?s/i:0,avgActivation:a}}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?A(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 me(d){return new T(d)}le();function ge(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 a=d[t];d[t]=d[i],d[i]=a}if(d[n]<d[t]){let a=d[t];d[t]=d[n],d[n]=a}if(d[i]<d[n]){let a=d[i];d[i]=d[n],d[n]=a}let s=d[n],r=t;for(let a=t;a<n;a++)if(d[a]<=s){let c=d[r];d[r]=d[a],d[a]=c,r++}let o=d[r];if(d[r]=d[n],d[n]=o,r===e)return d[r];r<e?t=r+1:n=r-1}return d[t]}var z=1e4,G=5e4,H=.8,re={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},S=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...re,...t}}async spread(e,t=1,n){let i=e.filter(l=>this.graph.getConcept(l)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let l of i)this.graph.setActivation(l,t),this.recordActivation(l,t);let s=0,r=t,o=0,a=0;for(;s<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let l=await this.spreadIteration(),h=this.graph.getActiveNodes(this.config.threshold);for(let u of h)u.activationLevel>r&&(r=u.activationLevel);if(h.length===o&&l===0){if(a++,a>=3)break}else a=0;o=h.length,s++}let c=this.graph.getActiveNodes(this.config.threshold).map(l=>({nodeId:l.id,activation:l.activationLevel})).sort((l,h)=>h.activation-l.activation),p=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:s,nodesActivated:c.length,peakActivation:r,activatedNodes:c,novelAssociations:p.map(l=>({source:l.source.id,target:l.target.id,strength:l.coActivation}))}}async dream(e,t){let n=Date.now(),i=[],s=0,r=0,o=new Set,a=this.graph.getAllConcepts(0);if(a.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let c=n+e;for(;Date.now()<c&&!t?.aborted;){let h=X(0,a.length),u=a[h];if(u){let g=this.config.noiseLevel+N()*this.config.noiseLevel*2,f=u.activationLevel,v=Math.min(1,f+g+.3);this.graph.setActivation(u.id,v);let y=await this.spread([u.id],v,c);s+=y.iterations,y.peakActivation>r&&(r=y.peakActivation);for(let E of y.activatedNodes)o.add(E.nodeId);for(let E of y.novelAssociations)i.push(E)}if(Date.now()>=c||t?.aborted)break;await this.sleep(50+N()*50,t)}let p=this.deduplicateAssociations(i),l=Array.from(o).map(h=>{let u=this.graph.getConcept(h);return{nodeId:h,activation:u?.activationLevel??0}}).filter(h=>h.activation>0).sort((h,u)=>u.activation-h.activation);return this.trimHistory(),{iterations:s,nodesActivated:l.length,peakActivation:r,activatedNodes:l,novelAssociations:p.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((r,o)=>o.activationLevel-r.activationLevel).slice(0,i));let s=[];for(let r=0;r<n.length;r++)for(let o=r+1;o<n.length;o++){let a=n[r],c=n[o],p=Math.sqrt(a.activationLevel*c.activationLevel),l=this.graph.getEdge(a.id,c.id),h=this.graph.getEdge(c.id,a.id),u=l!==void 0||h!==void 0,g=l?.weight??h?.weight??0,f=!u||g<.3;p>.3&&(s.push({source:a,target:c,coActivation:p,isNovel:f}),this.trackCoActivation(a.id,c.id))}return s.sort((r,o)=>r.isNovel!==o.isNovel?r.isNovel?-1:1:o.coActivation-r.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=z)return;let e=Math.floor(z*H),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<=G)return;let e=Math.floor(G*H),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=ge(n,t-1),s=[];for(let[r,o]of this.coActivationCounts){if(s.length>=t)break;o<=i&&s.push(r)}for(let r of s)this.coActivationCounts.delete(r)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let s=this.graph.getEdges(i.id);for(let r of s){let o=this.graph.getConcept(r.target);if(!o)continue;let a=i.activationLevel*r.weight*this.config.spreadFactor;if(a>.01){let c=o.activationLevel,p=Math.min(1,c+a);n.push({nodeId:r.target,newActivation:p})}}}for(let i of n){let s=this.graph.getConcept(i.nodeId);s&&i.newActivation>s.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=(N()-.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(":"),s=t.get(i);(!s||n.strength>s.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e,t){return new Promise(n=>{let i=setTimeout(s,e);function s(){clearTimeout(i),t?.removeEventListener("abort",s),n()}t?.addEventListener("abort",s,{once:!0})})}};ue();import{randomUUID as fe}from"crypto";var se={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},I=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...se,...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 s=await this.detectPatternMerges(i);for(let c of s)c.cycleId=e,n.push(c);let r=await this.detectNovelAssociations(t.novelAssociations);for(let c of r)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let a=await this.detectGaps(i);for(let c of a)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,p)=>p.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let s=i+1;s<n.length;s++){let r=n[i],o=n[s],a=this.graph.getEdge(r.id,o.id),c=this.graph.getEdge(o.id,r.id),p=Math.max(a?.weight??0,c?.weight??0),l=this.calculateContentSimilarity(r.content,o.content),h=Math.sqrt(r.activationLevel*o.activationLevel),u=p*.4+l*.3+h*.3;if(u>.5){let g=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[r.id,o.id]}),f=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[r.id,o.id],edgeWeight:p,contentSimilarity:l,coActivation:h});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[r.id,o.id],description:this.generatePatternMergeDescription(r,o,u),noveltyScore:g,confidenceScore:f,actionable:f>=this.config.minConfidence,applied:!1,suggestedAction:f>=this.config.minConfidence?`Merge "${this.truncate(r.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),s=this.graph.getConcept(n.target);if(!i||!s)continue;let r=this.graph.getEdge(n.source,n.target);if(r&&r.weight>.5)continue;let o=i.conceptType!==s.conceptType,a=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,s,n.strength,o),noveltyScore:a,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(s.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??{},s=i.successRate,r=i.executionCount,o=i.confidence,a=s!==void 0&&s<.7,c=r!==void 0&&r>10,p=o!==void 0&&o<.6;if(a||c&&p){let l=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:a,hasHighUsage:c}),h=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:a,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,s,r),noveltyScore:l,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 s=i.conceptType??"pattern",r=J(n,s)??[];K(n,s,r),r.push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let a=this.graph.getConcept(o.target);return a&&(a.conceptType==="pattern"||a.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),a=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:a,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 a=this.graph.getConcept(o.target);return a&&a.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),a=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:a,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(s=>s.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=fe().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),s=new Set(n),r=new Set(i),o=n.filter(c=>r.has(c)),a=s.size+r.size-o.length;return a===0?0:o.length/a}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 s=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 ${s}% 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}}};Y();F();Q();he();import{existsSync as ve,unlinkSync as ye}from"fs";var M={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},$=class{constructor(e,t=M){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-N7EOGE5P.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 s=`/tmp/dream-branch-${t}.rvf`,r=this.rvfAdapter.derive(s),o=i;o._rvfBranchPath=s,o._rvfChildAdapter=r}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),s=i.patternCount-n.patternCount,r=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,a=[],c=!0;if(n.patternCount>0){let l=-s/n.patternCount;l>this.thresholds.maxPatternCountDrop&&(c=!1,a.push(`Pattern count dropped by ${(l*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(r<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,a.push(`Avg confidence dropped by ${(-r).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let l=o/n.highConfidenceCount;l>this.thresholds.maxHighConfidenceLoss&&(c=!1,a.push(`${o} high-confidence patterns lost (${(l*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let l=this.rvfAdapter.dimension?.()??384,h=new Float32Array(l);for(let g=0;g<l;g++)h[g]=Math.sin(g*.1);let u=this.rvfAdapter.search?.(h,10)??[];u.length<Math.min(5,n.patternCount)&&a.push(`Search recall degraded: only ${u.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let p=c?"All quality checks passed":`Validation failed: ${a.join("; ")}`;return{passed:c,reason:p,patternCountDelta:s,avgConfidenceDelta:r,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&ve(n)&&ye(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{}}};function U(d,e){let t=d.prepare(`
66
+ `).run(a,e);s+=c.changes}return s})(),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,s=t.get().count,r={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)r[c.concept_type]=c.count;let a=0;return i>0&&(a=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:s,byType:r,avgEdgesPerNode:i>0?s/i:0,avgActivation:a}}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?A(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 Ce(d){return new T(d)}fe();function De(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 a=d[t];d[t]=d[i],d[i]=a}if(d[n]<d[t]){let a=d[t];d[t]=d[n],d[n]=a}if(d[i]<d[n]){let a=d[i];d[i]=d[n],d[n]=a}let s=d[n],r=t;for(let a=t;a<n;a++)if(d[a]<=s){let c=d[r];d[r]=d[a],d[a]=c,r++}let o=d[r];if(d[r]=d[n],d[n]=o,r===e)return d[r];r<e?t=r+1:n=r-1}return d[t]}var z=1e4,G=5e4,H=.8,ce={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},S=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...ce,...t}}async spread(e,t=1,n){let i=e.filter(u=>this.graph.getConcept(u)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let u of i)this.graph.setActivation(u,t),this.recordActivation(u,t);let s=0,r=t,o=0,a=0;for(;s<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let u=await this.spreadIteration(),m=this.graph.getActiveNodes(this.config.threshold);for(let l of m)l.activationLevel>r&&(r=l.activationLevel);if(m.length===o&&u===0){if(a++,a>=3)break}else a=0;o=m.length,s++}let c=this.graph.getActiveNodes(this.config.threshold).map(u=>({nodeId:u.id,activation:u.activationLevel})).sort((u,m)=>m.activation-u.activation),p=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:s,nodesActivated:c.length,peakActivation:r,activatedNodes:c,novelAssociations:p.map(u=>({source:u.source.id,target:u.target.id,strength:u.coActivation}))}}async dream(e,t){let n=Date.now(),i=[],s=0,r=0,o=new Set,a=this.graph.getAllConcepts(0);if(a.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let c=n+e;for(;Date.now()<c&&!t?.aborted;){let m=J(0,a.length),l=a[m];if(l){let g=this.config.noiseLevel+N()*this.config.noiseLevel*2,f=l.activationLevel,v=Math.min(1,f+g+.3);this.graph.setActivation(l.id,v);let y=await this.spread([l.id],v,c);s+=y.iterations,y.peakActivation>r&&(r=y.peakActivation);for(let b of y.activatedNodes)o.add(b.nodeId);for(let b of y.novelAssociations)i.push(b)}if(Date.now()>=c||t?.aborted)break;await this.sleep(50+N()*50,t)}let p=this.deduplicateAssociations(i),u=Array.from(o).map(m=>{let l=this.graph.getConcept(m);return{nodeId:m,activation:l?.activationLevel??0}}).filter(m=>m.activation>0).sort((m,l)=>l.activation-m.activation);return this.trimHistory(),{iterations:s,nodesActivated:u.length,peakActivation:r,activatedNodes:u,novelAssociations:p.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((r,o)=>o.activationLevel-r.activationLevel).slice(0,i));let s=[];for(let r=0;r<n.length;r++)for(let o=r+1;o<n.length;o++){let a=n[r],c=n[o],p=Math.sqrt(a.activationLevel*c.activationLevel),u=this.graph.getEdge(a.id,c.id),m=this.graph.getEdge(c.id,a.id),l=u!==void 0||m!==void 0,g=u?.weight??m?.weight??0,f=!l||g<.3;p>.3&&(s.push({source:a,target:c,coActivation:p,isNovel:f}),this.trackCoActivation(a.id,c.id))}return s.sort((r,o)=>r.isNovel!==o.isNovel?r.isNovel?-1:1:o.coActivation-r.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=z)return;let e=Math.floor(z*H),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<=G)return;let e=Math.floor(G*H),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=De(n,t-1),s=[];for(let[r,o]of this.coActivationCounts){if(s.length>=t)break;o<=i&&s.push(r)}for(let r of s)this.coActivationCounts.delete(r)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let s=this.graph.getEdges(i.id);for(let r of s){let o=this.graph.getConcept(r.target);if(!o)continue;let a=i.activationLevel*r.weight*this.config.spreadFactor;if(a>.01){let c=o.activationLevel,p=Math.min(1,c+a);n.push({nodeId:r.target,newActivation:p})}}}for(let i of n){let s=this.graph.getConcept(i.nodeId);s&&i.newActivation>s.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=(N()-.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(":"),s=t.get(i);(!s||n.strength>s.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e,t){return new Promise(n=>{let i=setTimeout(s,e);function s(){clearTimeout(i),t?.removeEventListener("abort",s),n()}t?.addEventListener("abort",s,{once:!0})})}};ve();import{randomUUID as Ee}from"crypto";var de={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},I=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...de,...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 s=await this.detectPatternMerges(i);for(let c of s)c.cycleId=e,n.push(c);let r=await this.detectNovelAssociations(t.novelAssociations);for(let c of r)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let a=await this.detectGaps(i);for(let c of a)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,p)=>p.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let s=i+1;s<n.length;s++){let r=n[i],o=n[s],a=this.graph.getEdge(r.id,o.id),c=this.graph.getEdge(o.id,r.id),p=Math.max(a?.weight??0,c?.weight??0),u=this.calculateContentSimilarity(r.content,o.content),m=Math.sqrt(r.activationLevel*o.activationLevel),l=p*.4+u*.3+m*.3;if(l>.5){let g=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[r.id,o.id]}),f=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[r.id,o.id],edgeWeight:p,contentSimilarity:u,coActivation:m});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[r.id,o.id],description:this.generatePatternMergeDescription(r,o,l),noveltyScore:g,confidenceScore:f,actionable:f>=this.config.minConfidence,applied:!1,suggestedAction:f>=this.config.minConfidence?`Merge "${this.truncate(r.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),s=this.graph.getConcept(n.target);if(!i||!s)continue;let r=this.graph.getEdge(n.source,n.target);if(r&&r.weight>.5)continue;let o=i.conceptType!==s.conceptType,a=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,s,n.strength,o),noveltyScore:a,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(s.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??{},s=i.successRate,r=i.executionCount,o=i.confidence,a=s!==void 0&&s<.7,c=r!==void 0&&r>10,p=o!==void 0&&o<.6;if(a||c&&p){let u=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:a,hasHighUsage:c}),m=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:a,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,s,r),noveltyScore:u,confidenceScore:m,actionable:m>=this.config.minConfidence,applied:!1,suggestedAction:m>=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 s=i.conceptType??"pattern",r=K(n,s)??[];Z(n,s,r),r.push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let a=this.graph.getConcept(o.target);return a&&(a.conceptType==="pattern"||a.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),a=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:a,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 a=this.graph.getConcept(o.target);return a&&a.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),a=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:a,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(s=>s.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=Ee().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),s=new Set(n),r=new Set(i),o=n.filter(c=>r.has(c)),a=s.size+r.size-o.length;return a===0?0:o.length/a}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 s=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 ${s}% 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}}};X();F();Y();ye();import{existsSync as be,unlinkSync as Ae}from"fs";var x={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},$=class{constructor(e,t=x){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-5JCSKL2P.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 s=`/tmp/dream-branch-${t}.rvf`,r=this.rvfAdapter.derive(s),o=i;o._rvfBranchPath=s,o._rvfChildAdapter=r}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),s=i.patternCount-n.patternCount,r=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,a=[],c=!0;if(n.patternCount>0){let u=-s/n.patternCount;u>this.thresholds.maxPatternCountDrop&&(c=!1,a.push(`Pattern count dropped by ${(u*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(r<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,a.push(`Avg confidence dropped by ${(-r).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let u=o/n.highConfidenceCount;u>this.thresholds.maxHighConfidenceLoss&&(c=!1,a.push(`${o} high-confidence patterns lost (${(u*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let u=this.rvfAdapter.dimension?.()??384,m=new Float32Array(u);for(let g=0;g<u;g++)m[g]=Math.sin(g*.1);let l=this.rvfAdapter.search?.(m,10)??[];l.length<Math.min(5,n.patternCount)&&a.push(`Search recall degraded: only ${l.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let p=c?"All quality checks passed":`Validation failed: ${a.join("; ")}`;return{passed:c,reason:p,patternCountDelta:s,avgConfidenceDelta:r,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&be(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{}}};function U(d,e){let t=d.prepare(`
67
67
  UPDATE concept_nodes
68
68
  SET activation_level = ?, last_activated = datetime('now')
69
69
  WHERE id = ? AND (? IS NULL OR COALESCE(activation_level, 0) = ?)
@@ -83,13 +83,13 @@ import{a as ie}from"./chunk-N4CYAKOX.js";import{c as te,d as ne}from"./chunk-3AN
83
83
  associations_found = excluded.associations_found,
84
84
  insights_generated = excluded.insights_generated,
85
85
  status = excluded.status, error = excluded.error
86
- `),s=d.transaction(()=>{let{cycle:a}=e;i.run(a.id,a.startTime.toISOString(),a.endTime?.toISOString()??null,a.durationMs??null,a.conceptsProcessed,a.associationsFound,a.insightsGenerated,a.status,a.error??null);let c=0;for(let[p,l,h]of e.activations){let u=h??null;c+=t.run(Math.max(0,Math.min(1,l)),p,u,u).changes}for(let p of e.insights)n.run(p.id,p.cycleId,p.type,JSON.stringify(p.sourceConcepts),p.description,p.noveltyScore,p.confidenceScore,p.actionable?1:0,p.suggestedAction??null);return{activationsWritten:c,activationsSkipped:e.activations.length-c,insightsWritten:e.insights.length}}),r=performance.now();return{...s.immediate(),commitDurationMs:performance.now()-r}}var x=600*1e3,Ce="abandoned: process exited";function q(d,e=x,t=Date.now()){let n=new Date(t-e).toISOString();return d.prepare(`
86
+ `),s=d.transaction(()=>{let{cycle:a}=e;i.run(a.id,a.startTime.toISOString(),a.endTime?.toISOString()??null,a.durationMs??null,a.conceptsProcessed,a.associationsFound,a.insightsGenerated,a.status,a.error??null);let c=0;for(let[p,u,m]of e.activations){let l=m??null;c+=t.run(Math.max(0,Math.min(1,u)),p,l,l).changes}for(let p of e.insights)n.run(p.id,p.cycleId,p.type,JSON.stringify(p.sourceConcepts),p.description,p.noveltyScore,p.confidenceScore,p.actionable?1:0,p.suggestedAction??null);return{activationsWritten:c,activationsSkipped:e.activations.length-c,insightsWritten:e.insights.length}}),r=performance.now();return{...s.immediate(),commitDurationMs:performance.now()-r}}var L=600*1e3,Te="abandoned: process exited";function q(d,e=L,t=Date.now()){let n=new Date(t-e).toISOString();return d.prepare(`
87
87
  UPDATE dream_cycles
88
88
  SET status = 'interrupted',
89
89
  error = ?,
90
90
  end_time = COALESCE(end_time, ?)
91
91
  WHERE status = 'running' AND start_time < ?
92
- `).run(Ce,new Date(t).toISOString(),n).changes}var b=_.create("dream-engine"),ae={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!1,branchValidationThresholds:{...M}},De=6e4,L=class extends Error{constructor(t){super(`A dream cycle is already running (cycle ${t}); wait for it to finish or cancel it`);this.cycleId=t;this.name="DreamAlreadyRunningError"}cycleId},W=class{constructor(e){this.graph=e}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;loadedLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear(),this.loadedLevels.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),this.loadedLevels.set(n.id,n.activationLevel);for(let n of t){let s=(await this.graph.getNeighbors(n.id)).map(r=>r.edge);this.edgeCache.set(n.id,s)}}activationEntries(){return Array.from(this.activationLevels.entries(),([e,t])=>[e,t,this.loadedLevels.get(e)])}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let r of e)t[r.conceptType]=(t[r.conceptType]??0)+1,n+=this.activationLevels.get(r.id)??r.activationLevel;let i=0,s=Array.from(this.edgeCache.values());for(let r of s)i+=r.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},w=class{config;persistence=null;graph=null;db=null;interruptActiveDream=null;activeDream=null;activeAbort=null;currentCycle=null;initialized=!1;cancelled=!1;cancelRequests=0;closing=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}set rvfAdapter(e){}constructor(e){this.config={...ae,...e}}async initialize(){if(!this.initialized)try{this.persistence=R(),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&&b.warn("DreamConfig.enableBranching is deprecated and ignored (#1060): dream results are committed in one short transaction instead of a SAVEPOINT held across the dream");let e=q(this.db,Math.max(this.config.maxDurationMs,De)+x);e>0&&b.info("Marked abandoned dream cycles as interrupted",{abandoned:e}),this.initialized=!0,this.closing=!1,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(a=>a.name==="duration_ms"),n=e.some(a=>a.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(),s=new Set(i.map(a=>a.name)),r=s.has("insight_type"),o=s.has("source_concepts");if(!r)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),b.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 '[]'"),b.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){b.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e,t={}){if(this.ensureInitialized(),this.closing)throw new Error("Dream engine is closing; no new dream is started");if(this.activeDream)throw new L(this.activeDream.cycleId);let n={id:D(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},i=this.runDream(n,e??this.config.maxDurationMs,t);this.activeDream={cycleId:n.id,done:i.catch(()=>{})};try{return await i}finally{this.activeDream?.cycleId===n.id&&(this.activeDream=null)}}async runDream(e,t,n){let i=this.db,s=this.graph,r=Date.now(),o=new AbortController;this.activeAbort=o,this.cancelled=!1,this.currentCycle=e;let a=n.commit!==!1,c=this.createCycleInterrupter(e,r,o);this.interruptActiveDream=c;let p=Z(c),l=()=>!this.cancelled&&!o.signal.aborted&&this.db===i,h=!1;try{if(a&&await this.saveCycle(e),!l())throw new Error("Dream cycle cancelled");let u=n.minConceptsRequired??this.config.minConceptsRequired,g=await s.getActiveNodes(0);if(g.length<u)throw new Error(`Insufficient concepts: ${g.length} < ${u}`);let f=new W(s);await f.loadIntoMemory(30);let y=await new S(f,{...this.config.activationConfig,...n.activationConfig}).dream(t,o.signal);if(!l())throw new Error("Dream cycle cancelled");e.conceptsProcessed=y.nodesActivated,e.associationsFound=y.novelAssociations.length;let O=await new I(f,this.config.insightConfig).generateFromActivation(e.id,y);if(!l())throw new Error("Dream cycle cancelled");e.insightsGenerated=O.length,e.endTime=new Date,e.durationMs=Date.now()-r,e.status="completed";let j={cycle:e,activations:f.activationEntries(),insights:O},B={cycle:{...e},insights:O,activationStats:{totalIterations:y.iterations,peakActivation:y.peakActivation,nodesActivated:y.nodesActivated},patternsCreated:0};return a?(B.commitDurationMs=this.commitComputed(i,j),h=!0,B):(h=!0,{...B,pending:j})}catch(u){if(!h&&e.status!=="interrupted"&&(e.status=this.cancelled?"interrupted":"failed",e.error=C(u),e.endTime=new Date,e.durationMs=Date.now()-r,a&&this.db===i))try{this.updateCycleSync(e)}catch{}if(!h&&a)try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:e.id,reason:C(u)},"dream-engine")}catch{}throw u}finally{p(),this.interruptActiveDream===c&&(this.interruptActiveDream=null),this.currentCycle===e&&(this.currentCycle=null),this.activeAbort===o&&(this.activeAbort=null)}}commitDreamResult(e){if(this.ensureInitialized(),this.closing)throw new Error("Dream engine is closing; nothing is committed");if(!e.pending)throw new Error("Dream result has nothing pending to commit (it was already committed)");let t=this.commitComputed(this.db,e.pending);return e.pending=void 0,e.commitDurationMs=t,t}commitComputed(e,t){let n=U(e,t);try{this._witnessChain?.append("DREAM_COMMIT",{cycleId:t.cycle.id,insights:n.insightsWritten,activations:n.activationsWritten,commitDurationMs:n.commitDurationMs},"dream-engine")}catch{}return n.commitDurationMs}createCycleInterrupter(e,t,n){return()=>{if(n.abort(),!(e.status!=="running"||!this.db)){e.status="interrupted",e.error="Interrupted: engine closed or process shut down during the dream cycle",e.endTime=new Date,e.durationMs=Date.now()-t;try{this.updateCycleSync(e)}catch{}}}}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
92
+ `).run(Te,new Date(t).toISOString(),n).changes}var E=R.create("dream-engine"),pe=!1,Se=1e3,ue={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!1,branchValidationThresholds:{...x}},Ie=6e4,P=class extends Error{constructor(t){super(`A dream cycle is already running (cycle ${t}); wait for it to finish or cancel it`);this.cycleId=t;this.name="DreamAlreadyRunningError"}cycleId},W=class{constructor(e){this.graph=e}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;loadedLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear(),this.loadedLevels.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),this.loadedLevels.set(n.id,n.activationLevel);for(let n of t){let s=(await this.graph.getNeighbors(n.id)).map(r=>r.edge);this.edgeCache.set(n.id,s)}}activationEntries(){return Array.from(this.activationLevels.entries(),([e,t])=>[e,t,this.loadedLevels.get(e)])}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let r of e)t[r.conceptType]=(t[r.conceptType]??0)+1,n+=this.activationLevels.get(r.id)??r.activationLevel;let i=0,s=Array.from(this.edgeCache.values());for(let r of s)i+=r.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},_=class{config;persistence=null;graph=null;db=null;interruptActiveDream=null;activeDream=null;activeAbort=null;currentCycle=null;initialized=!1;cancelled=!1;cancelRequests=0;closing=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}set rvfAdapter(e){}constructor(e){this.config={...ue,...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 T,await this.graph.initialize(),this.config.enableBranching&&E.warn("DreamConfig.enableBranching is deprecated and ignored (#1060): dream results are committed in one short transaction instead of a SAVEPOINT held across the dream");let e=q(this.db,Math.max(this.config.maxDurationMs,Ie)+L);e>0&&E.info("Marked abandoned dream cycles as interrupted",{abandoned:e}),this.initialized=!0,this.closing=!1,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(a=>a.name==="duration_ms"),n=e.some(a=>a.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(),s=new Set(i.map(a=>a.name)),r=s.has("insight_type"),o=s.has("source_concepts");if(!r)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),E.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 '[]'"),E.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){E.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e,t={}){if(this.ensureInitialized(),this.closing)throw new Error("Dream engine is closing; no new dream is started");if(this.activeDream)throw new P(this.activeDream.cycleId);let n={id:D(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},i=this.runDream(n,e??this.config.maxDurationMs,t);this.activeDream={cycleId:n.id,done:i.catch(()=>{})};try{return await i}finally{this.activeDream?.cycleId===n.id&&(this.activeDream=null)}}async runDream(e,t,n){let i=this.db,s=this.graph,r=Date.now(),o=new AbortController;this.activeAbort=o,this.cancelled=!1,this.currentCycle=e;let a=n.commit!==!1,c=this.createCycleInterrupter(e,r,o);this.interruptActiveDream=c;let p=ee(c),u=()=>!this.cancelled&&!o.signal.aborted&&this.db===i,m=!1;try{if(a&&await this.saveCycle(e),!u())throw new Error("Dream cycle cancelled");let l=n.minConceptsRequired??this.config.minConceptsRequired,g=await s.getActiveNodes(0);if(g.length<l)throw new Error(`Insufficient concepts: ${g.length} < ${l}`);let f=new W(s);await f.loadIntoMemory(30);let y=await new S(f,{...this.config.activationConfig,...n.activationConfig}).dream(t,o.signal);if(!u())throw new Error("Dream cycle cancelled");e.conceptsProcessed=y.nodesActivated,e.associationsFound=y.novelAssociations.length;let B=await new I(f,this.config.insightConfig).generateFromActivation(e.id,y);if(!u())throw new Error("Dream cycle cancelled");e.insightsGenerated=B.length,e.endTime=new Date,e.durationMs=Date.now()-r,e.status="completed";let j={cycle:e,activations:f.activationEntries(),insights:B},w={cycle:{...e},insights:B,activationStats:{totalIterations:y.iterations,peakActivation:y.peakActivation,nodesActivated:y.nodesActivated},patternsCreated:0};if(!a)return m=!0,{...w,pending:j};let Q=this.commitComputed(i,j);return m=!0,w.commitDurationMs=Q.durationMs,w.retention=Q.retention,w}catch(l){if(!m&&e.status!=="interrupted"&&(e.status=this.cancelled?"interrupted":"failed",e.error=C(l),e.endTime=new Date,e.durationMs=Date.now()-r,a&&this.db===i))try{this.updateCycleSync(e)}catch{}if(!m&&a)try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:e.id,reason:C(l)},"dream-engine")}catch{}throw l}finally{p(),this.interruptActiveDream===c&&(this.interruptActiveDream=null),this.currentCycle===e&&(this.currentCycle=null),this.activeAbort===o&&(this.activeAbort=null)}}commitDreamResult(e){if(this.ensureInitialized(),this.closing)throw new Error("Dream engine is closing; nothing is committed");if(!e.pending)throw new Error("Dream result has nothing pending to commit (it was already committed)");let t=this.commitComputed(this.db,e.pending);return e.pending=void 0,e.commitDurationMs=t.durationMs,e.retention=t.retention,t.durationMs}commitComputed(e,t){let n=U(e,t);try{this._witnessChain?.append("DREAM_COMMIT",{cycleId:t.cycle.id,insights:n.insightsWritten,activations:n.activationsWritten,commitDurationMs:n.commitDurationMs},"dream-engine")}catch{}return{durationMs:n.commitDurationMs,retention:this.runDefaultRetention(e)}}runDefaultRetention(e){let t=se();if(t.warnings.length>0&&!pe){pe=!0;for(let i of t.warnings)E.warn(i)}let n=e.pragma("busy_timeout",{simple:!0});try{e.pragma(`busy_timeout = ${Se}`);let i=ae(e,t);if(i.enabled)for(let s of i.steps)s.affected>0&&E.info(`Retention ${oe(s)}`);return i}catch(i){return E.warn("Dream retention skipped after dream commit",{error:C(i)}),{enabled:t.enabled,steps:[],error:C(i)}}finally{try{e.pragma(`busy_timeout = ${n}`)}catch{}}}createCycleInterrupter(e,t,n){return()=>{if(n.abort(),!(e.status!=="running"||!this.db)){e.status="interrupted",e.error="Interrupted: engine closed or process shut down during the dream cycle",e.endTime=new Date,e.durationMs=Date.now()-t;try{this.updateCycleSync(e)}catch{}}}}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
93
93
  FROM qe_pattern_nulls n
94
94
  JOIN qe_patterns p ON p.id = n.pattern_id
95
95
  ORDER BY n.updated_at DESC
@@ -99,7 +99,7 @@ import{a as ie}from"./chunk-N4CYAKOX.js";import{c as te,d as ne}from"./chunk-3AN
99
99
  JOIN qe_patterns p ON p.id = u.pattern_id
100
100
  WHERE u.success = 1
101
101
  ORDER BY u.created_at DESC
102
- LIMIT 100`).all();i.length>0&&await this.graph.loadSuccessesAsOutcomes(i)}catch(n){process.env.DEBUG&&b.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 (
102
+ LIMIT 100`).all();i.length>0&&await this.graph.loadSuccessesAsOutcomes(i)}catch(n){process.env.DEBUG&&E.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 (
103
103
  SELECT id, name, description, qe_domain as domain, pattern_type as patternType,
104
104
  confidence, success_rate as successRate
105
105
  FROM qe_patterns
@@ -115,7 +115,7 @@ import{a as ie}from"./chunk-N4CYAKOX.js";import{c as te,d as ne}from"./chunk-3AN
115
115
  WHERE confidence >= 0.3 AND success_rate < 0.7
116
116
  ORDER BY usage_count DESC
117
117
  LIMIT 40
118
- )`).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-WCACU3FN.js"),{createQEReasoningBank:i}=await import("./qe-reasoning-bank-DQSSX2IP.js"),s=await n(),r=i(s);await r.initialize();try{let{getSharedRvfDualWriter:h}=await import("./shared-rvf-dual-writer-YXMPZKQE.js"),u=await h();u&&r.setRvfDualWriter(u)}catch(h){process.env.DEBUG&&b.debug("RVF wiring skipped",{error:C(h)})}let o=[];try{o=A(t.source_concepts)}catch{}let a=await r.storePattern({patternType:Ee(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"}}),c=!a.success&&a.error instanceof ee&&a.error.disposition==="COMMITTED_PENDING_INDEX"?a.error:null;if(!a.success&&!c)return{success:!1,error:`Failed to create pattern: ${a.error?.message??"unknown error"}`};let p=a.success?a.value.id:c.patternId;return c&&b.warn("Insight applied; pattern committed with vector index pending",{insightId:e,patternId:p,cause:C(c.cause)}),this.db.prepare(`
118
+ )`).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-XPWGYDKD.js"),{createQEReasoningBank:i}=await import("./qe-reasoning-bank-GRXBT7FC.js"),s=await n(),r=i(s);await r.initialize();try{let{getSharedRvfDualWriter:m}=await import("./shared-rvf-dual-writer-6KENLN2W.js"),l=await m();l&&r.setRvfDualWriter(l)}catch(m){process.env.DEBUG&&E.debug("RVF wiring skipped",{error:C(m)})}let o=[];try{o=A(t.source_concepts)}catch{}let a=await r.storePattern({patternType:_e(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"}}),c=!a.success&&a.error instanceof te&&a.error.disposition==="COMMITTED_PENDING_INDEX"?a.error:null;if(!a.success&&!c)return{success:!1,error:`Failed to create pattern: ${a.error?.message??"unknown error"}`};let p=a.success?a.value.id:c.patternId;return c&&E.warn("Insight applied; pattern committed with vector index pending",{insightId:e,patternId:p,cause:C(c.cause)}),this.db.prepare(`
119
119
  UPDATE dream_insights
120
120
  SET applied = 1, pattern_id = ?
121
121
  WHERE id = ?
@@ -138,4 +138,4 @@ import{a as ie}from"./chunk-N4CYAKOX.js";import{c as te,d as ne}from"./chunk-3AN
138
138
  SET end_time = ?, duration_ms = ?, concepts_processed = ?, associations_found = ?,
139
139
  insights_generated = ?, status = ?, error = ?
140
140
  WHERE id = ?
141
- `).run(e.endTime?.toISOString()??null,e.durationMs??null,e.conceptsProcessed,e.associationsFound,e.insightsGenerated,e.status,e.error??null,e.id)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return null}onBranchEvent(e){this.branchEventListeners.push(e)}async close(){this.closing=!0,this.cancelRequests++,this.interruptActiveDream?.(),this.interruptActiveDream=null,this.activeAbort?.abort();let e=this.activeDream?.done;if(e){let t;await Promise.race([e,new Promise(n=>{t=setTimeout(n,2e3)})]),clearTimeout(t)}this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=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:A(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 Ee(d){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[d]||"test-template"}function be(d){let e=new w(d);return import("./feature-flags-N7EOGE5P.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-COUOS665.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var Ae=w;Q();var oe="learning:loop-health";async function ce(d,e,t){try{let n=new Date().toISOString(),i=await d.get(oe)??{overallLastSuccess:"",bootedAt:n,components:{}},s=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(s.ticksSinceBoot+=1,t.success)s.lastSuccessAt=n,s.successesSinceBoot+=1,delete s.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);s.lastError={message:o,at:n}}i.components[e]=s;let r=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=r.length>0?r.sort().pop():"",await d.set(oe,i)}catch{}}var m=_.create("DreamScheduler"),pe={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},de="dream-scheduler:hook-state",P=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={...pe,...t},this.metaLearningEngine=new ne}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,m.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),m.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),m.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,m.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&&(m.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{m.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,m.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&m.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(s){m.warn("Post-dream meta-learning failed (non-critical)",{error:s instanceof Error?s.message:String(s)})}return this.running&&this.scheduleNextDream(),m.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 ce(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&&m.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){m.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-COUOS665.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&m.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){m.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-YXMPZKQE.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&m.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){m.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new ie,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=te.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){m.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)m.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:D(),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{m.debug("Failed to publish meta-learning insight event")}}}else m.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){m.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),m.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){m.info("Quality gate failed but cannot start dream yet");return}m.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){m.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){m.info("Milestone reached but cannot start dream yet");return}m.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){m.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:D(),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){m.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(de),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(de,t)}catch(e){m.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){m.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??[],m.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){m.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 Te(d,e){return new P(d,e)}F();var Se=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],V=class{constructor(e){this.engine=e}engine;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=[],s=this.engine.cancelCount,r=()=>this.engine.cancelCount!==s;for(let c of e){if(r())break;i.push(await this.executeStrategy(c,t.durationMs))}if(r())return{strategies:i,winner:null,totalDurationMs:Date.now()-n,cancelled:!0};let o=null;for(let c of i)c.result&&(!o||c.score>o.score)&&(o=c);let a;if(o?.result)try{a=this.engine.commitDreamResult(o.result),o.selected=!0}catch(c){o.error=C(c),o=null}return{strategies:i,winner:o,totalDurationMs:Date.now()-n,commitDurationMs:a,cancelled:!1}}async executeStrategy(e,t){let n=Date.now();try{let i=await this.engine.dream(t,{activationConfig:e.activationConfig,commit:!1});return{strategy:e,result:i,score:this.scoreResult(i),selected:!1,durationMs:Date.now()-n}}catch(i){return{strategy:e,result:null,score:Number.NEGATIVE_INFINITY,error:C(i),selected:!1,durationMs:Date.now()-n}}}scoreResult(e){return e.insights.reduce((n,i)=>n+i.confidenceScore*i.noveltyScore,0)+e.cycle.associationsFound*.01}};export{ce as a,pe as b,P as c,Te as d,k as e,T as f,me as g,z as h,G as i,H as j,re as k,S as l,se as m,I as n,M as o,$ as p,U as q,x as r,q as s,ae as t,L as u,w as v,be as w,Ae as x,Se as y,V as z};
141
+ `).run(e.endTime?.toISOString()??null,e.durationMs??null,e.conceptsProcessed,e.associationsFound,e.insightsGenerated,e.status,e.error??null,e.id)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return null}onBranchEvent(e){this.branchEventListeners.push(e)}async close(){this.closing=!0,this.cancelRequests++,this.interruptActiveDream?.(),this.interruptActiveDream=null,this.activeAbort?.abort();let e=this.activeDream?.done;if(e){let t;await Promise.race([e,new Promise(n=>{t=setTimeout(n,2e3)})]),clearTimeout(t)}this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=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:A(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 _e(d){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[d]||"test-template"}function we(d){let e=new _(d);return import("./feature-flags-5JCSKL2P.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-ABY7PAY2.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var Re=_;Y();var le="learning:loop-health";async function me(d,e,t){try{let n=new Date().toISOString(),i=await d.get(le)??{overallLastSuccess:"",bootedAt:n,components:{}},s=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(s.ticksSinceBoot+=1,t.success)s.lastSuccessAt=n,s.successesSinceBoot+=1,delete s.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);s.lastError={message:o,at:n}}i.components[e]=s;let r=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=r.length>0?r.sort().pop():"",await d.set(le,i)}catch{}}var h=R.create("DreamScheduler"),ge={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},he="dream-scheduler:hook-state",O=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={...ge,...t},this.metaLearningEngine=new ie}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,h.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),h.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),h.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,h.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&&(h.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{h.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,h.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&h.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(s){h.warn("Post-dream meta-learning failed (non-critical)",{error:s instanceof Error?s.message:String(s)})}return this.running&&this.scheduleNextDream(),h.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 me(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&&h.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){h.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-ABY7PAY2.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&h.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){h.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-6KENLN2W.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&h.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){h.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new re,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=ne.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){h.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)h.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:D(),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{h.debug("Failed to publish meta-learning insight event")}}}else h.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){h.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),h.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){h.info("Quality gate failed but cannot start dream yet");return}h.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){h.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){h.info("Milestone reached but cannot start dream yet");return}h.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){h.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:D(),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){h.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(he),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(he,t)}catch(e){h.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){h.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??[],h.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){h.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 Ne(d,e){return new O(d,e)}F();var Me=[{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}}],V=class{constructor(e){this.engine=e}engine;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=[],s=this.engine.cancelCount,r=()=>this.engine.cancelCount!==s;for(let c of e){if(r())break;i.push(await this.executeStrategy(c,t.durationMs))}if(r())return{strategies:i,winner:null,totalDurationMs:Date.now()-n,cancelled:!0};let o=null;for(let c of i)c.result&&(!o||c.score>o.score)&&(o=c);let a;if(o?.result)try{a=this.engine.commitDreamResult(o.result),o.selected=!0}catch(c){o.error=C(c),o=null}return{strategies:i,winner:o,totalDurationMs:Date.now()-n,commitDurationMs:a,cancelled:!1}}async executeStrategy(e,t){let n=Date.now();try{let i=await this.engine.dream(t,{activationConfig:e.activationConfig,commit:!1});return{strategy:e,result:i,score:this.scoreResult(i),selected:!1,durationMs:Date.now()-n}}catch(i){return{strategy:e,result:null,score:Number.NEGATIVE_INFINITY,error:C(i),selected:!1,durationMs:Date.now()-n}}}scoreResult(e){return e.insights.reduce((n,i)=>n+i.confidenceScore*i.noveltyScore,0)+e.cycle.associationsFound*.01}};export{me as a,ge as b,O as c,Ne as d,k as e,T as f,Ce as g,z as h,G as i,H as j,ce as k,S as l,de as m,I as n,x as o,$ as p,U as q,L as r,q as s,ue as t,P as u,_ as v,we as w,Re as x,Me as y,V as z};
@@ -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.15.13");process.exit(0)}
2
- import{a as f,b as u,d as m}from"./chunk-UOC3O6RP.js";import{b as c}from"./chunk-ZAKQLAHT.js";function v(s){switch(s.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 d,l=c(()=>{"use strict";d={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR",4:"SILENT"}});var a,r,g,h=c(()=>{"use strict";l();m();a={includeTimestamp:!0,includeLevel:!0,timestampFormat:"short",prettyPrint:!1,maxContextDepth:3},r=class s{domain;level;config;inheritedContext;constructor(e,t=1,n={},o={}){this.domain=e,this.level=t,this.config={...a,...n},this.inheritedContext=o}debug(e,t){this.level<=0&&this.output(0,e,t)}info(e,t){this.level<=1&&this.output(1,e,t)}warn(e,t){this.level<=2&&this.output(2,e,t)}error(e,t,n){if(this.level<=3){let o={...n};if(t){o.errorName=t.name,o.errorMessage=t.message,t.stack&&(o.stack=t.stack);let i=t;i.cause!==void 0&&(o.cause=i.cause)}this.output(3,e,o)}}isEnabled(e){return this.level<=e}getDomain(){return this.domain}child(e){return new s(this.domain,this.level,this.config,{...this.inheritedContext,...e})}output(e,t,n){let o=this.format(e,t,n);switch(e){case 0:console.debug(o);break;case 1:console.info(o);break;case 2:console.warn(o);break;case 3:console.error(o);break}}format(e,t,n){let o=[];this.config.includeTimestamp&&o.push(this.formatTimestamp()),this.config.includeLevel&&o.push(this.formatLevel(e)),o.push(`[${this.domain}]`),o.push(f(t));let i=this.mergeContext(n);return i&&Object.keys(i).length>0&&o.push(this.formatContext(i)),o.join(" ")}formatTimestamp(){let e=new Date;if(this.config.timestampFormat==="iso")return`[${e.toISOString()}]`;let t=String(e.getHours()).padStart(2,"0"),n=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),i=String(e.getMilliseconds()).padStart(3,"0");return`[${t}:${n}:${o}.${i}]`}formatLevel(e){return`[${d[e].padEnd(5)}]`}mergeContext(e){if(!(!e&&Object.keys(this.inheritedContext).length===0))return{...this.inheritedContext,...e}}formatContext(e){try{let t=u(e,{maxDepth:this.config.maxContextDepth+1});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.15.14");process.exit(0)}
2
+ import{a as f,b as u,d as m}from"./chunk-IRPNEXOU.js";import{b as c}from"./chunk-V6SE2ZU2.js";function v(s){switch(s.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 d,l=c(()=>{"use strict";d={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR",4:"SILENT"}});var a,r,g,h=c(()=>{"use strict";l();m();a={includeTimestamp:!0,includeLevel:!0,timestampFormat:"short",prettyPrint:!1,maxContextDepth:3},r=class s{domain;level;config;inheritedContext;constructor(e,t=1,n={},o={}){this.domain=e,this.level=t,this.config={...a,...n},this.inheritedContext=o}debug(e,t){this.level<=0&&this.output(0,e,t)}info(e,t){this.level<=1&&this.output(1,e,t)}warn(e,t){this.level<=2&&this.output(2,e,t)}error(e,t,n){if(this.level<=3){let o={...n};if(t){o.errorName=t.name,o.errorMessage=t.message,t.stack&&(o.stack=t.stack);let i=t;i.cause!==void 0&&(o.cause=i.cause)}this.output(3,e,o)}}isEnabled(e){return this.level<=e}getDomain(){return this.domain}child(e){return new s(this.domain,this.level,this.config,{...this.inheritedContext,...e})}output(e,t,n){let o=this.format(e,t,n);switch(e){case 0:console.debug(o);break;case 1:console.info(o);break;case 2:console.warn(o);break;case 3:console.error(o);break}}format(e,t,n){let o=[];this.config.includeTimestamp&&o.push(this.formatTimestamp()),this.config.includeLevel&&o.push(this.formatLevel(e)),o.push(`[${this.domain}]`),o.push(f(t));let i=this.mergeContext(n);return i&&Object.keys(i).length>0&&o.push(this.formatContext(i)),o.join(" ")}formatTimestamp(){let e=new Date;if(this.config.timestampFormat==="iso")return`[${e.toISOString()}]`;let t=String(e.getHours()).padStart(2,"0"),n=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),i=String(e.getMilliseconds()).padStart(3,"0");return`[${t}:${n}:${o}.${i}]`}formatLevel(e){return`[${d[e].padEnd(5)}]`}mergeContext(e){if(!(!e&&Object.keys(this.inheritedContext).length===0))return{...this.inheritedContext,...e}}formatContext(e){try{let t=u(e,{maxDepth:this.config.maxContextDepth+1});return this.config.prettyPrint?`
3
3
  `+JSON.stringify(t,null,2):JSON.stringify(t)}catch{return"[unserializable context]"}}},g=class{domain;constructor(e="null"){this.domain=e}debug(e,t){}info(e,t){}warn(e,t){}error(e,t,n){}isEnabled(e){return!1}getDomain(){return this.domain}child(e){return this}}});function w(s,e){return L.create(s,e)}var C,L,x=c(()=>{"use strict";l();h();C={defaultLevel:1,domainLevels:new Map,consoleConfig:a,silent:!1},L=class{static config={...C};static customProvider=null;static instances=new Map;static setLevel(e){this.config.defaultLevel=e,this.instances.clear()}static setLevelFromString(e){this.setLevel(v(e))}static getLevel(){return this.config.defaultLevel}static setDomainLevel(e,t){this.config.domainLevels.set(e,t),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,t){if(!t&&this.instances.has(e))return this.instances.get(e);let n=this.getDomainLevel(e),o;return this.config.silent?o=new g(e):this.customProvider?o=this.customProvider(e,n,t):o=new r(e,n,this.config.consoleConfig,t),t||this.instances.set(e,o),o}static getLogger(e,t){return this.create(e,t)}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 t=process.env.LOG_TIMESTAMP;t!==void 0&&this.configure({includeTimestamp:t.toLowerCase()==="true"});let n=process.env.LOG_PRETTY;n!==void 0&&this.configure({prettyPrint:n.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,h as b,L as c,w as d,x as e};
@@ -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.15.13");process.exit(0)}
2
- import{b as S}from"./chunk-ZAKQLAHT.js";import{createHash as C}from"crypto";import*as a from"fs";import*as c from"os";import*as n from"path";function P(t){try{return a.realpathSync.native(t)}catch{return t}}function i(){let t="",r="";try{t=c.tmpdir()}catch{}try{r=c.homedir()}catch{}return{platform:process.platform,tmpdir:t,homedir:r,env:process.env,realpath:P}}function m(t){return t==="win32"?n.win32:n.posix}function l(t,r=i()){let e=m(r.platform),o=e.resolve(r.realpath(e.resolve(t))),s=e.parse(o).root.length;for(;o.length>s&&/[\\/]$/.test(o);)o=o.slice(0,-1);return r.platform==="win32"?o.toLowerCase():o}function w(t,r=i()){let e=m(r.platform),o=l(t,r);if(r.tmpdir&&o===l(r.tmpdir,r))return!0;if(r.platform==="win32")return o===e.parse(o).root.toLowerCase();let s=e.resolve(t);return y.some(p=>p===s||l(p,r)===o)}function b(t,r=i()){if(r.platform==="win32")return!1;try{return(a.statSync(t).mode&514)===514}catch{return!1}}function k(t,r=i()){return w(t,r)||b(t,r)}function A(t=i()){let r=m(t.platform),e;if(t.platform==="win32")e=t.env.LOCALAPPDATA||r.join(t.homedir,"AppData","Local");else if(t.platform==="darwin")e=r.join(t.homedir,"Library","Caches");else{let o=t.env.XDG_CACHE_HOME;e=o&&r.isAbsolute(o)?o:r.join(t.homedir,".cache")}return r.join(e,"agentic-qe","scratch")}function E(t,r=i()){let e=C("sha256").update(l(t,r)).digest("hex").slice(0,16);return m(r.platform).join(A(r),e)}function u(t){a.mkdirSync(t,{recursive:!0,mode:448}),process.platform!=="win32"&&a.chmodSync(t,448)}function R(t,r=i()){let e=E(t,r);try{return u(e),d(e,t),e}catch(o){let s=typeof process.getuid=="function"?String(process.getuid()):"user",p=n.join(r.tmpdir||c.tmpdir(),`agentic-qe-scratch-${s}`),f=n.join(p,n.basename(e));try{return u(p),u(f),d(f,t),f}catch(v){let g=h=>h instanceof Error?h.message:String(h);throw new Error(`Cannot create a private AQE scratch root for "${t}". User cache "${e}" failed: ${g(o)}. Temporary fallback "${f}" failed: ${g(v)}. Set AQE_PROJECT_ROOT to a project directory or make the user cache writable.`)}}}function d(t,r){let e=n.join(t,"SCRATCH_ROOT_FOR");try{a.existsSync(e)||a.writeFileSync(e,`${n.resolve(r)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.14");process.exit(0)}
2
+ import{b as S}from"./chunk-V6SE2ZU2.js";import{createHash as C}from"crypto";import*as a from"fs";import*as c from"os";import*as n from"path";function P(t){try{return a.realpathSync.native(t)}catch{return t}}function i(){let t="",r="";try{t=c.tmpdir()}catch{}try{r=c.homedir()}catch{}return{platform:process.platform,tmpdir:t,homedir:r,env:process.env,realpath:P}}function m(t){return t==="win32"?n.win32:n.posix}function l(t,r=i()){let e=m(r.platform),o=e.resolve(r.realpath(e.resolve(t))),s=e.parse(o).root.length;for(;o.length>s&&/[\\/]$/.test(o);)o=o.slice(0,-1);return r.platform==="win32"?o.toLowerCase():o}function w(t,r=i()){let e=m(r.platform),o=l(t,r);if(r.tmpdir&&o===l(r.tmpdir,r))return!0;if(r.platform==="win32")return o===e.parse(o).root.toLowerCase();let s=e.resolve(t);return y.some(p=>p===s||l(p,r)===o)}function b(t,r=i()){if(r.platform==="win32")return!1;try{return(a.statSync(t).mode&514)===514}catch{return!1}}function k(t,r=i()){return w(t,r)||b(t,r)}function A(t=i()){let r=m(t.platform),e;if(t.platform==="win32")e=t.env.LOCALAPPDATA||r.join(t.homedir,"AppData","Local");else if(t.platform==="darwin")e=r.join(t.homedir,"Library","Caches");else{let o=t.env.XDG_CACHE_HOME;e=o&&r.isAbsolute(o)?o:r.join(t.homedir,".cache")}return r.join(e,"agentic-qe","scratch")}function E(t,r=i()){let e=C("sha256").update(l(t,r)).digest("hex").slice(0,16);return m(r.platform).join(A(r),e)}function u(t){a.mkdirSync(t,{recursive:!0,mode:448}),process.platform!=="win32"&&a.chmodSync(t,448)}function R(t,r=i()){let e=E(t,r);try{return u(e),d(e,t),e}catch(o){let s=typeof process.getuid=="function"?String(process.getuid()):"user",p=n.join(r.tmpdir||c.tmpdir(),`agentic-qe-scratch-${s}`),f=n.join(p,n.basename(e));try{return u(p),u(f),d(f,t),f}catch(v){let g=h=>h instanceof Error?h.message:String(h);throw new Error(`Cannot create a private AQE scratch root for "${t}". User cache "${e}" failed: ${g(o)}. Temporary fallback "${f}" failed: ${g(v)}. Set AQE_PROJECT_ROOT to a project directory or make the user cache writable.`)}}}function d(t,r){let e=n.join(t,"SCRATCH_ROOT_FOR");try{a.existsSync(e)||a.writeFileSync(e,`${n.resolve(r)}
3
3
  `,{mode:384})}catch{}}var y,O=S(()=>{"use strict";y=["/","/tmp","/var/tmp","/usr/tmp","/dev/shm","/run/shm","/private","/private/tmp","/private/var","/private/var/tmp","/var","/usr","/etc","/opt","/srv","/mnt","/media","/run","/home","/Users","/Volumes"]});export{w as a,b,k as c,E as d,R as e,O as f};
@@ -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.15.13");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.15.14");process.exit(0)}
2
2
  var r="insufficient-evidence";function s(t,n){let e=n&&typeof n=="object"?n:null;return e&&(e.status===r||e.evidenceStatus===r)?!1:t==="coverage-analysis"?e?.measured===!0:!0}export{s as a};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.13");process.exit(0)}
2
- import{e as U,h as W,i as G}from"./chunk-TCBBNUBP.js";import{b as F}from"./chunk-YSZ5OE3Z.js";import{o as j,q as V}from"./chunk-SSU73QAX.js";import{b as D,c as $,d as Y}from"./chunk-KV4T4MXK.js";import{a as T,e as N}from"./chunk-3Y2ROSCL.js";N();Y();import*as C from"fs";import*as b from"path";import*as H from"yaml";var z=5,X=4,Z=3e4,ee=".claude/skills",te=5e3,se=500,K=100,re=1e3,q=500,ne=.8,ae=.2,ie=.1,w=.1,oe=.1,le=.1,ce=.1,ue=200,de=500,pe=300,me=1,ge=.9,Q={maxWorkers:z,batchSize:X,retryFailedTests:!0,timeout:Z,skillsDir:ee,progressIntervalMs:te},S=class{async execute(e,r,s){let t=$(K,se+K);return await new Promise(i=>setTimeout(i,t)),{output:this.generateMockResponse(e),tokensUsed:D(q,re+q),durationMs:t}}generateMockResponse(e){let r=[];return e.includes("alt")&&r.push("alt","1.1.1","perceivable"),e.includes("contrast")&&r.push("contrast","1.4.3","4.5:1"),e.includes("keyboard")&&r.push("keyboard","2.1.1","operable","button"),e.includes("label")&&r.push("label","3.3.2","understandable"),e.includes("ARIA")&&r.push("ARIA","4.1.2","robust"),e.includes("focus")&&r.push("focus","2.4.7","outline"),e.includes("lang")&&r.push("lang","3.1.1","language"),e.includes("caption")&&r.push("caption","1.2.2","track"),e.includes("accessible")&&r.push("accessible","compliant"),r.length===0&&r.push("accessibility","WCAG","finding"),`Analysis complete. Found issues related to: ${r.join(", ")}.
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.15.14");process.exit(0)}
2
+ import{e as U,h as W,i as G}from"./chunk-7MUO4DEH.js";import{b as F}from"./chunk-TOJF3ZG4.js";import{o as j,q as V}from"./chunk-4WLIOPHX.js";import{b as D,c as $,d as Y}from"./chunk-AJVLVF7V.js";import{a as T,e as N}from"./chunk-L5VSLPMW.js";N();Y();import*as C from"fs";import*as b from"path";import*as H from"yaml";var z=5,X=4,Z=3e4,ee=".claude/skills",te=5e3,se=500,K=100,re=1e3,q=500,ne=.8,ae=.2,ie=.1,w=.1,oe=.1,le=.1,ce=.1,ue=200,de=500,pe=300,me=1,ge=.9,Q={maxWorkers:z,batchSize:X,retryFailedTests:!0,timeout:Z,skillsDir:ee,progressIntervalMs:te},S=class{async execute(e,r,s){let t=$(K,se+K);return await new Promise(i=>setTimeout(i,t)),{output:this.generateMockResponse(e),tokensUsed:D(q,re+q),durationMs:t}}generateMockResponse(e){let r=[];return e.includes("alt")&&r.push("alt","1.1.1","perceivable"),e.includes("contrast")&&r.push("contrast","1.4.3","4.5:1"),e.includes("keyboard")&&r.push("keyboard","2.1.1","operable","button"),e.includes("label")&&r.push("label","3.3.2","understandable"),e.includes("ARIA")&&r.push("ARIA","4.1.2","robust"),e.includes("focus")&&r.push("focus","2.4.7","outline"),e.includes("lang")&&r.push("lang","3.1.1","language"),e.includes("caption")&&r.push("caption","1.2.2","track"),e.includes("accessible")&&r.push("accessible","compliant"),r.length===0&&r.push("accessibility","WCAG","finding"),`Analysis complete. Found issues related to: ${r.join(", ")}.
3
3
  Recommendations: Implement proper ${r[0]} attributes for better accessibility.
4
4
  Severity: ${e.includes("critical")?"critical":"serious"}`}},P=class{constructor(e,r,s){this.executor=r;this.config=s;this.id=e}executor;config;id;status="idle";tasksCompleted=0;tasksFailed=0;lastHeartbeat=Date.now();async executeBatch(e){this.status="running";let r=[];for(let s of e){this.lastHeartbeat=Date.now();try{let t=await this.executeTestCase(s);if(r.push(t),t.passed)this.tasksCompleted++;else if(this.tasksFailed++,this.config.retryFailedTests&&!t.passed){let a=await this.executeTestCase(s,!0);a.passed&&(r[r.length-1]=a,this.tasksCompleted++,this.tasksFailed--)}}catch(t){this.tasksFailed++,r.push({testId:s.testCaseId,passed:!1,expectedPatterns:s.testCase.expected_output.must_contain||[],actualPatterns:[],reasoningQuality:0,category:s.testCase.category,priority:s.testCase.priority,error:T(t)})}}return this.status="idle",r}async executeTestCase(e,r=!1){let s=Date.now(),t=this.buildPrompt(e),a=await this.executor.execute(t,e.model,{timeout:this.config.timeout}),i=this.validateResponse(a.output,e.testCase.expected_output,e.testCase.validation);return{testId:e.testCaseId,passed:i.passed,expectedPatterns:e.testCase.expected_output.must_contain||[],actualPatterns:i.foundPatterns,reasoningQuality:i.reasoningQuality,executionTimeMs:Date.now()-s,category:e.testCase.category,priority:e.testCase.priority,error:i.error}}buildPrompt(e){let{testCase:r}=e,s=r.input.context;return`Analyze the following ${s.language||"HTML"} code for accessibility issues.
5
5
  Context: ${s.description||r.description}
@@ -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.15.13");process.exit(0)}
2
- import{r as T,v as H}from"./chunk-3Y7TJFHU.js";import{a as C,b as M}from"./chunk-AQSVJNEH.js";import{i as b}from"./chunk-H4H2YSFH.js";H();M();import{createRequire as U}from"node:module";var O=U(import.meta.url),x=null;function w(){if(x)return x;let E=O("hnswlib-node");if(!E.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return x=E.HierarchicalNSW,x}function W(){return!0}var _=class{indexes;config;initialized;nextId;unifiedAdapters=null;useUnified;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.initialized=new Set,this.nextId=new Map,this.useUnified=W(),this.useUnified&&(this.unifiedAdapters=new Map)}initializeIndex(e){if(this.initialized.has(e))return;if(this.useUnified&&this.unifiedAdapters)try{let n=new C(`embedding-${e}`,{dimensions:this.config.dimension,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:this.config.metric==="dotproduct"?"cosine":this.config.metric});this.unifiedAdapters.set(e,n),this.initialized.add(e),this.nextId.set(e,0);return}catch(n){console.warn(`[HNSWEmbeddingIndex] Unified HNSW adapter unavailable for '${e}', using the legacy index (max 10000 entries): ${n instanceof Error?n.message:String(n)}`)}let t={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",s=w(),r=new s(t,this.config.dimension);r.initIndex({maxElements:1e4,m:this.config.M,efConstruction:this.config.efConstruction}),this.indexes.set(e,r),this.initialized.add(e),this.nextId.set(e,0)}addEmbedding(e,i){let t=e.namespace;this.initialized.has(t)||this.initializeIndex(t);let s=i??this.nextId.get(t);i===void 0&&this.nextId.set(t,s+1);let r=this.unifiedAdapters?.get(t);if(r){let o=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.add(s,o),s}let n=this.indexes.get(t),d=this.toFloatArray(e.vector);return n.addPoint(d,s),s}addEmbeddingsBatch(e){return e.map(i=>this.addEmbedding(i.embedding,i.id))}search(e,i={}){let t=i.namespace||e.namespace;if(!this.initialized.has(t))return[];let s=i.limit||10,r=this.unifiedAdapters?.get(t);if(r){let l=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.search(l,s).map(u=>({id:u.id,distance:1-u.score}))}let n=this.indexes.get(t),d=this.toFloatArray(e.vector),o=n.searchKnn(d,s);return o.neighbors.map((l,m)=>({id:l,distance:o.distances[m]}))}getIndexStats(e){if(!this.initialized.has(e))return null;let i=this.unifiedAdapters?.get(e);return i?{size:i.size(),maxElements:1e4,dimension:i.dimensions(),metric:this.config.metric}:{size:this.indexes.get(e).getCurrentCount(),maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}}async saveIndex(e,i){if(!this.initialized.has(e))throw new Error(`Namespace ${e} not initialized`);if(this.unifiedAdapters?.has(e)){console.warn(`[HNSWEmbeddingIndex] saveIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally.`);return}await this.indexes.get(e).writeIndex(i)}async loadIndex(e,i){if(this.useUnified){console.warn(`[HNSWEmbeddingIndex] loadIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally. Initialize via initializeIndex() instead.`);return}let s={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",r=w(),n=new r(s,this.config.dimension);await n.readIndex(i),this.indexes.set(e,n),this.initialized.add(e)}clearIndex(e){if(this.initialized.has(e)){let i=this.unifiedAdapters?.get(e);i&&(i.clear?.(),this.unifiedAdapters.delete(e)),this.indexes.delete(e),this.initialized.delete(e),this.nextId.delete(e)}}clearAll(){if(this.unifiedAdapters){for(let e of this.unifiedAdapters.values())e.clear?.();this.unifiedAdapters.clear()}this.indexes.clear(),this.initialized.clear(),this.nextId.clear()}resizeIndex(e,i){this.initialized.has(e)&&(this.clearIndex(e),this.initializeIndex(e))}setEfSearch(e){this.config.efSearch=e}toFloatArray(e){if(Array.isArray(e))return e;if(e instanceof Float32Array)return Array.from(e);if(e instanceof Int8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=e[t]/128;return i}if(e instanceof Uint8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=(e[t]-128)/128;return i}throw new Error(`Unsupported vector type: ${typeof e}`)}getConfig(){return{...this.config}}isInitialized(e){return this.initialized.has(e)}getInitializedNamespaces(){return Array.from(this.initialized)}getSize(e){if(!this.initialized.has(e))return 0;let i=this.unifiedAdapters?.get(e);return i?i.size():this.nextId.get(e)||0}};var q={mergeSimilarityThreshold:.85,maxMergesPerRun:50,softThreshold:400,hardThreshold:2e3,archiveMinAgeDays:30,archiveQualityThreshold:.15,mergeQualityBoost:.02,contradictionSimilarityThreshold:.85,contradictionQualityDelta:.4},R=class{config;db=null;initialized=!1;constructor(e={}){this.config={...q,...e}}async initialize(e){if(!this.initialized){if(e)this.db=e;else{let i=T();await i.initialize(),this.db=i.getDatabase()}this.initialized=!0}}async consolidateAll(e){this.ensureInitialized();let i={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[]},t=this.db.prepare("SELECT domain, COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL GROUP BY domain").all(),s=e?t.filter(n=>e.includes(n.domain)):t.filter(n=>n.cnt>this.config.softThreshold);for(let{domain:n,cnt:d}of s){let o=await this.consolidateDomain(n,d);i.merged+=o.merged,i.contradicted+=o.contradicted,i.qualityUpdated+=o.qualityUpdated,i.archived+=o.archived,i.hardDeleted+=o.hardDeleted,i.domainsProcessed.push(n)}let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL").get();return i.activeRemaining=r.cnt,(i.merged>0||i.archived>0||i.contradicted>0)&&console.log(`[ExperienceConsolidator] Consolidated: ${i.merged} merged, ${i.contradicted} contradicted, ${i.archived} archived, ${i.activeRemaining} active`),i}async consolidateDomain(e,i){this.ensureInitialized();let t={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]},s=await this.clusterAndMerge(e);t.merged=s.merged,t.contradicted=s.contradicted,t.qualityUpdated=this.reinforceQuality(e),t.archived=this.archiveValueless(e);let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE domain = ? AND consolidated_into IS NULL").get(e).cnt,n=0;return r>this.config.hardThreshold&&(n=this.hardDeleteExcess(e,r),t.archived+=n),t.activeRemaining=r-n,t}async bootstrapDomain(e){if(this.ensureInitialized(),this.db.prepare("SELECT value FROM kv_store WHERE key = ?").get(`consolidation_bootstrap_${e}`))return console.log(`[ExperienceConsolidator] Domain ${e} already bootstrapped`),{merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]};let t={...this.config};this.config.mergeSimilarityThreshold=.8,this.config.maxMergesPerRun=200;let s=await this.consolidateDomain(e);Object.assign(this.config,t);try{this.db.prepare("INSERT OR REPLACE INTO kv_store (key, value, namespace) VALUES (?, ?, 'system')").run(`consolidation_bootstrap_${e}`,new Date().toISOString())}catch{}return console.log(`[ExperienceConsolidator] Bootstrap ${e}: ${s.merged} merged, ${s.archived} archived`),s}async clusterAndMerge(e){let i=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.15.14");process.exit(0)}
2
+ import{r as T,v as H}from"./chunk-JK6PMLQQ.js";import{a as C,b as M}from"./chunk-57DRT6UA.js";import{i as b}from"./chunk-QP6GL3O5.js";H();M();import{createRequire as U}from"node:module";var O=U(import.meta.url),x=null;function w(){if(x)return x;let E=O("hnswlib-node");if(!E.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return x=E.HierarchicalNSW,x}function W(){return!0}var _=class{indexes;config;initialized;nextId;unifiedAdapters=null;useUnified;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.initialized=new Set,this.nextId=new Map,this.useUnified=W(),this.useUnified&&(this.unifiedAdapters=new Map)}initializeIndex(e){if(this.initialized.has(e))return;if(this.useUnified&&this.unifiedAdapters)try{let n=new C(`embedding-${e}`,{dimensions:this.config.dimension,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:this.config.metric==="dotproduct"?"cosine":this.config.metric});this.unifiedAdapters.set(e,n),this.initialized.add(e),this.nextId.set(e,0);return}catch(n){console.warn(`[HNSWEmbeddingIndex] Unified HNSW adapter unavailable for '${e}', using the legacy index (max 10000 entries): ${n instanceof Error?n.message:String(n)}`)}let t={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",s=w(),r=new s(t,this.config.dimension);r.initIndex({maxElements:1e4,m:this.config.M,efConstruction:this.config.efConstruction}),this.indexes.set(e,r),this.initialized.add(e),this.nextId.set(e,0)}addEmbedding(e,i){let t=e.namespace;this.initialized.has(t)||this.initializeIndex(t);let s=i??this.nextId.get(t);i===void 0&&this.nextId.set(t,s+1);let r=this.unifiedAdapters?.get(t);if(r){let o=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.add(s,o),s}let n=this.indexes.get(t),d=this.toFloatArray(e.vector);return n.addPoint(d,s),s}addEmbeddingsBatch(e){return e.map(i=>this.addEmbedding(i.embedding,i.id))}search(e,i={}){let t=i.namespace||e.namespace;if(!this.initialized.has(t))return[];let s=i.limit||10,r=this.unifiedAdapters?.get(t);if(r){let l=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.search(l,s).map(u=>({id:u.id,distance:1-u.score}))}let n=this.indexes.get(t),d=this.toFloatArray(e.vector),o=n.searchKnn(d,s);return o.neighbors.map((l,m)=>({id:l,distance:o.distances[m]}))}getIndexStats(e){if(!this.initialized.has(e))return null;let i=this.unifiedAdapters?.get(e);return i?{size:i.size(),maxElements:1e4,dimension:i.dimensions(),metric:this.config.metric}:{size:this.indexes.get(e).getCurrentCount(),maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}}async saveIndex(e,i){if(!this.initialized.has(e))throw new Error(`Namespace ${e} not initialized`);if(this.unifiedAdapters?.has(e)){console.warn(`[HNSWEmbeddingIndex] saveIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally.`);return}await this.indexes.get(e).writeIndex(i)}async loadIndex(e,i){if(this.useUnified){console.warn(`[HNSWEmbeddingIndex] loadIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally. Initialize via initializeIndex() instead.`);return}let s={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",r=w(),n=new r(s,this.config.dimension);await n.readIndex(i),this.indexes.set(e,n),this.initialized.add(e)}clearIndex(e){if(this.initialized.has(e)){let i=this.unifiedAdapters?.get(e);i&&(i.clear?.(),this.unifiedAdapters.delete(e)),this.indexes.delete(e),this.initialized.delete(e),this.nextId.delete(e)}}clearAll(){if(this.unifiedAdapters){for(let e of this.unifiedAdapters.values())e.clear?.();this.unifiedAdapters.clear()}this.indexes.clear(),this.initialized.clear(),this.nextId.clear()}resizeIndex(e,i){this.initialized.has(e)&&(this.clearIndex(e),this.initializeIndex(e))}setEfSearch(e){this.config.efSearch=e}toFloatArray(e){if(Array.isArray(e))return e;if(e instanceof Float32Array)return Array.from(e);if(e instanceof Int8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=e[t]/128;return i}if(e instanceof Uint8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=(e[t]-128)/128;return i}throw new Error(`Unsupported vector type: ${typeof e}`)}getConfig(){return{...this.config}}isInitialized(e){return this.initialized.has(e)}getInitializedNamespaces(){return Array.from(this.initialized)}getSize(e){if(!this.initialized.has(e))return 0;let i=this.unifiedAdapters?.get(e);return i?i.size():this.nextId.get(e)||0}};var q={mergeSimilarityThreshold:.85,maxMergesPerRun:50,softThreshold:400,hardThreshold:2e3,archiveMinAgeDays:30,archiveQualityThreshold:.15,mergeQualityBoost:.02,contradictionSimilarityThreshold:.85,contradictionQualityDelta:.4},R=class{config;db=null;initialized=!1;constructor(e={}){this.config={...q,...e}}async initialize(e){if(!this.initialized){if(e)this.db=e;else{let i=T();await i.initialize(),this.db=i.getDatabase()}this.initialized=!0}}async consolidateAll(e){this.ensureInitialized();let i={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[]},t=this.db.prepare("SELECT domain, COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL GROUP BY domain").all(),s=e?t.filter(n=>e.includes(n.domain)):t.filter(n=>n.cnt>this.config.softThreshold);for(let{domain:n,cnt:d}of s){let o=await this.consolidateDomain(n,d);i.merged+=o.merged,i.contradicted+=o.contradicted,i.qualityUpdated+=o.qualityUpdated,i.archived+=o.archived,i.hardDeleted+=o.hardDeleted,i.domainsProcessed.push(n)}let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL").get();return i.activeRemaining=r.cnt,(i.merged>0||i.archived>0||i.contradicted>0)&&console.log(`[ExperienceConsolidator] Consolidated: ${i.merged} merged, ${i.contradicted} contradicted, ${i.archived} archived, ${i.activeRemaining} active`),i}async consolidateDomain(e,i){this.ensureInitialized();let t={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]},s=await this.clusterAndMerge(e);t.merged=s.merged,t.contradicted=s.contradicted,t.qualityUpdated=this.reinforceQuality(e),t.archived=this.archiveValueless(e);let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE domain = ? AND consolidated_into IS NULL").get(e).cnt,n=0;return r>this.config.hardThreshold&&(n=this.hardDeleteExcess(e,r),t.archived+=n),t.activeRemaining=r-n,t}async bootstrapDomain(e){if(this.ensureInitialized(),this.db.prepare("SELECT value FROM kv_store WHERE key = ?").get(`consolidation_bootstrap_${e}`))return console.log(`[ExperienceConsolidator] Domain ${e} already bootstrapped`),{merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]};let t={...this.config};this.config.mergeSimilarityThreshold=.8,this.config.maxMergesPerRun=200;let s=await this.consolidateDomain(e);Object.assign(this.config,t);try{this.db.prepare("INSERT OR REPLACE INTO kv_store (key, value, namespace) VALUES (?, ?, 'system')").run(`consolidation_bootstrap_${e}`,new Date().toISOString())}catch{}return console.log(`[ExperienceConsolidator] Bootstrap ${e}: ${s.merged} merged, ${s.archived} archived`),s}async clusterAndMerge(e){let i=this.db.prepare(`
3
3
  SELECT id, task, domain, quality, success, application_count,
4
4
  consolidation_count, reuse_success_count, reuse_failure_count,
5
5
  embedding, embedding_dimension, started_at
@@ -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.15.13");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.15.14");process.exit(0)}
2
2
  var i=["qe-pentest-validator","qe-security-auditor","qe-security-scanner","qe-security-reviewer"],s="claude-sonnet-4-6",a=`anthropic/${s.replace("4-6","4.6")}`,u=s,p=new Set(["opus","fable"]),l=/claude-(opus|fable)-(\d+)(?:[-.](\d{1,2})(?!\d))?/,o={major:4,minor:7};function E(e){let r=e.trim().toLowerCase();if(p.has(r))return!0;let n=l.exec(r);if(!n)return!1;let t=Number(n[2]),c=n[3]===void 0?0:Number(n[3]);return t>o.major||t===o.major&&c>=o.minor}function _(e,r=process.env){return r.AQE_CYBER_VERIFIED==="true"?!1:i.includes(e)}function d(e,r,n,t=process.env){return!_(e,t)||!E(r)?r:n}function f(e){switch(e){case"openrouter":return a;case"bedrock":return"anthropic.claude-sonnet-4-6-v1:0";default:return u}}export{a,u as b,E as c,_ as d,d as e,f};
@@ -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.15.13");process.exit(0)}
2
- import{a as v,b as k}from"./chunk-CM4LSLKR.js";import{r as g,v as P}from"./chunk-3Y7TJFHU.js";import{a as d,b as y,e as R}from"./chunk-3Y2ROSCL.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,b};
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.15.14");process.exit(0)}
2
+ import{a as v,b as k}from"./chunk-BM3EJLMV.js";import{r as g,v as P}from"./chunk-JK6PMLQQ.js";import{a as d,b as y,e as R}from"./chunk-L5VSLPMW.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,b};
@@ -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.15.13");process.exit(0)}
2
- import{e as z}from"./chunk-SYV2V3PL.js";import{a as P}from"./chunk-E7CLYGS7.js";import{a as w,b as S}from"./chunk-H4GG2NLO.js";import{u as $,v as H}from"./chunk-3Y7TJFHU.js";import{a as T,e as I}from"./chunk-KDNJ4F3P.js";import{c as C,d as M}from"./chunk-J2ZIFFM6.js";import{a as k,e as F}from"./chunk-3Y2ROSCL.js";import{f as D}from"./chunk-ZAKQLAHT.js";M();import{createHash as L}from"crypto";import*as x from"path";function Q(){let o="3.15.13",e=(process.env.AQE_SESSION_CACHE_SALT??"").trim();return e?`${o}+${e}`:o}var U={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function N(o){let e=JSON.parse(JSON.stringify(o));function t(r){if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r))return"["+r.map(t).join(",")+"]";let i=r;return"{"+Object.keys(i).sort().map(n=>JSON.stringify(n)+":"+t(i[n])).join(",")+"}"}return t(e)}function j(o){let e=o?.projectRoot;if(!e)try{e=C()}catch{e=""}let t=o?.cwd;if(!t)try{t=process.cwd()}catch{t=""}return{projectRoot:e?x.resolve(e):"",cwd:t?x.resolve(t):"",inputs:o?.inputs??{}}}var v=class{cache=new Map;config;hits=0;misses=0;generation=0;constructor(e){this.config={...U,...e}}computeFingerprint(e,t,r,i){let n=N({action:t,build:Q(),domain:e,input:r,scope:j(i)});return L("sha256").update(n).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;!this.cache.has(e)&&this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=d();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
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.15.14");process.exit(0)}
2
+ import{e as z}from"./chunk-HHBF2BZC.js";import{a as P}from"./chunk-JJHLGGPP.js";import{a as w,b as S}from"./chunk-O32BFQV4.js";import{u as $,v as H}from"./chunk-JK6PMLQQ.js";import{a as T,e as I}from"./chunk-UDSB3XCG.js";import{c as C,d as M}from"./chunk-2UZBLC5H.js";import{a as k,e as F}from"./chunk-L5VSLPMW.js";import{f as D}from"./chunk-V6SE2ZU2.js";M();import{createHash as L}from"crypto";import*as x from"path";function Q(){let o="3.15.14",e=(process.env.AQE_SESSION_CACHE_SALT??"").trim();return e?`${o}+${e}`:o}var U={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function N(o){let e=JSON.parse(JSON.stringify(o));function t(r){if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r))return"["+r.map(t).join(",")+"]";let i=r;return"{"+Object.keys(i).sort().map(n=>JSON.stringify(n)+":"+t(i[n])).join(",")+"}"}return t(e)}function j(o){let e=o?.projectRoot;if(!e)try{e=C()}catch{e=""}let t=o?.cwd;if(!t)try{t=process.cwd()}catch{t=""}return{projectRoot:e?x.resolve(e):"",cwd:t?x.resolve(t):"",inputs:o?.inputs??{}}}var v=class{cache=new Map;config;hits=0;misses=0;generation=0;constructor(e){this.config={...U,...e}}computeFingerprint(e,t,r,i){let n=N({action:t,build:Q(),domain:e,input:r,scope:j(i)});return L("sha256").update(n).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;!this.cache.has(e)&&this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=d();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
3
3
  WHERE namespace = 'session_cache'
4
4
  AND created_at > ?
5
5
  ORDER BY created_at DESC LIMIT ?`).all(t,this.config.maxEntries);for(let i of r)try{let n=JSON.parse(i.value);Date.now()-n.cachedAt<=this.config.ttlMs&&this.cache.set(n.fingerprint,n)}catch{}}catch{}}getStats(){let e=this.hits+this.misses,t=0;for(let r of this.cache.values())t+=r.tokensSaved*r.hitCount;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,estimatedTokensSaved:t}}clear(){this.cache.clear(),this.hits=0,this.misses=0,this.generation++}getGeneration(){return this.generation}invalidateAll(){let e=this.cache.size;if(this.cache.clear(),this.generation++,this.config.persistToDb)try{d()?.prepare("DELETE FROM kv_store WHERE namespace = 'session_cache'").run()}catch{}return e}invalidateDomain(e){this.generation++;let t=0;for(let[r,i]of this.cache)i.domain===e&&(this.cache.delete(r),this.deletePersisted(i.fingerprint),t++);return t}evictOldest(){let e=null,t=1/0;for(let[r,i]of this.cache)i.cachedAt<t&&(t=i.cachedAt,e=r);e&&this.cache.delete(e)}persistEntry(e){try{let t=d();if(!t)return;t.prepare(`INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.13");process.exit(0)}
2
- import{b as L,d as B}from"./chunk-J2ZIFFM6.js";import*as a from"fs";import*as v from"path";import{createRequire as K}from"node:module";var Z=K(import.meta.url),b=Z("semver"),F="3.15.13",y=t=>typeof t=="string"&&b.valid(t)===t.split("+")[0],E=t=>b.validRange(t)!==null,x=(t,e)=>b.satisfies(t,e),C=(t,e)=>b.compare(t,e),N=(t,e)=>C(e,t)||t.localeCompare(e);B();var R=class{cacheDir;keepVersions;constructor(e={}){this.cacheDir=e.cacheDir??L("plugins"),this.keepVersions=e.keepVersions??2}has(e,n){let s=this.versionDir(e,n);return a.existsSync(s)&&a.existsSync(v.join(s,"qe-plugin.json"))}get(e,n){if(!this.has(e,n))return;let s=this.versionDir(e,n),i=a.readFileSync(v.join(s,"qe-plugin.json"),"utf-8"),r=JSON.parse(i),l=a.statSync(s);return{manifest:r,path:s,cachedAt:l.birthtime.toISOString()}}store(e,n){let s=this.versionDir(e.name,e.version);if(a.existsSync(s))return s;a.mkdirSync(s,{recursive:!0});try{this.copyDir(n,s),a.writeFileSync(v.join(s,"qe-plugin.json"),JSON.stringify(e,null,2))}catch(i){throw a.rmSync(s,{recursive:!0,force:!0}),i}return this.pruneOldVersions(e.name),s}remove(e,n){let s=this.versionDir(e,n);return a.existsSync(s)?(a.rmSync(s,{recursive:!0,force:!0}),!0):!1}listVersions(e){let n=v.join(this.cacheDir,e);if(!a.existsSync(n))return[];let s=[],i=a.readdirSync(n);for(let r of i){let l=v.join(n,r),d=v.join(l,"qe-plugin.json");if(a.existsSync(d))try{let p=a.readFileSync(d,"utf-8"),m=JSON.parse(p);if(!y(m.version)){console.warn(`[PluginCache] Skipping cached plugin ${e}@${r}: invalid version ${JSON.stringify(m.version)}`);continue}let c=a.statSync(l);s.push({manifest:m,path:l,cachedAt:c.birthtime.toISOString()})}catch{}}return s}listAll(){if(!a.existsSync(this.cacheDir))return[];let e=[],n=a.readdirSync(this.cacheDir);for(let s of n){let i=this.listVersions(s);i.length>0&&(i.sort((r,l)=>N(r.manifest.version,l.manifest.version)),e.push(i[0]))}return e}listCandidates(){return a.existsSync(this.cacheDir)?a.readdirSync(this.cacheDir).flatMap(e=>this.listVersions(e)):[]}versionDir(e,n){return v.join(this.cacheDir,e,n)}pruneOldVersions(e){let n=this.listVersions(e);if(n.length<=this.keepVersions)return;n.sort((i,r)=>i.cachedAt.localeCompare(r.cachedAt));let s=n.slice(0,n.length-this.keepVersions);for(let i of s)a.rmSync(i.path,{recursive:!0,force:!0})}copyDir(e,n){if(!a.existsSync(e))return;let s=a.readdirSync(e,{withFileTypes:!0});for(let i of s){let r=v.join(e,i.name),l=v.join(n,i.name);if(i.isDirectory()){if(i.name===".git"||i.name==="node_modules")continue;a.mkdirSync(l,{recursive:!0}),this.copyDir(r,l)}else a.copyFileSync(r,l)}}};var ee=/^[a-z][a-z0-9-]*$/,se=["aqe-core-","agentic-qe-core-"],G=64,T=500;function k(t){let e=[],n=[];if(!t||typeof t!="object")return{valid:!1,errors:["Manifest must be a non-null object"],warnings:[]};let s=t;if(!s.name||typeof s.name!="string"?e.push("name is required and must be a string"):ne(s.name,e,n),!s.version||typeof s.version!="string"?e.push("version is required and must be a string"):y(s.version)||e.push(`version "${s.version}" is not valid semver (expected: major.minor.patch)`),!s.description||typeof s.description!="string"?e.push("description is required and must be a string"):s.description.length>T&&n.push(`description exceeds ${T} characters`),(!s.author||typeof s.author!="string")&&e.push("author is required and must be a string"),!Array.isArray(s.domains)||s.domains.length===0)e.push("domains is required and must be a non-empty array");else for(let i of s.domains)if(typeof i!="string"){e.push("Each domain must be a string");break}if(!s.entryPoint||typeof s.entryPoint!="string"?e.push("entryPoint is required and must be a string"):te(s.entryPoint,e),s.dependencies!==void 0)if(typeof s.dependencies!="object"||s.dependencies===null||Array.isArray(s.dependencies))e.push("dependencies must be an object mapping plugin names to semver ranges");else for(let[i,r]of Object.entries(s.dependencies))typeof r!="string"?e.push(`Dependency "${i}" must have a string version range`):E(r)||e.push(`Dependency "${i}" has an invalid semver range`);if(s.hooks!==void 0)if(typeof s.hooks!="object"||s.hooks===null||Array.isArray(s.hooks))e.push("hooks must be an object mapping event names to handler paths");else for(let[,i]of Object.entries(s.hooks)){if(typeof i!="string"){e.push("Hook handler paths must be strings");break}i.includes("..")&&e.push(`Hook handler path "${i}" must not contain ".." (path traversal)`)}if(s.minAqeVersion!==void 0&&(typeof s.minAqeVersion!="string"||!y(s.minAqeVersion))&&e.push("minAqeVersion must be valid semver"),s.permissions!==void 0){if(!Array.isArray(s.permissions))e.push("permissions must be an array of strings");else for(let i of s.permissions)if(typeof i!="string"){e.push("Each permission must be a string");break}}return{valid:e.length===0,errors:e,warnings:n}}function U(t){let e=typeof t=="string"?JSON.parse(t):t,n=k(e);if(!n.valid)throw new Error(`Invalid plugin manifest:
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.15.14");process.exit(0)}
2
+ import{b as L,d as B}from"./chunk-2UZBLC5H.js";import*as a from"fs";import*as v from"path";import{createRequire as K}from"node:module";var Z=K(import.meta.url),b=Z("semver"),F="3.15.14",y=t=>typeof t=="string"&&b.valid(t)===t.split("+")[0],E=t=>b.validRange(t)!==null,x=(t,e)=>b.satisfies(t,e),C=(t,e)=>b.compare(t,e),N=(t,e)=>C(e,t)||t.localeCompare(e);B();var R=class{cacheDir;keepVersions;constructor(e={}){this.cacheDir=e.cacheDir??L("plugins"),this.keepVersions=e.keepVersions??2}has(e,n){let s=this.versionDir(e,n);return a.existsSync(s)&&a.existsSync(v.join(s,"qe-plugin.json"))}get(e,n){if(!this.has(e,n))return;let s=this.versionDir(e,n),i=a.readFileSync(v.join(s,"qe-plugin.json"),"utf-8"),r=JSON.parse(i),l=a.statSync(s);return{manifest:r,path:s,cachedAt:l.birthtime.toISOString()}}store(e,n){let s=this.versionDir(e.name,e.version);if(a.existsSync(s))return s;a.mkdirSync(s,{recursive:!0});try{this.copyDir(n,s),a.writeFileSync(v.join(s,"qe-plugin.json"),JSON.stringify(e,null,2))}catch(i){throw a.rmSync(s,{recursive:!0,force:!0}),i}return this.pruneOldVersions(e.name),s}remove(e,n){let s=this.versionDir(e,n);return a.existsSync(s)?(a.rmSync(s,{recursive:!0,force:!0}),!0):!1}listVersions(e){let n=v.join(this.cacheDir,e);if(!a.existsSync(n))return[];let s=[],i=a.readdirSync(n);for(let r of i){let l=v.join(n,r),d=v.join(l,"qe-plugin.json");if(a.existsSync(d))try{let p=a.readFileSync(d,"utf-8"),m=JSON.parse(p);if(!y(m.version)){console.warn(`[PluginCache] Skipping cached plugin ${e}@${r}: invalid version ${JSON.stringify(m.version)}`);continue}let c=a.statSync(l);s.push({manifest:m,path:l,cachedAt:c.birthtime.toISOString()})}catch{}}return s}listAll(){if(!a.existsSync(this.cacheDir))return[];let e=[],n=a.readdirSync(this.cacheDir);for(let s of n){let i=this.listVersions(s);i.length>0&&(i.sort((r,l)=>N(r.manifest.version,l.manifest.version)),e.push(i[0]))}return e}listCandidates(){return a.existsSync(this.cacheDir)?a.readdirSync(this.cacheDir).flatMap(e=>this.listVersions(e)):[]}versionDir(e,n){return v.join(this.cacheDir,e,n)}pruneOldVersions(e){let n=this.listVersions(e);if(n.length<=this.keepVersions)return;n.sort((i,r)=>i.cachedAt.localeCompare(r.cachedAt));let s=n.slice(0,n.length-this.keepVersions);for(let i of s)a.rmSync(i.path,{recursive:!0,force:!0})}copyDir(e,n){if(!a.existsSync(e))return;let s=a.readdirSync(e,{withFileTypes:!0});for(let i of s){let r=v.join(e,i.name),l=v.join(n,i.name);if(i.isDirectory()){if(i.name===".git"||i.name==="node_modules")continue;a.mkdirSync(l,{recursive:!0}),this.copyDir(r,l)}else a.copyFileSync(r,l)}}};var ee=/^[a-z][a-z0-9-]*$/,se=["aqe-core-","agentic-qe-core-"],G=64,T=500;function k(t){let e=[],n=[];if(!t||typeof t!="object")return{valid:!1,errors:["Manifest must be a non-null object"],warnings:[]};let s=t;if(!s.name||typeof s.name!="string"?e.push("name is required and must be a string"):ne(s.name,e,n),!s.version||typeof s.version!="string"?e.push("version is required and must be a string"):y(s.version)||e.push(`version "${s.version}" is not valid semver (expected: major.minor.patch)`),!s.description||typeof s.description!="string"?e.push("description is required and must be a string"):s.description.length>T&&n.push(`description exceeds ${T} characters`),(!s.author||typeof s.author!="string")&&e.push("author is required and must be a string"),!Array.isArray(s.domains)||s.domains.length===0)e.push("domains is required and must be a non-empty array");else for(let i of s.domains)if(typeof i!="string"){e.push("Each domain must be a string");break}if(!s.entryPoint||typeof s.entryPoint!="string"?e.push("entryPoint is required and must be a string"):te(s.entryPoint,e),s.dependencies!==void 0)if(typeof s.dependencies!="object"||s.dependencies===null||Array.isArray(s.dependencies))e.push("dependencies must be an object mapping plugin names to semver ranges");else for(let[i,r]of Object.entries(s.dependencies))typeof r!="string"?e.push(`Dependency "${i}" must have a string version range`):E(r)||e.push(`Dependency "${i}" has an invalid semver range`);if(s.hooks!==void 0)if(typeof s.hooks!="object"||s.hooks===null||Array.isArray(s.hooks))e.push("hooks must be an object mapping event names to handler paths");else for(let[,i]of Object.entries(s.hooks)){if(typeof i!="string"){e.push("Hook handler paths must be strings");break}i.includes("..")&&e.push(`Hook handler path "${i}" must not contain ".." (path traversal)`)}if(s.minAqeVersion!==void 0&&(typeof s.minAqeVersion!="string"||!y(s.minAqeVersion))&&e.push("minAqeVersion must be valid semver"),s.permissions!==void 0){if(!Array.isArray(s.permissions))e.push("permissions must be an array of strings");else for(let i of s.permissions)if(typeof i!="string"){e.push("Each permission must be a string");break}}return{valid:e.length===0,errors:e,warnings:n}}function U(t){let e=typeof t=="string"?JSON.parse(t):t,n=k(e);if(!n.valid)throw new Error(`Invalid plugin manifest:
3
3
  - ${n.errors.join(`
4
4
  - `)}`);return e}function ne(t,e,n){t.length>G&&e.push(`name must be ${G} characters or fewer`),ee.test(t)||e.push("name must be lowercase alphanumeric with hyphens, starting with a letter"),/[^\x00-\x7F]/.test(t)&&e.push("name must contain only ASCII characters");for(let s of se)t.startsWith(s)&&e.push(`name cannot start with reserved prefix "${s}"`);["plugin","test","tool"].includes(t)&&n.push(`name "${t}" is very generic \u2014 consider a more descriptive name`)}function te(t,e){t.includes("..")&&e.push('entryPoint must not contain ".." (path traversal)'),(t.startsWith("/")||t.startsWith("\\"))&&e.push("entryPoint must be a relative path"),!t.endsWith(".js")&&!t.endsWith(".ts")&&!t.endsWith(".mjs")&&e.push("entryPoint must end in .js, .ts, or .mjs")}var I=class{constructor(e=F){this.aqeVersion=e}aqeVersion;resolve(e,n){let s=new Map,i=new Map;for(let o of e){let u=s.get(o.name)??[];s.set(o.name,u);let f=this.validateVersions(o);f?i.set(o.name,[...i.get(o.name)??[],f]):u.push(o)}for(let o of s.values())o.sort((u,f)=>N(u.version,f.version));let r=new Map,l=[],d=o=>({ordered:o.map((u,f)=>({manifest:u,order:f})),missing:r,errors:l,selectedVersions:Object.fromEntries(o.map(u=>[u.name,u.version])),aqeVersion:this.aqeVersion}),p=[...n??s.keys()].sort(),m=new Set(p),c=new Map,_=0,h=!1,X=()=>{for(let o of c.values())for(let[u,f]of Object.entries(o.dependencies??{})){let g=c.get(u);if(!(g?[g]:s.get(u)??[]).some(M=>x(M.version,f)))return!1}return!0},A,z=()=>{let o=new Set,u=new Set,f=(g,P)=>{if(u.has(g))return[...P.slice(P.indexOf(g)),g];if(!o.has(g)){u.add(g);for(let M of Object.keys(c.get(g)?.dependencies??{})){let Q=f(M,[...P,g]);if(Q)return Q}u.delete(g),o.add(g)}};for(let g of c.keys()){let P=f(g,[]);if(P)return P}},j=()=>{let o=new Set(p);for(let f of c.values())for(let g of Object.keys(f.dependencies??{}))o.add(g);let u=[...o].sort().find(f=>!c.has(f));if(!u){let f=z();return f?(A=f,!1):!0}m.add(u);for(let f of s.get(u)??[]){if(++_>1e4)return h=!0,!1;if(c.set(u,f),X()&&j())return!0;if(c.delete(u),h)return!1}return!1};if(!j()){if(A&&!h)throw new Error(`Dependency cycle detected: ${A.join(" -> ")}`);for(let o of m)s.get(o)?.length||l.push(...i.get(o)??[]);for(let[o,u]of s){let f=[...new Set(u.flatMap(g=>Object.keys(g.dependencies??{})))].filter(g=>!s.has(g));f.length&&r.set(o,f)}return l.push({code:h?"RESOLUTION_LIMIT":r.size?"MISSING_DEPENDENCY":"UNSATISFIED_DEPENDENCY_RANGE",plugin:p.join(", "),message:h?"Plugin dependency search exceeded 10000 candidates":"No cached plugin selection satisfies all dependency ranges"}),d([])}let O=[],q=new Set,w=new Set,$=(o,u)=>{if(q.has(o))return;if(w.has(o))throw new Error(`Dependency cycle detected: ${[...u.slice(u.indexOf(o)),o].join(" -> ")}`);w.add(o);let f=c.get(o);for(let g of Object.keys(f.dependencies??{}))$(g,[...u,o]);w.delete(o),q.add(o),O.push(f)};for(let o of[...c.keys()].sort())$(o,[]);return d(O)}resolveAvailable(e){let n=[],s=this.resolve(e,[]),i=[],r=new Map;for(let l of[...new Set(e.map(d=>d.name))].sort())try{let d=this.resolve(e,[...n,l]);if(d.errors.length){i.push(...d.errors.map(p=>({...p,plugin:l})));for(let[p,m]of d.missing)r.set(p,m);continue}n.push(l),s=d}catch(d){i.push({code:"DEPENDENCY_CYCLE",plugin:l,message:d instanceof Error?d.message:String(d)})}return{...s,errors:i,missing:r}}canLoad(e,n){let s=Object.entries(e.dependencies??{}).filter(([i,r])=>{let l=n instanceof Set?void 0:n.get(i);return!l||!E(r)||!x(l,r)}).map(([i])=>i);return{canLoad:!this.validateVersions(e)&&s.length===0,missingDeps:s}}validateVersions(e){if(!y(e.version))return{code:"INVALID_PLUGIN_VERSION",plugin:e.name,message:"Invalid plugin version"};for(let n of Object.values(e.dependencies??{}))if(!E(n))return{code:"INVALID_DEPENDENCY_RANGE",plugin:e.name,message:"Invalid dependency range"};if(e.minAqeVersion&&(!y(e.minAqeVersion)||!y(this.aqeVersion)||C(this.aqeVersion,e.minAqeVersion)<0))return{code:"AQE_VERSION_INCOMPATIBLE",plugin:e.name,message:`Requires AQE ${e.minAqeVersion}; running ${this.aqeVersion}`}}};var ie=["aqe-core-","agentic-qe-core-","agentic-qe-internal-"],Y=new Set(["aqe","agentic-qe","ruflo","claude-flow"]),re=["..","~","/etc/","/proc/","/dev/","node_modules/"];function W(t){let e=[];return oe(t.name,e),ae(t.entryPoint,e),ce(t.hooks,e),ue(t.permissions,e),{safe:e.length===0,violations:e}}function oe(t,e){/[^\x20-\x7E]/.test(t)&&e.push(`Plugin name "${t}" contains non-ASCII characters`),Y.has(t.toLowerCase())&&e.push(`Plugin name "${t}" is a reserved name`);for(let s of ie)t.toLowerCase().startsWith(s)&&e.push(`Plugin name "${t}" uses reserved prefix "${s}"`);let n=t.toLowerCase().replace(/[0o]/g,"o").replace(/[1il]/g,"l").replace(/[-_]/g,"");Y.has(n)&&e.push(`Plugin name "${t}" is visually similar to a reserved name`)}function ae(t,e){H(t,"entryPoint",e),(t.startsWith("/")||t.startsWith("\\"))&&e.push("entryPoint must be a relative path, not absolute")}function ce(t,e){if(t)for(let[n,s]of Object.entries(t))H(s,`hook[${n}]`,e)}function H(t,e,n){for(let s of re)t.includes(s)&&n.push(`${e} contains dangerous path pattern "${s}"`);t.includes("\0")&&n.push(`${e} contains null byte (path injection attempt)`)}function ue(t,e){if(!t)return;let n=["fs:write-root","net:arbitrary","exec:shell"];for(let s of t)n.includes(s)&&e.push(`Plugin requests dangerous permission: ${s}`)}import*as S from"fs";import*as V from"path";var D=class{type="local";async resolve(e){let n=V.resolve(e),s=V.join(n,"qe-plugin.json");if(!S.existsSync(s))throw new Error(`No qe-plugin.json found at ${s}`);let i=S.readFileSync(s,"utf-8");return U(i)}async getPluginPath(e){let n=V.resolve(e);if(!S.existsSync(n))throw new Error(`Plugin directory does not exist: ${n}`);return n}};var J=class{cache;resolver;sources=new Map;constructor(e={}){this.cache=e.cache??new R,this.resolver=new I;let n=new D;if(this.sources.set("local",n),e.sources)for(let s of e.sources)this.sources.set(s.type,s)}async install(e,n="local"){if(process.env.AQE_PLUGINS_DISABLED==="true")return{success:!1,errors:["Plugin loading is disabled (AQE_PLUGINS_DISABLED=true)"],securityViolations:[]};let s=[],i=this.sources.get(n);if(!i)return{success:!1,errors:[`Unknown source type: ${n}. Available: ${[...this.sources.keys()].join(", ")}`],securityViolations:[]};let r;try{r=await i.resolve(e)}catch(c){return{success:!1,errors:[`Failed to resolve plugin: ${c instanceof Error?c.message:String(c)}`],securityViolations:[]}}let l=k(r);if(!l.valid)return{success:!1,manifest:r,errors:l.errors,securityViolations:[]};let d=W(r);if(!d.safe)return{success:!1,manifest:r,errors:["Plugin failed security checks"],securityViolations:d.violations};try{let c=this.cache.listCandidates().map(h=>h.manifest).filter(h=>h.name!==r.name),_=this.resolver.resolve([...c,r],[r.name]);if(_.errors.length)return{success:!1,manifest:r,errors:_.errors.map(h=>`${h.code}: ${h.message}`),securityViolations:[]}}catch(c){return{success:!1,manifest:r,errors:[c instanceof Error?c.message:String(c)],securityViolations:[]}}if(this.cache.has(r.name,r.version)){let c=this.cache.get(r.name,r.version);return{success:!0,manifest:r,cachePath:c.path,errors:[],securityViolations:[]}}let p;try{p=await i.getPluginPath(e)}catch(c){return{success:!1,manifest:r,errors:[`Failed to get plugin path: ${c instanceof Error?c.message:String(c)}`],securityViolations:[]}}let m=this.cache.store(r,p);return{success:!0,manifest:r,cachePath:m,errors:s,securityViolations:[]}}remove(e,n){if(n)return this.cache.remove(e,n);let s=this.cache.listVersions(e),i=!1;for(let r of s)this.cache.remove(e,r.manifest.version)&&(i=!0);return i}list(){return this.cache.listAll().map(n=>({name:n.manifest.name,version:n.manifest.version,description:n.manifest.description,domains:n.manifest.domains,source:"cached",cachePath:n.path}))}resolveLoadOrder(){let e=this.cache.listCandidates();return this.resolver.resolveAvailable(e.map(n=>n.manifest))}registerSource(e){this.sources.set(e.type,e)}};export{U as a,R as b,J as c};