agentic-qe 3.13.0 → 3.13.2

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 (386) hide show
  1. package/.agents/skills/aqe-plan-quality/SKILL.md +25 -0
  2. package/.agents/skills/aqe-plan-quality/agents/openai.yaml +4 -0
  3. package/.agents/skills/aqe-plan-quality/references/qe-routing.md +22 -0
  4. package/.agents/skills/aqe-review-quality/SKILL.md +24 -0
  5. package/.agents/skills/aqe-review-quality/agents/openai.yaml +4 -0
  6. package/.agents/skills/aqe-review-quality/references/quality-gates.md +20 -0
  7. package/.agents/skills/aqe-test-change/SKILL.md +26 -0
  8. package/.agents/skills/aqe-test-change/agents/openai.yaml +4 -0
  9. package/.agents/skills/aqe-test-change/references/test-specialties.md +23 -0
  10. package/.claude/helpers/ruflo-hook.cjs +5 -1
  11. package/.claude/skills/skills-manifest.json +1 -1
  12. package/.codex/hooks/aqe-codex-hook.cjs +69 -0
  13. package/.codex/hooks/ruflo-codex-hook.cjs +94 -0
  14. package/.codex/hooks.json +169 -0
  15. package/CHANGELOG.md +123 -0
  16. package/assets/skills/skills-manifest.json +1 -1
  17. package/dist/cli/bundle.js +5 -5
  18. package/dist/cli/chunks/adapter-I4SNWMCM.js +2 -0
  19. package/dist/cli/chunks/{agent-booster-wasm-ACX2DK7Y.js → agent-booster-wasm-PZYYTKSS.js} +2 -2
  20. package/dist/cli/chunks/{agent-handler-B45WP4ZJ.js → agent-handler-DNN7GXUN.js} +2 -2
  21. package/dist/cli/chunks/{agent-memory-branch-QQLZDE56.js → agent-memory-branch-LVCBBCQY.js} +2 -2
  22. package/dist/cli/chunks/aqe-learning-engine-WI47XKXI.js +2 -0
  23. package/dist/cli/chunks/{arena-SDB7723R.js → arena-422HSTPE.js} +2 -2
  24. package/dist/cli/chunks/{arena-G3IKZAG5.js → arena-OCEOLMCH.js} +4 -4
  25. package/dist/cli/chunks/{audit-GY46XUZA.js → audit-5O45K34M.js} +3 -3
  26. package/dist/cli/chunks/base-VJ6VDLD7.js +2 -0
  27. package/dist/cli/chunks/{hnswlib-node-RJPBJU2Q.js → better-sqlite3-Y36THYK2.js} +2 -2
  28. package/dist/cli/chunks/{brain-handler-347CYMPN.js → brain-handler-7VHXYN3P.js} +3 -3
  29. package/dist/cli/chunks/{branch-enumerator-Z3ULBFSM.js → branch-enumerator-PZKOD6S6.js} +2 -2
  30. package/dist/cli/chunks/{browser-OYEIHD7F.js → browser-M74UO4WJ.js} +2 -2
  31. package/dist/cli/chunks/browser-workflow-WRYHQQDU.js +2 -0
  32. package/dist/cli/chunks/{chunk-RVJPWRV6.js → chunk-24S5IUSI.js} +2 -2
  33. package/dist/cli/chunks/{chunk-3NOCK6ED.js → chunk-2DG44UZ5.js} +2 -2
  34. package/dist/cli/chunks/{chunk-34PEINFS.js → chunk-2QJPAQE5.js} +2 -2
  35. package/dist/cli/chunks/{chunk-SHCTEXNH.js → chunk-4DKL4H5L.js} +2 -2
  36. package/dist/cli/chunks/{chunk-A4QLGPYO.js → chunk-4FYTWD4Q.js} +2 -2
  37. package/dist/cli/chunks/{chunk-YFGAHNCG.js → chunk-4HFNY3Z2.js} +3 -3
  38. package/dist/cli/chunks/{chunk-RVRBTOWX.js → chunk-4PM5VORA.js} +2 -2
  39. package/dist/cli/chunks/{chunk-QWYISZTN.js → chunk-4SFOQSXU.js} +2 -2
  40. package/dist/cli/chunks/{chunk-RSFIOR2I.js → chunk-4STE6VLR.js} +87 -87
  41. package/dist/cli/chunks/{chunk-54MFKCLT.js → chunk-54BCLRRJ.js} +2 -2
  42. package/dist/cli/chunks/{chunk-IYDYJ33J.js → chunk-5AAG7JTB.js} +2 -2
  43. package/dist/cli/chunks/{chunk-TVMFH5N2.js → chunk-5EFNZEOB.js} +2 -2
  44. package/dist/cli/chunks/{chunk-GUEZQOHL.js → chunk-5GGGZYFA.js} +1 -1
  45. package/dist/cli/chunks/{chunk-5KAT6WBQ.js → chunk-5KMBZTDI.js} +2 -2
  46. package/dist/cli/chunks/{chunk-ANYYTWOQ.js → chunk-5XYVRTI6.js} +2 -2
  47. package/dist/cli/chunks/{chunk-ANIDFJCT.js → chunk-62D27BDO.js} +3 -3
  48. package/dist/cli/chunks/{chunk-SNTUKW4Q.js → chunk-6DMB6WK5.js} +2 -2
  49. package/dist/cli/chunks/{chunk-ZCFZ4USU.js → chunk-6R7TX5L4.js} +1 -1
  50. package/dist/cli/chunks/chunk-6UGYFYS4.js +2 -0
  51. package/dist/cli/chunks/chunk-6XHDH3IJ.js +3 -0
  52. package/dist/cli/chunks/{chunk-IHQTXJAQ.js → chunk-73HALJY5.js} +1 -1
  53. package/dist/cli/chunks/{chunk-7YXT6BXN.js → chunk-7TCVVVFA.js} +3 -3
  54. package/dist/cli/chunks/{chunk-RJZRWVL4.js → chunk-A2OD5Z4B.js} +1 -1
  55. package/dist/cli/chunks/{chunk-ES7WCYOU.js → chunk-AJ7A52GF.js} +1 -1
  56. package/dist/cli/chunks/{chunk-QCEW4ZDW.js → chunk-AP2BBV2D.js} +2 -2
  57. package/dist/cli/chunks/{chunk-FQLWQWRU.js → chunk-AS2HVJ42.js} +3 -3
  58. package/dist/cli/chunks/{chunk-7UNY32PU.js → chunk-ASIGTVFQ.js} +1 -1
  59. package/dist/cli/chunks/{chunk-EECM5XKY.js → chunk-B7KZMPF2.js} +1 -1
  60. package/dist/cli/chunks/{chunk-Z6QCOZ2H.js → chunk-BFKXHXWW.js} +2 -2
  61. package/dist/cli/chunks/{chunk-VC6EXDGY.js → chunk-BO2RBAPF.js} +2 -2
  62. package/dist/cli/chunks/{chunk-OXXMVQDF.js → chunk-BSQ32ZS5.js} +2 -2
  63. package/dist/cli/chunks/{chunk-WRYT4HTZ.js → chunk-CKTFKA7Q.js} +2 -2
  64. package/dist/cli/chunks/{chunk-QQB55ZJJ.js → chunk-CLBBFKXV.js} +2 -2
  65. package/dist/cli/chunks/{chunk-5FLTZ3KT.js → chunk-COOMXCCP.js} +2 -2
  66. package/dist/cli/chunks/{chunk-DYUC7WFA.js → chunk-DAHNHVND.js} +1 -1
  67. package/dist/cli/chunks/{chunk-6AOBLBR4.js → chunk-DCQQJLUY.js} +2 -2
  68. package/dist/cli/chunks/{chunk-LBE2P6UC.js → chunk-DIPOFCBX.js} +2 -2
  69. package/dist/cli/chunks/{chunk-EFRESRLB.js → chunk-DL2HDULJ.js} +5 -5
  70. package/dist/cli/chunks/{chunk-YRQLVGCI.js → chunk-DQXSDWRP.js} +2 -2
  71. package/dist/cli/chunks/{chunk-QI4CGJNK.js → chunk-E6JJ4ZRQ.js} +1 -1
  72. package/dist/cli/chunks/{chunk-KUA4HHU6.js → chunk-E6PYV3DB.js} +2 -2
  73. package/dist/cli/chunks/{chunk-ZJG6N2OK.js → chunk-EABGQVTV.js} +1 -1
  74. package/dist/cli/chunks/{chunk-U2SW6KK5.js → chunk-EFHMS7TJ.js} +2 -2
  75. package/dist/cli/chunks/{chunk-CWUBOLKY.js → chunk-ELVUERQW.js} +2 -2
  76. package/dist/cli/chunks/{chunk-A7GLWWSE.js → chunk-EU7NUUL6.js} +1 -1
  77. package/dist/cli/chunks/{chunk-3UHEZ5HZ.js → chunk-F6UMLI5Y.js} +2 -2
  78. package/dist/cli/chunks/{chunk-TZPKTRJB.js → chunk-FECBWGCA.js} +2 -2
  79. package/dist/cli/chunks/{chunk-OETDMOOE.js → chunk-FFMUTX26.js} +1 -1
  80. package/dist/cli/chunks/{chunk-VLNPJAVH.js → chunk-FJ2L6P7O.js} +1 -1
  81. package/dist/cli/chunks/{chunk-2DIT5AUU.js → chunk-FMYNKZ2S.js} +2 -2
  82. package/dist/cli/chunks/{chunk-L4LLA5U7.js → chunk-FXXXLDB3.js} +1 -1
  83. package/dist/cli/chunks/{chunk-D3MPV5G7.js → chunk-FZEWEG6Q.js} +2 -2
  84. package/dist/cli/chunks/{chunk-BGYLNCL6.js → chunk-G4LZ5SBC.js} +2 -2
  85. package/dist/cli/chunks/{chunk-J3L52EA4.js → chunk-GHJRLC3C.js} +5 -5
  86. package/dist/cli/chunks/{chunk-3JVUWKCO.js → chunk-GKKD22CC.js} +2 -2
  87. package/dist/cli/chunks/{chunk-32ZGV4Q4.js → chunk-GMKJWOXZ.js} +1 -1
  88. package/dist/cli/chunks/chunk-GMKQJEKX.js +2 -0
  89. package/dist/cli/chunks/{chunk-3GSYD5SL.js → chunk-GZ775E5O.js} +2 -2
  90. package/dist/cli/chunks/{chunk-GTUFX7AR.js → chunk-H6C2YTPX.js} +2 -2
  91. package/dist/cli/chunks/{chunk-UIPPJKON.js → chunk-HANBJ37Z.js} +2 -2
  92. package/dist/cli/chunks/{chunk-ZOXWASCC.js → chunk-HANJESCY.js} +2 -2
  93. package/dist/cli/chunks/{chunk-JPIBPKBP.js → chunk-HD6PZHLC.js} +3 -3
  94. package/dist/cli/chunks/{chunk-FQY3UTGA.js → chunk-HHUKHEW5.js} +2 -2
  95. package/dist/cli/chunks/{chunk-W5YEIHIO.js → chunk-HQCJYUKC.js} +2 -2
  96. package/dist/cli/chunks/{chunk-CYL2FV23.js → chunk-IIZ3HBPV.js} +2 -2
  97. package/dist/cli/chunks/{chunk-HTPM3URI.js → chunk-IV77BQ2R.js} +2 -2
  98. package/dist/cli/chunks/{chunk-THBTN7XB.js → chunk-J722Z7VO.js} +2 -2
  99. package/dist/cli/chunks/{chunk-5EIOQCGN.js → chunk-JDRYENTD.js} +2 -2
  100. package/dist/cli/chunks/{chunk-NQNKKVNO.js → chunk-JKVUSXT4.js} +3 -3
  101. package/dist/cli/chunks/{chunk-CQFT7H3F.js → chunk-JMRUHQEL.js} +2 -2
  102. package/dist/cli/chunks/{chunk-PERJO2DY.js → chunk-JPO4AC5Q.js} +1 -1
  103. package/dist/cli/chunks/{chunk-KSYLRM4Q.js → chunk-JPPHM3I6.js} +2 -2
  104. package/dist/cli/chunks/{chunk-56WZFXTQ.js → chunk-K3MNTU4O.js} +2 -2
  105. package/dist/cli/chunks/{chunk-CPH5JP4L.js → chunk-K47EWX3M.js} +1 -1
  106. package/dist/cli/chunks/{chunk-7DMXCCSD.js → chunk-KAHMXURL.js} +1 -1
  107. package/dist/cli/chunks/{chunk-UNIBND6A.js → chunk-KHVW6DQS.js} +1 -1
  108. package/dist/cli/chunks/{chunk-RLCWR7TS.js → chunk-KKPWS3XJ.js} +98 -88
  109. package/dist/cli/chunks/chunk-KRRGOJ6K.js +2 -0
  110. package/dist/cli/chunks/chunk-LEOSNZR2.js +2 -0
  111. package/dist/cli/chunks/{chunk-TNRIGQ6U.js → chunk-LG6UUM55.js} +2 -2
  112. package/dist/cli/chunks/{chunk-HOKON5EL.js → chunk-LJWIBYTR.js} +2 -2
  113. package/dist/cli/chunks/{chunk-N7VOOI3U.js → chunk-LQDQTLWV.js} +2 -2
  114. package/dist/cli/chunks/{chunk-2NRZYQSF.js → chunk-LXYVWAFN.js} +2 -2
  115. package/dist/cli/chunks/{chunk-YPTGE5NJ.js → chunk-LZNJ7HXB.js} +2 -2
  116. package/dist/cli/chunks/{chunk-6SXKCIN5.js → chunk-M4JZOCV3.js} +1 -1
  117. package/dist/cli/chunks/{chunk-UMG5URNV.js → chunk-MBTVAIFF.js} +1 -1
  118. package/dist/cli/chunks/{chunk-N5MMBA35.js → chunk-MNDPSIEI.js} +1 -1
  119. package/dist/cli/chunks/{chunk-L4S722JD.js → chunk-MUSLUG6Y.js} +1 -1
  120. package/dist/cli/chunks/{chunk-VLBV2VL3.js → chunk-MVJ5UQI3.js} +1 -1
  121. package/dist/cli/chunks/{chunk-XFCWYQHW.js → chunk-N2AGOQCL.js} +2 -2
  122. package/dist/cli/chunks/{chunk-KVL63BSU.js → chunk-N4O2RWSL.js} +1 -1
  123. package/dist/cli/chunks/{chunk-L2SFGFE6.js → chunk-NBRKZOPM.js} +1 -1
  124. package/dist/cli/chunks/{chunk-NETN3OUG.js → chunk-NIE3SGZM.js} +1 -1
  125. package/dist/cli/chunks/{chunk-LOXVVMS4.js → chunk-NNIKJZA4.js} +3 -3
  126. package/dist/cli/chunks/{chunk-5ICQL42E.js → chunk-NTKIDOIW.js} +2 -2
  127. package/dist/cli/chunks/{chunk-Q7PBGNUD.js → chunk-ODE7Z667.js} +1 -1
  128. package/dist/cli/chunks/{chunk-K5N6SLHO.js → chunk-OYWZYG6Q.js} +1 -1
  129. package/dist/cli/chunks/{chunk-CFVEDUTW.js → chunk-P33EORZZ.js} +2 -2
  130. package/dist/cli/chunks/{chunk-R3GEXYO4.js → chunk-PILZKQX7.js} +2 -2
  131. package/dist/cli/chunks/{chunk-ZJIX5FGQ.js → chunk-PJOH5Z5I.js} +2 -2
  132. package/dist/cli/chunks/{chunk-JGM6XCCP.js → chunk-PNQWEOE2.js} +1 -1
  133. package/dist/cli/chunks/{chunk-XKFE3FLI.js → chunk-PRQPUOSH.js} +2 -2
  134. package/dist/cli/chunks/{chunk-LWYLW7RX.js → chunk-PT6NTWGT.js} +2 -2
  135. package/dist/cli/chunks/{chunk-FBBZHATF.js → chunk-Q45FBGVV.js} +1 -1
  136. package/dist/cli/chunks/{chunk-SRQ3CPJE.js → chunk-Q625ISQI.js} +4 -4
  137. package/dist/cli/chunks/{chunk-BOVH6WSM.js → chunk-QS6TI7NR.js} +2 -2
  138. package/dist/cli/chunks/{chunk-4BDLD7V2.js → chunk-QVD3LU27.js} +1 -1
  139. package/dist/cli/chunks/{chunk-ZLXBNNNT.js → chunk-QZACODX6.js} +2 -2
  140. package/dist/cli/chunks/{chunk-NUQBJGGF.js → chunk-REBNPQI7.js} +2 -2
  141. package/dist/cli/chunks/{chunk-FAQLI3P5.js → chunk-RF2DMPX2.js} +2 -2
  142. package/dist/cli/chunks/{chunk-2VQVEQS4.js → chunk-RI2V2U2N.js} +2 -2
  143. package/dist/cli/chunks/{chunk-GJMZR7WU.js → chunk-RJYAUJDC.js} +3 -3
  144. package/dist/cli/chunks/{chunk-KZTBNDNE.js → chunk-RWHHOQIC.js} +1 -1
  145. package/dist/cli/chunks/{chunk-ZEIG5IQ4.js → chunk-RWUK5VMZ.js} +2 -2
  146. package/dist/cli/chunks/{chunk-E3B5XTXJ.js → chunk-SOOI2HJB.js} +1 -1
  147. package/dist/cli/chunks/{chunk-IPHLXAMX.js → chunk-T2XXTEZV.js} +2 -2
  148. package/dist/cli/chunks/{chunk-USMDIIHY.js → chunk-T55XIENI.js} +2 -2
  149. package/dist/cli/chunks/{chunk-VSNRPMAZ.js → chunk-T726SRYP.js} +2 -2
  150. package/dist/cli/chunks/{chunk-RDU4WTV2.js → chunk-TLG56A27.js} +2 -2
  151. package/dist/cli/chunks/{chunk-FUU32QY5.js → chunk-TTWWCWAR.js} +2 -2
  152. package/dist/cli/chunks/{chunk-LXPB7H2P.js → chunk-TVWX7NYD.js} +1 -1
  153. package/dist/cli/chunks/{chunk-G5DFYX3J.js → chunk-U2FCUBBW.js} +2 -2
  154. package/dist/cli/chunks/{chunk-DRIJYTSK.js → chunk-UIQVVS7K.js} +2 -2
  155. package/dist/cli/chunks/{chunk-6DTOGSDV.js → chunk-UPGJZA3D.js} +4 -4
  156. package/dist/cli/chunks/{chunk-3K4SF57Q.js → chunk-UVLWT6QM.js} +1 -1
  157. package/dist/cli/chunks/{chunk-FL3BM54K.js → chunk-VKU5BUUC.js} +1 -1
  158. package/dist/cli/chunks/{chunk-AO7AHX6K.js → chunk-VOYUCJLK.js} +2 -2
  159. package/dist/cli/chunks/{chunk-BCKTBGDM.js → chunk-WMK2ZNLM.js} +3 -3
  160. package/dist/cli/chunks/{chunk-4BESADKE.js → chunk-WTSVP6OK.js} +2 -2
  161. package/dist/cli/chunks/{chunk-MBCGI3M2.js → chunk-XS2S3ECA.js} +5 -5
  162. package/dist/cli/chunks/chunk-XXQLFPIK.js +2 -0
  163. package/dist/cli/chunks/{chunk-HL2QMM4M.js → chunk-XZOTFJHU.js} +2 -2
  164. package/dist/cli/chunks/{chunk-QTU3CVOB.js → chunk-YTHUTBBH.js} +2 -2
  165. package/dist/cli/chunks/{chunk-BUGWPTMF.js → chunk-YWJ2GPD4.js} +2 -2
  166. package/dist/cli/chunks/{chunk-GFBLWFRV.js → chunk-YXTDCP6H.js} +1 -1
  167. package/dist/cli/chunks/{chunk-TZ73SXQ5.js → chunk-YZUMCXH6.js} +1 -1
  168. package/dist/cli/chunks/{chunk-VHYMSZNF.js → chunk-ZIT5VF43.js} +2 -2
  169. package/dist/cli/chunks/{chunk-IZRLIWFN.js → chunk-ZY5FB3JV.js} +2 -2
  170. package/dist/cli/chunks/{ci-74ZUCO5V.js → ci-EOFZKCSH.js} +2 -2
  171. package/dist/cli/chunks/{ci-output-HD6IZNJA.js → ci-output-TAJFQWDP.js} +2 -2
  172. package/dist/cli/chunks/{circuit-breaker-USZVMA42.js → circuit-breaker-QA7YJ3IF.js} +2 -2
  173. package/dist/cli/chunks/{claude-flow-setup-S4XKNCD5.js → claude-flow-setup-4RNAIALK.js} +2 -2
  174. package/dist/cli/chunks/client-N2WAM5IK.js +2 -0
  175. package/dist/cli/chunks/{cline-installer-6EW4CHAR.js → cline-installer-K25NUUA4.js} +2 -2
  176. package/dist/cli/chunks/{code-TOLWD2XL.js → code-JM4D3I2W.js} +2 -2
  177. package/dist/cli/chunks/{code-index-extractor-UA4QQ7B3.js → code-index-extractor-6B6TJ2B5.js} +2 -2
  178. package/dist/cli/chunks/codex-installer-GRUENCIO.js +10 -0
  179. package/dist/cli/chunks/{completions-KVUMQQ4K.js → completions-LADTXGCC.js} +2 -2
  180. package/dist/cli/chunks/{complexity-analyzer-DFH6LMK2.js → complexity-analyzer-IQITOJH5.js} +2 -2
  181. package/dist/cli/chunks/{continuedev-installer-LYDQSAU7.js → continuedev-installer-H6NAXFZK.js} +2 -2
  182. package/dist/cli/chunks/{copilot-installer-7USXLZHZ.js → copilot-installer-W7HCQKOS.js} +2 -2
  183. package/dist/cli/chunks/core-handlers-VSX474R3.js +2 -0
  184. package/dist/cli/chunks/{cost-tracker-JBDIUMKZ.js → cost-tracker-MC7KEENQ.js} +2 -2
  185. package/dist/cli/chunks/{coverage-RGO3K357.js → coverage-NOOKPFYQ.js} +3 -3
  186. package/dist/cli/chunks/cross-domain-router-VNE7QKX4.js +2 -0
  187. package/dist/cli/chunks/{cursor-installer-YEZGD37F.js → cursor-installer-GOZ64GZJ.js} +2 -2
  188. package/dist/cli/chunks/{daemon-FVETQ3LL.js → daemon-G4ABQMFJ.js} +3 -3
  189. package/dist/cli/chunks/{daemon-LPEXHNYG.js → daemon-V23WTCJJ.js} +4 -4
  190. package/dist/cli/chunks/{dag-attention-scheduler-UKYE2FII.js → dag-attention-scheduler-YKOO6ZWL.js} +2 -2
  191. package/dist/cli/chunks/{detect-WBG5P7ER.js → detect-SNEMKQGJ.js} +2 -2
  192. package/dist/cli/chunks/{dist-node-YW6YRBCU.js → dist-node-VBNEM6K6.js} +2 -2
  193. package/dist/cli/chunks/{domain-handler-HH7J4A32.js → domain-handler-2G5XEERC.js} +2 -2
  194. package/dist/cli/chunks/{domain-transfer-V34GXD5I.js → domain-transfer-HSEUUM7E.js} +2 -2
  195. package/dist/cli/chunks/dream-A5LVJU7T.js +2 -0
  196. package/dist/cli/chunks/{embed-and-insert-pattern-WYLRS3CL.js → embed-and-insert-pattern-H6MU5HK4.js} +2 -2
  197. package/dist/cli/chunks/{eval-EIMVXY5J.js → eval-XYVDJXJF.js} +2 -2
  198. package/dist/cli/chunks/{experience-capture-middleware-QMZHRUKM.js → experience-capture-middleware-BZQJVXTE.js} +3 -3
  199. package/dist/cli/chunks/{fast-paths-NHLW6XS6.js → fast-paths-76WWBJ4H.js} +2 -2
  200. package/dist/cli/chunks/{feature-flags-NE3MBL3P.js → feature-flags-7E5YZ4P5.js} +2 -2
  201. package/dist/cli/chunks/{feature-flags-N3UHMSZ3.js → feature-flags-SCQ35J6M.js} +2 -2
  202. package/dist/cli/chunks/{file-discovery-SI44X4YS.js → file-discovery-LU5MAXWA.js} +2 -2
  203. package/dist/cli/chunks/{fleet-MMYUXRRM.js → fleet-M3TH65SV.js} +3 -3
  204. package/dist/cli/chunks/{gnn-wrapper-RLYXYU2Q.js → gnn-wrapper-OYUJEJD2.js} +2 -2
  205. package/dist/cli/chunks/{heartbeat-handler-6EDRUYLV.js → heartbeat-handler-II4NSOXK.js} +4 -4
  206. package/dist/cli/chunks/heartbeat-scheduler-CFZ6DNQY.js +2 -0
  207. package/dist/cli/chunks/hnsw-adapter-I4Y2T4HO.js +2 -0
  208. package/dist/cli/chunks/hnsw-index-SBR5VYGN.js +2 -0
  209. package/dist/cli/chunks/{hnsw-legacy-bridge-RVM7EAIH.js → hnsw-legacy-bridge-322R2UAB.js} +2 -2
  210. package/dist/cli/chunks/{better-sqlite3-DUZ6FFAH.js → hnswlib-node-OVLAHTPU.js} +2 -2
  211. package/dist/cli/chunks/{hooks-ZF4VKHEO.js → hooks-2A27XCUJ.js} +37 -37
  212. package/dist/cli/chunks/hybrid-router-E6YM74NQ.js +2 -0
  213. package/dist/cli/chunks/{hypergraph-engine-YWS66PGO.js → hypergraph-engine-ERA527UR.js} +2 -2
  214. package/dist/cli/chunks/{hypergraph-handler-OQHVRPWB.js → hypergraph-handler-7XL4OL6W.js} +3 -3
  215. package/dist/cli/chunks/impact-analyzer-GHYFSSMJ.js +2 -0
  216. package/dist/cli/chunks/{init-handler-YW74YF2V.js → init-handler-WN6KQ5WY.js} +6 -6
  217. package/dist/cli/chunks/init-wizard-KAN5KOGD.js +2 -0
  218. package/dist/cli/chunks/kernel-LET4HEEF.js +2 -0
  219. package/dist/cli/chunks/{kilocode-installer-APWB2GMA.js → kilocode-installer-5UCCFZ7V.js} +2 -2
  220. package/dist/cli/chunks/{kiro-installer-DICKFVNC.js → kiro-installer-77DPEP3K.js} +2 -2
  221. package/dist/cli/chunks/knowledge-graph-P3UJWNQS.js +2 -0
  222. package/dist/cli/chunks/{learning-MXHNYW5D.js → learning-A5GKUD73.js} +3 -3
  223. package/dist/cli/chunks/{llm-router-LTFIX7NY.js → llm-router-SINJNEGP.js} +4 -4
  224. package/dist/cli/chunks/llm-router-service-BOBENURJ.js +2 -0
  225. package/dist/cli/chunks/{load-JUMIQ4LZ.js → load-Q56GLXHJ.js} +2 -2
  226. package/dist/cli/chunks/load-test-4VDCVB7S.js +2 -0
  227. package/dist/cli/chunks/{mcp-WHIARJGO.js → mcp-VBDU2WLY.js} +2 -2
  228. package/dist/cli/chunks/{memory-KAHS6Z5A.js → memory-IGWBRDIT.js} +5 -5
  229. package/dist/cli/chunks/memory-backend-RRFAYQYS.js +2 -0
  230. package/dist/cli/chunks/{memory-handlers-DG3RRXB6.js → memory-handlers-IITHQ7KV.js} +2 -2
  231. package/dist/cli/chunks/{multi-model-executor-E3Y2RHMX.js → multi-model-executor-2QUEY4CC.js} +2 -2
  232. package/dist/cli/chunks/{opencode-installer-3RKGNGGE.js → opencode-installer-FZJ5N2B3.js} +2 -2
  233. package/dist/cli/chunks/{orchestrator-TXITUKWD.js → orchestrator-BGLDS47V.js} +5 -5
  234. package/dist/cli/chunks/pattern-null-store-V7DEZEF2.js +2 -0
  235. package/dist/cli/chunks/{pattern-usage-recorder-EE2BUFZT.js → pattern-usage-recorder-4MFN4WKV.js} +2 -2
  236. package/dist/cli/chunks/{pipeline-AXTT6KZB.js → pipeline-GZHAORGP.js} +2 -2
  237. package/dist/cli/chunks/{platform-TICPVKE2.js → platform-TZEX4YZQ.js} +2 -2
  238. package/dist/cli/chunks/{plugin-VQKNV3EM.js → plugin-VEYUFCNY.js} +2 -2
  239. package/dist/cli/chunks/{prime-radiant-advanced-wasm-6GY5YY7D.js → prime-radiant-advanced-wasm-OA5DLXJJ.js} +2 -2
  240. package/dist/cli/chunks/protocol-executor-I3C2ZETP.js +2 -0
  241. package/dist/cli/chunks/{protocol-handler-YFWDR7UZ.js → protocol-handler-MVJ5N4X5.js} +2 -2
  242. package/dist/cli/chunks/{prove-FUMRCXAA.js → prove-VKF7YCUA.js} +2 -2
  243. package/dist/cli/chunks/provider-manager-HB4YVQDI.js +2 -0
  244. package/dist/cli/chunks/qe-reasoning-bank-RDLBAXJY.js +2 -0
  245. package/dist/cli/chunks/{quality-2APISBW5.js → quality-NLB5LVGM.js} +2 -2
  246. package/dist/cli/chunks/{quality-gate-MCC3E5TM.js → quality-gate-OM6A7FQM.js} +3 -3
  247. package/dist/cli/chunks/queen-coordinator-QRWRNUDR.js +2 -0
  248. package/dist/cli/chunks/{real-embeddings-CC5TNOTI.js → real-embeddings-NONEKGAV.js} +2 -2
  249. package/dist/cli/chunks/{roocode-installer-YAHTEVPI.js → roocode-installer-ORXQQO3F.js} +2 -2
  250. package/dist/cli/chunks/router-WDF7KV4M.js +2 -0
  251. package/dist/cli/chunks/routing-feedback-DHYB4ZNL.js +2 -0
  252. package/dist/cli/chunks/{routing-handler-6NQBW4TQ.js → routing-handler-LGMIBVDS.js} +2 -2
  253. package/dist/cli/chunks/{ruvector-commands-ZHXLHUPG.js → ruvector-commands-4GZMU4BZ.js} +2 -2
  254. package/dist/cli/chunks/{rvf-dual-writer-5KF2DGCW.js → rvf-dual-writer-45HKI22F.js} +2 -2
  255. package/dist/cli/chunks/{rvf-migration-adapter-BBU57BGF.js → rvf-migration-adapter-RHYIXI3I.js} +2 -2
  256. package/dist/cli/chunks/{rvf-migration-coordinator-VN4VRZA4.js → rvf-migration-coordinator-ANTAYKNN.js} +2 -2
  257. package/dist/cli/chunks/rvf-native-adapter-7W53TYTH.js +2 -0
  258. package/dist/cli/chunks/{rvf-store-integrity-XCY2XQZA.js → rvf-store-integrity-CPQUTFST.js} +2 -2
  259. package/dist/cli/chunks/safe-db-4HBFO7OQ.js +2 -0
  260. package/dist/cli/chunks/schedule-M2OSBJZM.js +2 -0
  261. package/dist/cli/chunks/scheduler-JWV5MSGE.js +2 -0
  262. package/dist/cli/chunks/{security-PYP4H3KN.js → security-BM6LMCBI.js} +3 -3
  263. package/dist/cli/chunks/{shared-rvf-adapter-3CJHRNX6.js → shared-rvf-adapter-3HGARKJX.js} +2 -2
  264. package/dist/cli/chunks/{shared-rvf-dual-writer-MKSLKWDI.js → shared-rvf-dual-writer-UQ4O46ZI.js} +2 -2
  265. package/dist/cli/chunks/sqlite-persistence-QA4JRQZ2.js +2 -0
  266. package/dist/cli/chunks/{status-handler-VYIZ3VJF.js → status-handler-TGRAM5PC.js} +2 -2
  267. package/dist/cli/chunks/{structural-health-MVV4OWXP.js → structural-health-RXETMBB3.js} +2 -2
  268. package/dist/cli/chunks/{sync-VNX6L3TI.js → sync-B4KEYFCP.js} +2 -2
  269. package/dist/cli/chunks/{sync-G47OYIQ3.js → sync-JTBZIACA.js} +2 -2
  270. package/dist/cli/chunks/{task-handler-GOWF2GEH.js → task-handler-D7VXHWPG.js} +2 -2
  271. package/dist/cli/chunks/{task-handlers-J2WC6J37.js → task-handlers-XF6VVPTR.js} +3 -3
  272. package/dist/cli/chunks/{test-DMCJ3BXS.js → test-BKEIMBSX.js} +4 -4
  273. package/dist/cli/chunks/{test-scheduling-TRFHHKFM.js → test-scheduling-A4OHR7KW.js} +3 -3
  274. package/dist/cli/chunks/{token-bootstrap-KEQ7AHFF.js → token-bootstrap-LIDDAOAK.js} +2 -2
  275. package/dist/cli/chunks/{token-usage-B54FOFOF.js → token-usage-BJUFIU4V.js} +2 -2
  276. package/dist/cli/chunks/{transformers-IACZG7IV.js → transformers-YYUQCGMV.js} +2 -2
  277. package/dist/cli/chunks/{tree-sitter-wasm-parser-N7H4X37E.js → tree-sitter-wasm-parser-DFXYTJ23.js} +2 -2
  278. package/dist/cli/chunks/{types-B3SHT4OD.js → types-Z75HK5HH.js} +2 -2
  279. package/dist/cli/chunks/unified-memory-BEUZQTTC.js +2 -0
  280. package/dist/cli/chunks/unified-memory-hnsw-FHLSAEX4.js +2 -0
  281. package/dist/cli/chunks/unified-persistence-TVEQGCSB.js +2 -0
  282. package/dist/cli/chunks/{upgrade-A2PQ5EWK.js → upgrade-NETNZZH3.js} +2 -2
  283. package/dist/cli/chunks/{validate-UXV7UQUT.js → validate-U2WQ7P6T.js} +2 -2
  284. package/dist/cli/chunks/{validate-swarm-MMBU4FPP.js → validate-swarm-DKD7H2E3.js} +2 -2
  285. package/dist/cli/chunks/{vibium-R4GUVADA.js → vibium-FOQ73JBW.js} +2 -2
  286. package/dist/cli/chunks/visual-security-AYV46OUO.js +2 -0
  287. package/dist/cli/chunks/{web-tree-sitter-MP6E6CJB.js → web-tree-sitter-PQXWMQO6.js} +2 -2
  288. package/dist/cli/chunks/{windsurf-installer-Z6BWMUUO.js → windsurf-installer-CTFSFOBX.js} +2 -2
  289. package/dist/cli/chunks/{witness-chain-EFLTABBA.js → witness-chain-NCRHNFQM.js} +2 -2
  290. package/dist/cli/chunks/witness-chain-RU356H6R.js +2 -0
  291. package/dist/cli/chunks/{witness-key-manager-PN36TV43.js → witness-key-manager-WGCSSB23.js} +2 -2
  292. package/dist/cli/chunks/{workflow-A2AX3RJU.js → workflow-FE5QGP2U.js} +4 -4
  293. package/dist/cli/chunks/workflow-orchestrator-N2DQTC3X.js +2 -0
  294. package/dist/cli/chunks/{wrappers-NA6FHA63.js → wrappers-AHL5K2LO.js} +2 -2
  295. package/dist/cli/commands/hooks-handlers/hooks-shared.d.ts +9 -0
  296. package/dist/cli/commands/hooks-handlers/hooks-shared.js +38 -0
  297. package/dist/cli/commands/hooks.d.ts +2 -2
  298. package/dist/cli/commands/hooks.js +8 -2
  299. package/dist/cli/handlers/init-handler.js +1 -1
  300. package/dist/coordination/handlers/coverage-collection.d.ts +161 -0
  301. package/dist/coordination/handlers/coverage-collection.js +643 -0
  302. package/dist/coordination/handlers/coverage-handlers.js +199 -146
  303. package/dist/coordination/handlers/handler-types.d.ts +6 -1
  304. package/dist/coordination/handlers/handler-utils.js +10 -3
  305. package/dist/coordination/handlers/security-handlers.js +17 -2
  306. package/dist/coordination/handlers/test-execution-handlers.js +16 -1
  307. package/dist/coordination/queen-coordinator.js +4 -3
  308. package/dist/coordination/result-saver.js +119 -97
  309. package/dist/coordination/task-executor.d.ts +26 -1
  310. package/dist/coordination/task-executor.js +52 -4
  311. package/dist/domains/code-intelligence/services/knowledge-graph.js +8 -0
  312. package/dist/domains/coverage-analysis/services/coverage-analyzer.js +4 -0
  313. package/dist/domains/coverage-analysis/services/gap-detector.js +4 -0
  314. package/dist/domains/defect-intelligence/services/defect-predictor.js +4 -0
  315. package/dist/domains/defect-intelligence/services/root-cause-analyzer.js +4 -0
  316. package/dist/domains/quality-assessment/services/deployment-advisor.js +4 -0
  317. package/dist/domains/quality-assessment/services/quality-analyzer.js +4 -0
  318. package/dist/domains/security-compliance/services/scanners/sast-scanner.js +4 -0
  319. package/dist/domains/test-generation/index.js +17 -2
  320. package/dist/domains/test-generation/services/test-generator.js +31 -9
  321. package/dist/init/codex-installer.d.ts +13 -0
  322. package/dist/init/codex-installer.js +122 -1
  323. package/dist/init/phases/09-assets.js +4 -0
  324. package/dist/init/phases/phase-interface.d.ts +1 -1
  325. package/dist/integrations/ruvector/rvf-store-integrity.js +5 -1
  326. package/dist/integrations/ruvector/shared-rvf-adapter.js +5 -5
  327. package/dist/learning/real-embeddings.js +15 -1
  328. package/dist/mcp/bundle.js +429 -419
  329. package/dist/mcp/handlers/domain-handler-configs.js +79 -14
  330. package/dist/mcp/types.d.ts +42 -4
  331. package/dist/optimization/session-cache.d.ts +13 -1
  332. package/dist/optimization/session-cache.js +27 -2
  333. package/dist/shared/llm/llm-router-service.js +59 -4
  334. package/dist/shared/llm/router/agent-router-config.d.ts +46 -2
  335. package/dist/shared/llm/router/agent-router-config.js +124 -2
  336. package/dist/shared/llm/router/config-store.d.ts +17 -1
  337. package/dist/shared/llm/router/config-store.js +103 -0
  338. package/dist/shared/llm/router/index.d.ts +2 -2
  339. package/dist/shared/llm/router/index.js +2 -0
  340. package/dist/shared/llm/router/types.d.ts +44 -0
  341. package/dist/shared/llm/router/types.js +1 -0
  342. package/package.json +9 -6
  343. package/dist/cli/chunks/adapter-CWIMFWAI.js +0 -2
  344. package/dist/cli/chunks/aqe-learning-engine-OTXT2DLN.js +0 -2
  345. package/dist/cli/chunks/base-O3SPSWBA.js +0 -2
  346. package/dist/cli/chunks/browser-workflow-MXS3ZKY2.js +0 -2
  347. package/dist/cli/chunks/chunk-G4GTE3RJ.js +0 -2
  348. package/dist/cli/chunks/chunk-G7FMYFTN.js +0 -2
  349. package/dist/cli/chunks/chunk-HVB2L52I.js +0 -2
  350. package/dist/cli/chunks/chunk-MVI2QMRW.js +0 -2
  351. package/dist/cli/chunks/chunk-OZR25R7W.js +0 -2
  352. package/dist/cli/chunks/chunk-PP2RYSHT.js +0 -3
  353. package/dist/cli/chunks/client-33PGO5FA.js +0 -2
  354. package/dist/cli/chunks/codex-installer-C2CUP4FW.js +0 -8
  355. package/dist/cli/chunks/core-handlers-CSNZIM3A.js +0 -2
  356. package/dist/cli/chunks/cross-domain-router-DRIBR5L3.js +0 -2
  357. package/dist/cli/chunks/dream-WUNO723O.js +0 -2
  358. package/dist/cli/chunks/heartbeat-scheduler-VAFQDJLL.js +0 -2
  359. package/dist/cli/chunks/hnsw-adapter-TIRPA7XE.js +0 -2
  360. package/dist/cli/chunks/hnsw-index-SSQBRQCQ.js +0 -2
  361. package/dist/cli/chunks/hybrid-router-AKBWZOQ3.js +0 -2
  362. package/dist/cli/chunks/impact-analyzer-46FQIZ6Y.js +0 -2
  363. package/dist/cli/chunks/init-wizard-U3NHGYSS.js +0 -2
  364. package/dist/cli/chunks/kernel-ZDXHT6QF.js +0 -2
  365. package/dist/cli/chunks/knowledge-graph-6XTW6WO6.js +0 -2
  366. package/dist/cli/chunks/llm-router-service-3F4E64SY.js +0 -2
  367. package/dist/cli/chunks/load-test-SWZNGEIY.js +0 -2
  368. package/dist/cli/chunks/memory-backend-PR74ZPBA.js +0 -2
  369. package/dist/cli/chunks/pattern-null-store-EPE36BVT.js +0 -2
  370. package/dist/cli/chunks/protocol-executor-IELENNST.js +0 -2
  371. package/dist/cli/chunks/provider-manager-3R3KOBHG.js +0 -2
  372. package/dist/cli/chunks/qe-reasoning-bank-S2R2PCBS.js +0 -2
  373. package/dist/cli/chunks/queen-coordinator-2E23NEV4.js +0 -2
  374. package/dist/cli/chunks/router-3FVLWO6S.js +0 -2
  375. package/dist/cli/chunks/routing-feedback-ZQLRNNR7.js +0 -2
  376. package/dist/cli/chunks/rvf-native-adapter-YFGLQNEB.js +0 -2
  377. package/dist/cli/chunks/safe-db-4SBLBTW7.js +0 -2
  378. package/dist/cli/chunks/schedule-5Y3BGVAA.js +0 -2
  379. package/dist/cli/chunks/scheduler-DOID3QF3.js +0 -2
  380. package/dist/cli/chunks/sqlite-persistence-M4JEQO57.js +0 -2
  381. package/dist/cli/chunks/unified-memory-WNYWTGVX.js +0 -2
  382. package/dist/cli/chunks/unified-memory-hnsw-YPAV7U4E.js +0 -2
  383. package/dist/cli/chunks/unified-persistence-TJ252S7L.js +0 -2
  384. package/dist/cli/chunks/visual-security-VKYXEGJB.js +0 -2
  385. package/dist/cli/chunks/witness-chain-WVXRXKQP.js +0 -2
  386. package/dist/cli/chunks/workflow-orchestrator-GOWSPR3G.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.13.0");process.exit(0)}
2
- import{a as q}from"./chunk-FQY3UTGA.js";import{c as V,d as W}from"./chunk-GJMZR7WU.js";import{c as x}from"./chunk-CFVEDUTW.js";import{a as G}from"./chunk-HVB2L52I.js";import{c as R}from"./chunk-OXXMVQDF.js";import{b as E,d as $}from"./chunk-2DIT5AUU.js";import{a as C,c as H}from"./chunk-CYL2FV23.js";import{i as v}from"./chunk-E3B5XTXJ.js";import{a as M,b as U,d as ee}from"./chunk-RDU4WTV2.js";var P={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};$();H();var T=class p{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...P,...e}}async initialize(){if(!this.initialized)try{if(this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.prepareStatements(),this.initialized=!0,this.config.debug){let e=await this.getStats();console.log(`[ConceptGraph] Initialized: ${this.persistence.getDbPath()}`,e)}}catch(e){throw new Error(`Failed to initialize ConceptGraph: ${C(e)}`)}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertNode",this.db.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.2");process.exit(0)}
2
+ import{a as q}from"./chunk-HHUKHEW5.js";import{c as V,d as W}from"./chunk-RJYAUJDC.js";import{c as x}from"./chunk-P33EORZZ.js";import{a as G}from"./chunk-6UGYFYS4.js";import{c as R}from"./chunk-BSQ32ZS5.js";import{b as E,d as $}from"./chunk-FMYNKZ2S.js";import{a as C,c as H}from"./chunk-IIZ3HBPV.js";import{i as v}from"./chunk-SOOI2HJB.js";import{a as M,b as U,d as ee}from"./chunk-TLG56A27.js";var P={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};$();H();var T=class p{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...P,...e}}async initialize(){if(!this.initialized)try{if(this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.prepareStatements(),this.initialized=!0,this.config.debug){let e=await this.getStats();console.log(`[ConceptGraph] Initialized: ${this.persistence.getDbPath()}`,e)}}catch(e){throw new Error(`Failed to initialize ConceptGraph: ${C(e)}`)}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertNode",this.db.prepare(`
3
3
  INSERT INTO concept_nodes
4
4
  (id, concept_type, content, embedding, activation_level, last_activated, pattern_id, metadata)
5
5
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
@@ -63,7 +63,7 @@ import{a as q}from"./chunk-FQY3UTGA.js";import{c as V,d as W}from"./chunk-GJMZR7
63
63
  ORDER BY weight DESC
64
64
  LIMIT -1 OFFSET ?
65
65
  )
66
- `).run(s,e);r+=c.changes}return r})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,r=t.get().count,a={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)a[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:r,byType:a,avgEdgesPerNode:i>0?r/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?E(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function te(p){return new T(p)}ee();function ne(p,e){if(e<0||e>=p.length)return p[0]??0;let t=0,n=p.length-1;for(;t<n;){let i=t+n>>1;if(p[i]<p[t]){let s=p[t];p[t]=p[i],p[i]=s}if(p[n]<p[t]){let s=p[t];p[t]=p[n],p[n]=s}if(p[i]<p[n]){let s=p[i];p[i]=p[n],p[n]=s}let r=p[n],a=t;for(let s=t;s<n;s++)if(p[s]<=r){let c=p[a];p[a]=p[s],p[s]=c,a++}let o=p[a];if(p[a]=p[n],p[n]=o,a===e)return p[a];a<e?t=a+1:n=a-1}return p[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},w=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(d=>this.graph.getConcept(d)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let d of i)this.graph.setActivation(d,t),this.recordActivation(d,t);let r=0,a=t,o=0,s=0;for(;r<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),h=this.graph.getActiveNodes(this.config.threshold);for(let g of h)g.activationLevel>a&&(a=g.activationLevel);if(h.length===o&&d===0){if(s++,s>=3)break}else s=0;o=h.length,r++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,h)=>h.activation-d.activation),l=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:r,nodesActivated:c.length,peakActivation:a,activatedNodes:c,novelAssociations:l.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,r=0,a=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let d=U(0,o.length),h=o[d];if(h){let g=this.config.noiseLevel+M()*this.config.noiseLevel*2,m=h.activationLevel,y=Math.min(1,m+g+.3);this.graph.setActivation(h.id,y);let f=await this.spread([h.id],y,s);i+=f.iterations,f.peakActivation>r&&(r=f.peakActivation);for(let D of f.activatedNodes)a.add(D.nodeId);for(let D of f.novelAssociations)n.push(D)}if(Date.now()>=s)break;await this.sleep(50+M()*50)}let c=this.deduplicateAssociations(n),l=Array.from(a).map(d=>{let h=this.graph.getConcept(d);return{nodeId:d,activation:h?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,h)=>h.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:l.length,peakActivation:r,activatedNodes:l,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((a,o)=>o.activationLevel-a.activationLevel).slice(0,i));let r=[];for(let a=0;a<n.length;a++)for(let o=a+1;o<n.length;o++){let s=n[a],c=n[o],l=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),h=this.graph.getEdge(c.id,s.id),g=d!==void 0||h!==void 0,m=d?.weight??h?.weight??0,y=!g||m<.3;l>.3&&(r.push({source:s,target:c,coActivation:l,isNovel:y}),this.trackCoActivation(s.id,c.id))}return r.sort((a,o)=>a.isNovel!==o.isNovel?a.isNovel?-1:1:o.coActivation-a.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=B)return;let e=Math.floor(B*F),t=this.activationHistory.size-e,n=Array.from(this.activationHistory.keys()).slice(0,t);for(let i of n)this.activationHistory.delete(i)}trimCoActivationCounts(){if(this.coActivationCounts.size<=O)return;let e=Math.floor(O*F),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=ne(n,t-1),r=[];for(let[a,o]of this.coActivationCounts){if(r.length>=t)break;o<=i&&r.push(a)}for(let a of r)this.coActivationCounts.delete(a)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let r=this.graph.getEdges(i.id);for(let a of r){let o=this.graph.getConcept(a.target);if(!o)continue;let s=i.activationLevel*a.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,l=Math.min(1,c+s);n.push({nodeId:a.target,newActivation:l})}}}for(let i of n){let r=this.graph.getConcept(i.nodeId);r&&i.newActivation>r.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(M()-.5)*2*this.config.noiseLevel,i=Math.max(0,Math.min(1,t.activationLevel+n));this.graph.setActivation(t.id,i)}}recordActivation(e,t){let n=this.activationHistory.get(e)||[];n.push(t),n.length>50&&n.shift(),this.activationHistory.set(e,n)}trackCoActivation(e,t){let n=[e,t].sort().join(":"),i=this.coActivationCounts.get(n)||0;this.coActivationCounts.set(n,i+1)}deduplicateAssociations(e){let t=new Map;for(let n of e){let i=[n.source,n.target].sort().join(":"),r=t.get(i);(!r||n.strength>r.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ie}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},_=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let r=await this.detectPatternMerges(i);for(let c of r)c.cycleId=e,n.push(c);let a=await this.detectNovelAssociations(t.novelAssociations);for(let c of a)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,l)=>l.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let a=n[i],o=n[r],s=this.graph.getEdge(a.id,o.id),c=this.graph.getEdge(o.id,a.id),l=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(a.content,o.content),h=Math.sqrt(a.activationLevel*o.activationLevel),g=l*.4+d*.3+h*.3;if(g>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[a.id,o.id]}),y=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[a.id,o.id],edgeWeight:l,contentSimilarity:d,coActivation:h});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[a.id,o.id],description:this.generatePatternMergeDescription(a,o,g),noveltyScore:m,confidenceScore:y,actionable:y>=this.config.minConfidence,applied:!1,suggestedAction:y>=this.config.minConfidence?`Merge "${this.truncate(a.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),r=this.graph.getConcept(n.target);if(!i||!r)continue;let a=this.graph.getEdge(n.source,n.target);if(a&&a.weight>.5)continue;let o=i.conceptType!==r.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,r,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(r.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},r=i.successRate,a=i.executionCount,o=i.confidence,s=r!==void 0&&r<.7,c=a!==void 0&&a>10,l=o!==void 0&&o<.6;if(s||c&&l){let d=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),h=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,r,a),noveltyScore:d,confidenceScore:h,actionable:h>=this.config.minConfidence,applied:!1,suggestedAction:h>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let r=i.conceptType??"pattern";n[r]||(n[r]=[]),n[r].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(r=>r.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ie().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),r=new Set(n),a=new Set(i),o=n.filter(c=>a.has(c)),s=r.size+a.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let r=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${r}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};$();H();G();import{existsSync as re,unlinkSync as ae}from"fs";var A={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},b=class{constructor(e,t=A){this.db=e;this.thresholds=t}db;thresholds;activeBranches=new Map;listeners=[];rvfAdapter;useRvfFork=!1;_witnessChain=null;set witnessChain(e){this._witnessChain=e}setRvfAdapter(e,t=!0){this.rvfAdapter=e,this.useRvfFork=t,import("./feature-flags-N3UHMSZ3.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-r/n.patternCount;d>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(d*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let d=o/n.highConfidenceCount;d>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(d*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let d=this.rvfAdapter.dimension?.()??384,h=new Float32Array(d);for(let m=0;m<d;m++)h[m]=Math.sin(m*.1);let g=this.rvfAdapter.search?.(h,10)??[];g.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${g.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let l=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:l,patternCountDelta:r,avgConfidenceDelta:a,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&re(n)&&ae(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var S=R.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...A}},k=class{constructor(e){this.graph=e}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},N=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase();try{this.db.pragma("busy_timeout = 60000")}catch{}this.migrateSchema(),this.graph=new T,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new b(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${C(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),S.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),S.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){S.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:v(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new k(this.graph);await a.loadIntoMemory(30);let s=await new w(a,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await a.persistActivations();let l=await new _(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=l.length;for(let h of l)await this.saveInsight(h);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let h=this.branchManager.validateBranch(i);if(h.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,h);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,h);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:h.reason},"dream-engine")}catch{}S.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:h.reason})}i=null}let d={cycle:{...this.currentCycle},insights:l,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(r){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=C(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async loadFailuresAsConcepts(e){return this.ensureInitialized(),this.graph.loadFailuresAsErrors(e)}async loadSuccessesAsConcepts(e){return this.ensureInitialized(),this.graph.loadSuccessesAsOutcomes(e)}async ensureConceptsLoaded(){this.ensureInitialized();try{let n=this.db.prepare(`SELECT n.id as id, n.pattern_id as sourcePatternId, p.qe_domain as domain, n.failure_mode as failureMode
66
+ `).run(s,e);r+=c.changes}return r})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,r=t.get().count,a={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)a[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:r,byType:a,avgEdgesPerNode:i>0?r/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?E(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function te(p){return new T(p)}ee();function ne(p,e){if(e<0||e>=p.length)return p[0]??0;let t=0,n=p.length-1;for(;t<n;){let i=t+n>>1;if(p[i]<p[t]){let s=p[t];p[t]=p[i],p[i]=s}if(p[n]<p[t]){let s=p[t];p[t]=p[n],p[n]=s}if(p[i]<p[n]){let s=p[i];p[i]=p[n],p[n]=s}let r=p[n],a=t;for(let s=t;s<n;s++)if(p[s]<=r){let c=p[a];p[a]=p[s],p[s]=c,a++}let o=p[a];if(p[a]=p[n],p[n]=o,a===e)return p[a];a<e?t=a+1:n=a-1}return p[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},w=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(d=>this.graph.getConcept(d)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let d of i)this.graph.setActivation(d,t),this.recordActivation(d,t);let r=0,a=t,o=0,s=0;for(;r<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),h=this.graph.getActiveNodes(this.config.threshold);for(let g of h)g.activationLevel>a&&(a=g.activationLevel);if(h.length===o&&d===0){if(s++,s>=3)break}else s=0;o=h.length,r++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,h)=>h.activation-d.activation),l=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:r,nodesActivated:c.length,peakActivation:a,activatedNodes:c,novelAssociations:l.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,r=0,a=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let d=U(0,o.length),h=o[d];if(h){let g=this.config.noiseLevel+M()*this.config.noiseLevel*2,m=h.activationLevel,y=Math.min(1,m+g+.3);this.graph.setActivation(h.id,y);let f=await this.spread([h.id],y,s);i+=f.iterations,f.peakActivation>r&&(r=f.peakActivation);for(let D of f.activatedNodes)a.add(D.nodeId);for(let D of f.novelAssociations)n.push(D)}if(Date.now()>=s)break;await this.sleep(50+M()*50)}let c=this.deduplicateAssociations(n),l=Array.from(a).map(d=>{let h=this.graph.getConcept(d);return{nodeId:d,activation:h?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,h)=>h.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:l.length,peakActivation:r,activatedNodes:l,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((a,o)=>o.activationLevel-a.activationLevel).slice(0,i));let r=[];for(let a=0;a<n.length;a++)for(let o=a+1;o<n.length;o++){let s=n[a],c=n[o],l=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),h=this.graph.getEdge(c.id,s.id),g=d!==void 0||h!==void 0,m=d?.weight??h?.weight??0,y=!g||m<.3;l>.3&&(r.push({source:s,target:c,coActivation:l,isNovel:y}),this.trackCoActivation(s.id,c.id))}return r.sort((a,o)=>a.isNovel!==o.isNovel?a.isNovel?-1:1:o.coActivation-a.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=B)return;let e=Math.floor(B*F),t=this.activationHistory.size-e,n=Array.from(this.activationHistory.keys()).slice(0,t);for(let i of n)this.activationHistory.delete(i)}trimCoActivationCounts(){if(this.coActivationCounts.size<=O)return;let e=Math.floor(O*F),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=ne(n,t-1),r=[];for(let[a,o]of this.coActivationCounts){if(r.length>=t)break;o<=i&&r.push(a)}for(let a of r)this.coActivationCounts.delete(a)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let r=this.graph.getEdges(i.id);for(let a of r){let o=this.graph.getConcept(a.target);if(!o)continue;let s=i.activationLevel*a.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,l=Math.min(1,c+s);n.push({nodeId:a.target,newActivation:l})}}}for(let i of n){let r=this.graph.getConcept(i.nodeId);r&&i.newActivation>r.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(M()-.5)*2*this.config.noiseLevel,i=Math.max(0,Math.min(1,t.activationLevel+n));this.graph.setActivation(t.id,i)}}recordActivation(e,t){let n=this.activationHistory.get(e)||[];n.push(t),n.length>50&&n.shift(),this.activationHistory.set(e,n)}trackCoActivation(e,t){let n=[e,t].sort().join(":"),i=this.coActivationCounts.get(n)||0;this.coActivationCounts.set(n,i+1)}deduplicateAssociations(e){let t=new Map;for(let n of e){let i=[n.source,n.target].sort().join(":"),r=t.get(i);(!r||n.strength>r.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ie}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},_=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let r=await this.detectPatternMerges(i);for(let c of r)c.cycleId=e,n.push(c);let a=await this.detectNovelAssociations(t.novelAssociations);for(let c of a)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,l)=>l.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let a=n[i],o=n[r],s=this.graph.getEdge(a.id,o.id),c=this.graph.getEdge(o.id,a.id),l=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(a.content,o.content),h=Math.sqrt(a.activationLevel*o.activationLevel),g=l*.4+d*.3+h*.3;if(g>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[a.id,o.id]}),y=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[a.id,o.id],edgeWeight:l,contentSimilarity:d,coActivation:h});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[a.id,o.id],description:this.generatePatternMergeDescription(a,o,g),noveltyScore:m,confidenceScore:y,actionable:y>=this.config.minConfidence,applied:!1,suggestedAction:y>=this.config.minConfidence?`Merge "${this.truncate(a.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),r=this.graph.getConcept(n.target);if(!i||!r)continue;let a=this.graph.getEdge(n.source,n.target);if(a&&a.weight>.5)continue;let o=i.conceptType!==r.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,r,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(r.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},r=i.successRate,a=i.executionCount,o=i.confidence,s=r!==void 0&&r<.7,c=a!==void 0&&a>10,l=o!==void 0&&o<.6;if(s||c&&l){let d=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),h=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,r,a),noveltyScore:d,confidenceScore:h,actionable:h>=this.config.minConfidence,applied:!1,suggestedAction:h>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let r=i.conceptType??"pattern";n[r]||(n[r]=[]),n[r].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(r=>r.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ie().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),r=new Set(n),a=new Set(i),o=n.filter(c=>a.has(c)),s=r.size+a.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let r=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${r}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};$();H();G();import{existsSync as re,unlinkSync as ae}from"fs";var A={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},b=class{constructor(e,t=A){this.db=e;this.thresholds=t}db;thresholds;activeBranches=new Map;listeners=[];rvfAdapter;useRvfFork=!1;_witnessChain=null;set witnessChain(e){this._witnessChain=e}setRvfAdapter(e,t=!0){this.rvfAdapter=e,this.useRvfFork=t,import("./feature-flags-SCQ35J6M.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-r/n.patternCount;d>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(d*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let d=o/n.highConfidenceCount;d>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(d*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let d=this.rvfAdapter.dimension?.()??384,h=new Float32Array(d);for(let m=0;m<d;m++)h[m]=Math.sin(m*.1);let g=this.rvfAdapter.search?.(h,10)??[];g.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${g.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let l=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:l,patternCountDelta:r,avgConfidenceDelta:a,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&re(n)&&ae(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var S=R.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...A}},k=class{constructor(e){this.graph=e}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},N=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase();try{this.db.pragma("busy_timeout = 60000")}catch{}this.migrateSchema(),this.graph=new T,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new b(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${C(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),S.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),S.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){S.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:v(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new k(this.graph);await a.loadIntoMemory(30);let s=await new w(a,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await a.persistActivations();let l=await new _(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=l.length;for(let h of l)await this.saveInsight(h);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let h=this.branchManager.validateBranch(i);if(h.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,h);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,h);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:h.reason},"dream-engine")}catch{}S.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:h.reason})}i=null}let d={cycle:{...this.currentCycle},insights:l,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(r){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=C(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async loadFailuresAsConcepts(e){return this.ensureInitialized(),this.graph.loadFailuresAsErrors(e)}async loadSuccessesAsConcepts(e){return this.ensureInitialized(),this.graph.loadSuccessesAsOutcomes(e)}async ensureConceptsLoaded(){this.ensureInitialized();try{let n=this.db.prepare(`SELECT n.id as id, n.pattern_id as sourcePatternId, p.qe_domain as domain, n.failure_mode as failureMode
67
67
  FROM qe_pattern_nulls n
68
68
  JOIN qe_patterns p ON p.id = n.pattern_id
69
69
  ORDER BY n.updated_at DESC
@@ -89,7 +89,7 @@ import{a as q}from"./chunk-FQY3UTGA.js";import{c as V,d as W}from"./chunk-GJMZR7
89
89
  WHERE confidence >= 0.3 AND success_rate < 0.7
90
90
  ORDER BY usage_count DESC
91
91
  LIMIT 40
92
- )`).all();return t.length===0?0:this.graph.loadFromPatterns(t)}async applyInsight(e){this.ensureInitialized();try{let t=await this.getInsightRowById(e);if(!t)return{success:!1,error:`Insight not found: ${e}`};if(t.actionable!==1)return{success:!1,error:"Insight is not actionable"};if(t.applied===1)return{success:!0,patternId:t.pattern_id??void 0,error:"Insight already applied"};let{getSharedMemoryBackend:n}=await import("./base-O3SPSWBA.js"),{createQEReasoningBank:i}=await import("./qe-reasoning-bank-S2R2PCBS.js"),r=await n(),a=i(r);await a.initialize();try{let{getSharedRvfDualWriter:d}=await import("./shared-rvf-dual-writer-MKSLKWDI.js"),h=await d();h&&a.setRvfDualWriter(h)}catch(d){process.env.DEBUG&&S.debug("RVF wiring skipped",{error:C(d)})}let o=[];try{o=E(t.source_concepts)}catch{}let s=await a.storePattern({patternType:se(t.insight_type),name:`Dream Insight: ${t.insight_type}`,description:`${t.description} (confidence: ${t.confidence_score.toFixed(2)})`,template:{type:"workflow",content:t.suggested_action||t.description,variables:[]},context:{tags:["dream-generated",t.insight_type,...o.slice(0,3)],complexity:"medium"}});if(!s.success)return{success:!1,error:`Failed to create pattern: ${s.error?.message??"unknown error"}`};let c=s.value.id;return this.db.prepare(`
92
+ )`).all();return t.length===0?0:this.graph.loadFromPatterns(t)}async applyInsight(e){this.ensureInitialized();try{let t=await this.getInsightRowById(e);if(!t)return{success:!1,error:`Insight not found: ${e}`};if(t.actionable!==1)return{success:!1,error:"Insight is not actionable"};if(t.applied===1)return{success:!0,patternId:t.pattern_id??void 0,error:"Insight already applied"};let{getSharedMemoryBackend:n}=await import("./base-VJ6VDLD7.js"),{createQEReasoningBank:i}=await import("./qe-reasoning-bank-RDLBAXJY.js"),r=await n(),a=i(r);await a.initialize();try{let{getSharedRvfDualWriter:d}=await import("./shared-rvf-dual-writer-UQ4O46ZI.js"),h=await d();h&&a.setRvfDualWriter(h)}catch(d){process.env.DEBUG&&S.debug("RVF wiring skipped",{error:C(d)})}let o=[];try{o=E(t.source_concepts)}catch{}let s=await a.storePattern({patternType:se(t.insight_type),name:`Dream Insight: ${t.insight_type}`,description:`${t.description} (confidence: ${t.confidence_score.toFixed(2)})`,template:{type:"workflow",content:t.suggested_action||t.description,variables:[]},context:{tags:["dream-generated",t.insight_type,...o.slice(0,3)],complexity:"medium"}});if(!s.success)return{success:!1,error:`Failed to create pattern: ${s.error?.message??"unknown error"}`};let c=s.value.id;return this.db.prepare(`
93
93
  UPDATE dream_insights
94
94
  SET applied = 1, pattern_id = ?
95
95
  WHERE id = ?
@@ -117,4 +117,4 @@ import{a as q}from"./chunk-FQY3UTGA.js";import{c as V,d as W}from"./chunk-GJMZR7
117
117
  (id, cycle_id, insight_type, source_concepts, description, novelty_score,
118
118
  confidence_score, actionable, applied, suggested_action, pattern_id)
119
119
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
120
- `).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:E(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function se(p){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[p]||"test-template"}function oe(p){let e=new N(p);return import("./feature-flags-N3UHMSZ3.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-3CJHRNX6.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var ce=N;G();var Y="learning:loop-health";async function J(p,e,t){try{let n=new Date().toISOString(),i=await p.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await p.set(Y,i)}catch{}}var u=R.create("DreamScheduler"),Z={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},K="dream-scheduler:hook-state",L=class p{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Z,...t},this.metaLearningEngine=new W}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,u.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),u.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),u.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,u.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(u.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{u.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,u.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&u.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){u.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),u.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&u.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){u.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-3CJHRNX6.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&u.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){u.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-MKSLKWDI.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&u.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){u.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new q,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>p.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){u.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)u.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>p.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:v(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{u.debug("Failed to publish meta-learning insight event")}}}else u.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),u.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){u.info("Quality gate failed but cannot start dream yet");return}u.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){u.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){u.info("Milestone reached but cannot start dream yet");return}u.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:v(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){u.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(K),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(K,t)}catch(e){u.warn("Dream hook-state reconcile failed (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){u.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],u.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){u.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function de(p,e){return new L(p,e)}var pe=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],z=class{constructor(e,t){this.db=e;this.branchManager=new b(e,t??A)}db;branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,l)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(l.validation)>d?l:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,P as b,T as c,te as d,B as e,O as f,F as g,j as h,w as i,Q as j,_ as k,A as l,b as m,X as n,N as o,oe as p,ce as q,pe as r,z as s,Z as t,L as u,de as v};
120
+ `).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:E(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function se(p){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[p]||"test-template"}function oe(p){let e=new N(p);return import("./feature-flags-SCQ35J6M.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-3HGARKJX.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var ce=N;G();var Y="learning:loop-health";async function J(p,e,t){try{let n=new Date().toISOString(),i=await p.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await p.set(Y,i)}catch{}}var u=R.create("DreamScheduler"),Z={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},K="dream-scheduler:hook-state",L=class p{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Z,...t},this.metaLearningEngine=new W}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,u.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),u.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),u.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,u.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(u.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{u.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,u.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&u.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){u.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),u.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&u.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){u.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-3HGARKJX.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&u.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){u.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-UQ4O46ZI.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&u.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){u.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new q,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>p.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){u.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)u.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>p.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:v(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{u.debug("Failed to publish meta-learning insight event")}}}else u.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),u.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){u.info("Quality gate failed but cannot start dream yet");return}u.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){u.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){u.info("Milestone reached but cannot start dream yet");return}u.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:v(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){u.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(K),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(K,t)}catch(e){u.warn("Dream hook-state reconcile failed (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){u.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],u.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){u.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function de(p,e){return new L(p,e)}var pe=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],z=class{constructor(e,t){this.db=e;this.branchManager=new b(e,t??A)}db;branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,l)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(l.validation)>d?l:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,P as b,T as c,te as d,B as e,O as f,F as g,j as h,w as i,Q as j,_ as k,A as l,b as m,X as n,N as o,oe as p,ce as q,pe as r,z as s,Z as t,L as u,de as v};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
2
- import{b as y,d as p}from"./chunk-ZCFZ4USU.js";import{i as h}from"./chunk-E3B5XTXJ.js";var f={healthyThreshold:3,warningThreshold:2,checkIntervalMs:5e3,maxHistoryEntries:100,alertsEnabled:!0,alertCooldownMs:6e4,selfHealingEnabled:!1,maxHealingActionsPerMinute:5};var g=class{calculator;config;eventBus;persistence;graph;history=[];alerts=new Map;lastAlertTime=new Map;monitoringInterval=null;isMonitoring=!1;constructor(e,t={},r,i){this.graph=e,this.config={...f,...t},this.calculator=p(),this.eventBus=r,this.persistence=i}start(){this.isMonitoring||(this.isMonitoring=!0,this.monitoringInterval=setInterval(()=>this.checkHealth(),this.config.checkIntervalMs),this.checkHealth())}stop(){this.monitoringInterval&&(clearInterval(this.monitoringInterval),this.monitoringInterval=null),this.isMonitoring=!1}updateGraph(e){this.graph=e,this.isMonitoring&&this.checkHealth()}isEmptyTopology(){return this.graph.getVerticesByType("agent").length===0}checkHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph),r=this.isEmptyTopology()?"idle":this.determineStatus(e),i=this.calculateTrend();return this.recordHistory(e),this.isEmptyTopology()||this.checkAlertConditions(e,t,r),this.persistence&&t.length>0&&this.persistence.saveWeakVertices(t).catch(n=>console.warn("[MinCutHealthMonitor] Failed to persist weak vertices:",n)),this.emitEvent("mincut.updated",e,{status:r,weakVertexCount:t.length}),{status:r,minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:i,history:this.history.slice(-20),lastUpdated:new Date}}getHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph);return{status:this.isEmptyTopology()?"idle":this.determineStatus(e),minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:this.calculateTrend(),history:this.history.slice(-20),lastUpdated:new Date}}getMinCutValue(){return this.calculator.getMinCutValue(this.graph)}getWeakVertices(){return this.calculator.findWeakVertices(this.graph)}isCritical(){return this.calculator.getMinCutValue(this.graph)<this.config.warningThreshold}isHealthy(){return this.calculator.getMinCutValue(this.graph)>=this.config.healthyThreshold}getActiveAlerts(){return Array.from(this.alerts.values()).filter(e=>!e.acknowledged).sort((e,t)=>{let r={critical:0,high:1,medium:2,low:3,info:4};return r[e.severity]-r[t.severity]})}getAllAlerts(){return Array.from(this.alerts.values())}acknowledgeAlert(e){let t=this.alerts.get(e);return t?(t.acknowledged=!0,!0):!1}clearAcknowledgedAlerts(){let e=[];for(let[t,r]of this.alerts)r.acknowledged&&e.push(t);for(let t of e)this.alerts.delete(t);return e.length}getHistory(){return[...this.history]}getTrend(){return this.calculateTrend()}getStats(e=6e4){let t=Date.now()-e,r=this.history.filter(n=>n.timestamp.getTime()>t);if(r.length===0){let n=this.calculator.getMinCutValue(this.graph);return{min:n,max:n,average:n,count:0}}let i=r.map(n=>n.value);return{min:Math.min(...i),max:Math.max(...i),average:i.reduce((n,a)=>n+a,0)/i.length,count:r.length}}updateConfig(e){Object.assign(this.config,e),e.checkIntervalMs&&this.isMonitoring&&(this.stop(),this.start())}getConfig(){return{...this.config}}determineStatus(e){return e>=this.config.healthyThreshold?"healthy":e>=this.config.warningThreshold?"warning":"critical"}calculateTrend(){if(this.history.length<3)return"stable";let e=this.history.slice(-5),t=e[0].value,i=e[e.length-1].value-t,a=e.reduce((o,c)=>o+c.value,0)/e.length*.1;return i>a?"improving":i<-a?"degrading":"stable"}recordHistory(e){let t={timestamp:new Date,value:e,vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount};for(this.history.push(t);this.history.length>this.config.maxHistoryEntries;)this.history.shift()}checkAlertConditions(e,t,r){if(!this.config.alertsEnabled)return;let i=Date.now();r==="critical"?this.maybeGenerateAlert("critical-threshold","critical",`MinCut value (${e.toFixed(2)}) is below critical threshold (${this.config.warningThreshold})`,e,this.config.warningThreshold,t):r==="warning"&&this.maybeGenerateAlert("warning-threshold","high",`MinCut value (${e.toFixed(2)}) is below healthy threshold (${this.config.healthyThreshold})`,e,this.config.healthyThreshold,t);let n=t.filter(o=>o.weightedDegree===0);n.length>0&&this.maybeGenerateAlert("isolated-vertices","high",`${n.length} isolated vertex(es) detected`,e,0,n);let a=t.filter(o=>o.riskScore>.8);a.length>0&&this.maybeGenerateAlert("critical-vertices","medium",`${a.length} critical vertex(es) with high risk score`,e,0,a)}maybeGenerateAlert(e,t,r,i,n,a){let o=Date.now(),c=this.lastAlertTime.get(e)||0;if(o-c<this.config.alertCooldownMs)return;let s={id:h(),severity:t,message:r,minCutValue:i,threshold:n,affectedVertices:a.map(l=>l.vertexId),timestamp:new Date,acknowledged:!1,remediations:a.flatMap(l=>l.suggestions).slice(0,5)};this.alerts.set(s.id,s),this.persistence&&this.persistence.saveAlert(s).catch(l=>console.warn("[MinCutHealthMonitor] Failed to persist alert:",l)),this.lastAlertTime.set(e,o),this.emitEvent("mincut.alert.generated",i,{alert:s})}emitEvent(e,t,r){if(!this.eventBus)return;let i={id:h(),type:e,source:"coordination",timestamp:new Date,correlationId:h(),payload:{minCutValue:t,...r}};this.eventBus.publish(i).catch(n=>{console.error("Failed to publish MinCut event:",n)})}};function v(m,e,t,r){return new g(m,e,t,r)}var d=null,u=null;function C(){return d||(d=y()),d}function P(){return u||(u=v(C())),u}function B(){return d!==null}function F(){return u!==null}export{f as a,v as b,C as c,P as d,B as e,F as f};
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.13.2");process.exit(0)}
2
+ import{b as y,d as p}from"./chunk-6R7TX5L4.js";import{i as h}from"./chunk-SOOI2HJB.js";var f={healthyThreshold:3,warningThreshold:2,checkIntervalMs:5e3,maxHistoryEntries:100,alertsEnabled:!0,alertCooldownMs:6e4,selfHealingEnabled:!1,maxHealingActionsPerMinute:5};var g=class{calculator;config;eventBus;persistence;graph;history=[];alerts=new Map;lastAlertTime=new Map;monitoringInterval=null;isMonitoring=!1;constructor(e,t={},r,i){this.graph=e,this.config={...f,...t},this.calculator=p(),this.eventBus=r,this.persistence=i}start(){this.isMonitoring||(this.isMonitoring=!0,this.monitoringInterval=setInterval(()=>this.checkHealth(),this.config.checkIntervalMs),this.checkHealth())}stop(){this.monitoringInterval&&(clearInterval(this.monitoringInterval),this.monitoringInterval=null),this.isMonitoring=!1}updateGraph(e){this.graph=e,this.isMonitoring&&this.checkHealth()}isEmptyTopology(){return this.graph.getVerticesByType("agent").length===0}checkHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph),r=this.isEmptyTopology()?"idle":this.determineStatus(e),i=this.calculateTrend();return this.recordHistory(e),this.isEmptyTopology()||this.checkAlertConditions(e,t,r),this.persistence&&t.length>0&&this.persistence.saveWeakVertices(t).catch(n=>console.warn("[MinCutHealthMonitor] Failed to persist weak vertices:",n)),this.emitEvent("mincut.updated",e,{status:r,weakVertexCount:t.length}),{status:r,minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:i,history:this.history.slice(-20),lastUpdated:new Date}}getHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph);return{status:this.isEmptyTopology()?"idle":this.determineStatus(e),minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:this.calculateTrend(),history:this.history.slice(-20),lastUpdated:new Date}}getMinCutValue(){return this.calculator.getMinCutValue(this.graph)}getWeakVertices(){return this.calculator.findWeakVertices(this.graph)}isCritical(){return this.calculator.getMinCutValue(this.graph)<this.config.warningThreshold}isHealthy(){return this.calculator.getMinCutValue(this.graph)>=this.config.healthyThreshold}getActiveAlerts(){return Array.from(this.alerts.values()).filter(e=>!e.acknowledged).sort((e,t)=>{let r={critical:0,high:1,medium:2,low:3,info:4};return r[e.severity]-r[t.severity]})}getAllAlerts(){return Array.from(this.alerts.values())}acknowledgeAlert(e){let t=this.alerts.get(e);return t?(t.acknowledged=!0,!0):!1}clearAcknowledgedAlerts(){let e=[];for(let[t,r]of this.alerts)r.acknowledged&&e.push(t);for(let t of e)this.alerts.delete(t);return e.length}getHistory(){return[...this.history]}getTrend(){return this.calculateTrend()}getStats(e=6e4){let t=Date.now()-e,r=this.history.filter(n=>n.timestamp.getTime()>t);if(r.length===0){let n=this.calculator.getMinCutValue(this.graph);return{min:n,max:n,average:n,count:0}}let i=r.map(n=>n.value);return{min:Math.min(...i),max:Math.max(...i),average:i.reduce((n,a)=>n+a,0)/i.length,count:r.length}}updateConfig(e){Object.assign(this.config,e),e.checkIntervalMs&&this.isMonitoring&&(this.stop(),this.start())}getConfig(){return{...this.config}}determineStatus(e){return e>=this.config.healthyThreshold?"healthy":e>=this.config.warningThreshold?"warning":"critical"}calculateTrend(){if(this.history.length<3)return"stable";let e=this.history.slice(-5),t=e[0].value,i=e[e.length-1].value-t,a=e.reduce((o,c)=>o+c.value,0)/e.length*.1;return i>a?"improving":i<-a?"degrading":"stable"}recordHistory(e){let t={timestamp:new Date,value:e,vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount};for(this.history.push(t);this.history.length>this.config.maxHistoryEntries;)this.history.shift()}checkAlertConditions(e,t,r){if(!this.config.alertsEnabled)return;let i=Date.now();r==="critical"?this.maybeGenerateAlert("critical-threshold","critical",`MinCut value (${e.toFixed(2)}) is below critical threshold (${this.config.warningThreshold})`,e,this.config.warningThreshold,t):r==="warning"&&this.maybeGenerateAlert("warning-threshold","high",`MinCut value (${e.toFixed(2)}) is below healthy threshold (${this.config.healthyThreshold})`,e,this.config.healthyThreshold,t);let n=t.filter(o=>o.weightedDegree===0);n.length>0&&this.maybeGenerateAlert("isolated-vertices","high",`${n.length} isolated vertex(es) detected`,e,0,n);let a=t.filter(o=>o.riskScore>.8);a.length>0&&this.maybeGenerateAlert("critical-vertices","medium",`${a.length} critical vertex(es) with high risk score`,e,0,a)}maybeGenerateAlert(e,t,r,i,n,a){let o=Date.now(),c=this.lastAlertTime.get(e)||0;if(o-c<this.config.alertCooldownMs)return;let s={id:h(),severity:t,message:r,minCutValue:i,threshold:n,affectedVertices:a.map(l=>l.vertexId),timestamp:new Date,acknowledged:!1,remediations:a.flatMap(l=>l.suggestions).slice(0,5)};this.alerts.set(s.id,s),this.persistence&&this.persistence.saveAlert(s).catch(l=>console.warn("[MinCutHealthMonitor] Failed to persist alert:",l)),this.lastAlertTime.set(e,o),this.emitEvent("mincut.alert.generated",i,{alert:s})}emitEvent(e,t,r){if(!this.eventBus)return;let i={id:h(),type:e,source:"coordination",timestamp:new Date,correlationId:h(),payload:{minCutValue:t,...r}};this.eventBus.publish(i).catch(n=>{console.error("Failed to publish MinCut event:",n)})}};function v(m,e,t,r){return new g(m,e,t,r)}var d=null,u=null;function C(){return d||(d=y()),d}function P(){return u||(u=v(C())),u}function B(){return d!==null}function F(){return u!==null}export{f as a,v as b,C as c,P as d,B as e,F 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.13.0");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.13.2");process.exit(0)}
2
2
  var s=["qe-pentest-validator","qe-security-auditor","qe-security-scanner","qe-security-reviewer"],c="anthropic/claude-sonnet-4.6",u="claude-sonnet-4-6";function o(n){return n.includes("claude-opus-4-7")||n.includes("claude-opus-4.7")}function i(n,e=process.env){return e.AQE_CYBER_VERIFIED==="true"?!1:s.includes(n)}function a(n,e,r,t=process.env){return!i(n,t)||!o(e)?e:r}export{c as a,u as b,o as c,i as d,a as e};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.2");process.exit(0)}
2
+ import{a as y,c as v,d as R}from"./chunk-6XHDH3IJ.js";import{d as u}from"./chunk-HD6PZHLC.js";import{a as p,b as g,c as P,d as s}from"./chunk-KRRGOJ6K.js";import{d as f,e as C}from"./chunk-BSQ32ZS5.js";C();var E=f("llm/router-service");function m(e){let r={};for(let[i,t]of Object.entries(e.providers??{}))t?.defaultModel&&(r[i]=t.defaultModel);p(e.agentOverrides,r);let o=g();if(o.length===0)return e;let n=e.rules.length>0?e.rules:P;return{...e,rules:[...o,...n]}}var T=["ollama","onnx","gemini","openrouter","openai","claude","azure-openai","bedrock"];async function F(e={}){if(e.providerManager){let a=m(v({projectRoot:e.projectRoot,override:e.override,env:e.env})),d=new s(e.providerManager,a);return await d.initialize(),{router:d,resolvedConfig:a,enabledProviders:x(a)}}if(!R({projectRoot:e.projectRoot,env:e.env}))return null;let r=m(v({projectRoot:e.projectRoot,override:e.override,env:e.env})),o=M(r,e.env??process.env);if(o.length===0)return null;let n=new Set(o);for(let[a,d]of Object.entries(r.agentOverrides??{}))d.provider&&!n.has(d.provider)&&E.warn(`[llm-config] agentOverrides["${a}"] routes to provider "${d.provider}", which is not enabled (no API key detected and not enabled in .agentic-qe/llm-config.json). This override will not take effect until that provider is available.`);let{primary:i,fallbacks:t}=L(r,o),l={primary:i,fallbacks:t,providers:k(r,o),loadBalancing:"round-robin",global:{enableCostTracking:!0,enableMetrics:!0}},b=new u(l),c=new s(b,r);return await c.initialize(),{router:c,resolvedConfig:r,enabledProviders:o}}function M(e,r=process.env){let o=y(r),n=[],i=t=>{n.includes(t)||!e.providers?.[t]?.enabled||o.has(t)&&n.push(t)};i(e.defaultProvider);for(let t of e.fallbackChain?.entries??[])i(t.provider);for(let t of T)i(t);return n}function x(e){let r=new Set([e.defaultProvider]);for(let o of e.fallbackChain?.entries??[])r.add(o.provider);return Array.from(r)}function L(e,r){if(r.length===0)throw new Error("pickPrimaryAndFallbacks: no enabled providers");let o=r.includes(e.defaultProvider)?e.defaultProvider:r[0],n=r.filter(i=>i!==o);return{primary:o,fallbacks:n}}function k(e,r){let o={};for(let n of r){let i=e.providers?.[n];i&&(o[n]=i)}return o}export{F as a,M as b,L as c};
@@ -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.13.0");process.exit(0)}
2
- import{c as s,e as t}from"./chunk-ES7WCYOU.js";var K={};t(K,{DEFAULT_FEATURE_FLAGS:()=>r,getRuVectorFeatureFlags:()=>u,getRvfMigrationStage:()=>H,initFeatureFlagsFromEnv:()=>z,isAgentMemoryBranchingEnabled:()=>I,isCNNVisualRegressionEnabled:()=>b,isCognitiveRoutingEnabled:()=>Y,isCoherenceActionGateEnabled:()=>A,isCoherenceGateEnabled:()=>f,isColdTierGNNEnabled:()=>P,isCrossDomainTransferEnabled:()=>N,isCusumDriftDetectionEnabled:()=>F,isDAGAttentionEnabled:()=>g,isDeltaEventSourcingEnabled:()=>M,isDeterministicDitherEnabled:()=>T,isEpropOnlineLearningEnabled:()=>Q,isEwcPlusPlusEnabled:()=>L,isFlashAttentionEnabled:()=>E,isGNNIndexEnabled:()=>R,isGrangerCausalityEnabled:()=>B,isGraphMAEEnabled:()=>x,isHDCFingerprintingEnabled:()=>D,isHnswHealthMonitorEnabled:()=>U,isHopfieldMemoryEnabled:()=>h,isHyperbolicHnswEnabled:()=>k,isMetaLearningEnabled:()=>m,isMetadataFilteringEnabled:()=>S,isNativeHNSWEnabled:()=>_,isNeuralRoutingEnabled:()=>C,isRVFPatternStoreEnabled:()=>V,isReasoningQECEnabled:()=>v,isRegretTrackingEnabled:()=>O,isReservoirReplayEnabled:()=>w,isSONAEnabled:()=>a,isSONAThreeLoopEnabled:()=>p,isSpectralSparsificationEnabled:()=>W,isSublinearSolverEnabled:()=>y,isTemporalCompressionEnabled:()=>c,isUnifiedHnswEnabled:()=>G,isWitnessChainEnabled:()=>d,resetRuVectorFeatureFlags:()=>i,setRuVectorFeatureFlags:()=>o,shouldLogMigrationMetrics:()=>l});function u(){return{...e}}function o(n){e={...e,...n}}function i(){e={...r}}function a(){return e.useQESONA}function E(){return e.useQEFlashAttention}function R(){return e.useQEGNNIndex}function l(){return e.logMigrationMetrics}function _(){return e.useNativeHNSW}function c(){return e.useTemporalCompression}function S(){return e.useMetadataFiltering}function T(){return e.useDeterministicDither}function C(){return e.useNeuralRouting}function p(){return e.useSONAThreeLoop}function N(){return e.useCrossDomainTransfer}function U(){return e.useHnswHealthMonitor}function O(){return e.useRegretTracking}function f(){return e.useCoherenceGate}function d(){return e.useWitnessChain}function b(){return e.useCNNVisualRegression}function g(){return e.useDAGAttention}function A(){return e.useCoherenceActionGate}function v(){return e.useReasoningQEC}function V(){return e.useRVFPatternStore}function I(){return e.useAgentMemoryBranching}function G(){return e.useUnifiedHnsw}function H(){return e.rvfMigrationStage}function D(){return e.useHDCFingerprinting}function F(){return e.useCusumDriftDetection}function M(){return e.useDeltaEventSourcing}function L(){return e.useEwcPlusPlusRegularization}function x(){return e.useGraphMAEEmbeddings}function h(){return e.useHopfieldMemory}function P(){return e.useColdTierGNN}function m(){return e.useMetaLearningEnhancements}function y(){return e.useSublinearSolver}function W(){return e.useSpectralSparsification}function w(){return e.useReservoirReplay}function Q(){return e.useEpropOnlineLearning}function B(){return e.useGrangerCausality}function Y(){return e.useCognitiveRouting}function k(){return e.useHyperbolicHnsw}function z(){let n={};process.env.RUVECTOR_USE_RVF_PATTERN_STORE!==void 0&&(n.useRVFPatternStore=process.env.RUVECTOR_USE_RVF_PATTERN_STORE==="true"),process.env.RUVECTOR_USE_SONA!==void 0&&(n.useQESONA=process.env.RUVECTOR_USE_SONA==="true"),process.env.RUVECTOR_USE_FLASH_ATTENTION!==void 0&&(n.useQEFlashAttention=process.env.RUVECTOR_USE_FLASH_ATTENTION==="true"),process.env.RUVECTOR_USE_GNN_INDEX!==void 0&&(n.useQEGNNIndex=process.env.RUVECTOR_USE_GNN_INDEX==="true"),process.env.RUVECTOR_LOG_MIGRATION_METRICS!==void 0&&(n.logMigrationMetrics=process.env.RUVECTOR_LOG_MIGRATION_METRICS==="true"),process.env.RUVECTOR_USE_NATIVE_HNSW!==void 0&&(n.useNativeHNSW=process.env.RUVECTOR_USE_NATIVE_HNSW==="true"),process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION!==void 0&&(n.useTemporalCompression=process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION==="true"),process.env.RUVECTOR_USE_METADATA_FILTERING!==void 0&&(n.useMetadataFiltering=process.env.RUVECTOR_USE_METADATA_FILTERING==="true"),process.env.RUVECTOR_USE_DETERMINISTIC_DITHER!==void 0&&(n.useDeterministicDither=process.env.RUVECTOR_USE_DETERMINISTIC_DITHER==="true"),process.env.RUVECTOR_USE_NEURAL_ROUTING!==void 0&&(n.useNeuralRouting=process.env.RUVECTOR_USE_NEURAL_ROUTING==="true"),process.env.RUVECTOR_USE_SONA_THREE_LOOP!==void 0&&(n.useSONAThreeLoop=process.env.RUVECTOR_USE_SONA_THREE_LOOP==="true"),process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER!==void 0&&(n.useCrossDomainTransfer=process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER==="true"),process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR!==void 0&&(n.useHnswHealthMonitor=process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR==="true"),process.env.RUVECTOR_USE_REGRET_TRACKING!==void 0&&(n.useRegretTracking=process.env.RUVECTOR_USE_REGRET_TRACKING==="true"),process.env.RUVECTOR_USE_COHERENCE_GATE!==void 0&&(n.useCoherenceGate=process.env.RUVECTOR_USE_COHERENCE_GATE==="true"),process.env.RUVECTOR_USE_WITNESS_CHAIN!==void 0&&(n.useWitnessChain=process.env.RUVECTOR_USE_WITNESS_CHAIN==="true"),process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION!==void 0&&(n.useCNNVisualRegression=process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION==="true"),process.env.RUVECTOR_USE_DAG_ATTENTION!==void 0&&(n.useDAGAttention=process.env.RUVECTOR_USE_DAG_ATTENTION==="true"),process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE!==void 0&&(n.useCoherenceActionGate=process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE==="true"),process.env.RUVECTOR_USE_REASONING_QEC!==void 0&&(n.useReasoningQEC=process.env.RUVECTOR_USE_REASONING_QEC==="true"),process.env.RUVECTOR_USE_HDC_FINGERPRINTING!==void 0&&(n.useHDCFingerprinting=process.env.RUVECTOR_USE_HDC_FINGERPRINTING==="true"),process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION!==void 0&&(n.useCusumDriftDetection=process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION==="true"),process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING!==void 0&&(n.useDeltaEventSourcing=process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING==="true"),process.env.RUVECTOR_USE_EWC_PLUS_PLUS!==void 0&&(n.useEwcPlusPlusRegularization=process.env.RUVECTOR_USE_EWC_PLUS_PLUS==="true"),process.env.RUVECTOR_USE_META_LEARNING!==void 0&&(n.useMetaLearningEnhancements=process.env.RUVECTOR_USE_META_LEARNING==="true"),process.env.RUVECTOR_USE_SUBLINEAR_SOLVER!==void 0&&(n.useSublinearSolver=process.env.RUVECTOR_USE_SUBLINEAR_SOLVER==="true"),process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION!==void 0&&(n.useSpectralSparsification=process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION==="true"),process.env.RUVECTOR_USE_RESERVOIR_REPLAY!==void 0&&(n.useReservoirReplay=process.env.RUVECTOR_USE_RESERVOIR_REPLAY==="true"),process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING!==void 0&&(n.useEpropOnlineLearning=process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING==="true"),process.env.RUVECTOR_USE_GRANGER_CAUSALITY!==void 0&&(n.useGrangerCausality=process.env.RUVECTOR_USE_GRANGER_CAUSALITY==="true"),process.env.RUVECTOR_USE_COGNITIVE_ROUTING!==void 0&&(n.useCognitiveRouting=process.env.RUVECTOR_USE_COGNITIVE_ROUTING==="true"),process.env.RUVECTOR_USE_HYPERBOLIC_HNSW!==void 0&&(n.useHyperbolicHnsw=process.env.RUVECTOR_USE_HYPERBOLIC_HNSW==="true"),o(n)}var r,e,X=s(()=>{r={useQESONA:!0,useQEFlashAttention:!0,useQEGNNIndex:!0,logMigrationMetrics:!0,useNativeHNSW:!0,useTemporalCompression:!0,useMetadataFiltering:!0,useDeterministicDither:!0,useNeuralRouting:!0,useSONAThreeLoop:!0,useCrossDomainTransfer:!0,useHnswHealthMonitor:!0,useRegretTracking:!0,useCoherenceGate:!0,useWitnessChain:!0,useCNNVisualRegression:!0,useDAGAttention:!0,useCoherenceActionGate:!0,useReasoningQEC:!0,useRVFPatternStore:!0,useAgentMemoryBranching:!0,useUnifiedHnsw:!0,rvfMigrationStage:2,useHDCFingerprinting:!0,useCusumDriftDetection:!0,useDeltaEventSourcing:!0,useEwcPlusPlusRegularization:!0,useGraphMAEEmbeddings:!0,useHopfieldMemory:!0,useColdTierGNN:!0,useMetaLearningEnhancements:!0,useSublinearSolver:!0,useSpectralSparsification:!0,useReservoirReplay:!0,useEpropOnlineLearning:!0,useGrangerCausality:!0,useCognitiveRouting:!1,useHyperbolicHnsw:!1},e={...r}});export{r as a,u as b,o as c,i as d,a as e,E as f,R as g,l as h,_ as i,c as j,S as k,T as l,C as m,p as n,N as o,U as p,O as q,f as r,d as s,b as t,g as u,A as v,v as w,V as x,I as y,G as z,H as A,D as B,F as C,M as D,L as E,x as F,h as G,P as H,m as I,y as J,W as K,w as L,Q as M,B as N,Y as O,k as P,z as Q,K as R,X as S};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.2");process.exit(0)}
2
+ import{c as s,e as t}from"./chunk-AJ7A52GF.js";var K={};t(K,{DEFAULT_FEATURE_FLAGS:()=>r,getRuVectorFeatureFlags:()=>u,getRvfMigrationStage:()=>H,initFeatureFlagsFromEnv:()=>z,isAgentMemoryBranchingEnabled:()=>I,isCNNVisualRegressionEnabled:()=>b,isCognitiveRoutingEnabled:()=>Y,isCoherenceActionGateEnabled:()=>A,isCoherenceGateEnabled:()=>f,isColdTierGNNEnabled:()=>P,isCrossDomainTransferEnabled:()=>N,isCusumDriftDetectionEnabled:()=>F,isDAGAttentionEnabled:()=>g,isDeltaEventSourcingEnabled:()=>M,isDeterministicDitherEnabled:()=>T,isEpropOnlineLearningEnabled:()=>Q,isEwcPlusPlusEnabled:()=>L,isFlashAttentionEnabled:()=>E,isGNNIndexEnabled:()=>R,isGrangerCausalityEnabled:()=>B,isGraphMAEEnabled:()=>x,isHDCFingerprintingEnabled:()=>D,isHnswHealthMonitorEnabled:()=>U,isHopfieldMemoryEnabled:()=>h,isHyperbolicHnswEnabled:()=>k,isMetaLearningEnabled:()=>m,isMetadataFilteringEnabled:()=>S,isNativeHNSWEnabled:()=>_,isNeuralRoutingEnabled:()=>C,isRVFPatternStoreEnabled:()=>V,isReasoningQECEnabled:()=>v,isRegretTrackingEnabled:()=>O,isReservoirReplayEnabled:()=>w,isSONAEnabled:()=>a,isSONAThreeLoopEnabled:()=>p,isSpectralSparsificationEnabled:()=>W,isSublinearSolverEnabled:()=>y,isTemporalCompressionEnabled:()=>c,isUnifiedHnswEnabled:()=>G,isWitnessChainEnabled:()=>d,resetRuVectorFeatureFlags:()=>i,setRuVectorFeatureFlags:()=>o,shouldLogMigrationMetrics:()=>l});function u(){return{...e}}function o(n){e={...e,...n}}function i(){e={...r}}function a(){return e.useQESONA}function E(){return e.useQEFlashAttention}function R(){return e.useQEGNNIndex}function l(){return e.logMigrationMetrics}function _(){return e.useNativeHNSW}function c(){return e.useTemporalCompression}function S(){return e.useMetadataFiltering}function T(){return e.useDeterministicDither}function C(){return e.useNeuralRouting}function p(){return e.useSONAThreeLoop}function N(){return e.useCrossDomainTransfer}function U(){return e.useHnswHealthMonitor}function O(){return e.useRegretTracking}function f(){return e.useCoherenceGate}function d(){return e.useWitnessChain}function b(){return e.useCNNVisualRegression}function g(){return e.useDAGAttention}function A(){return e.useCoherenceActionGate}function v(){return e.useReasoningQEC}function V(){return e.useRVFPatternStore}function I(){return e.useAgentMemoryBranching}function G(){return e.useUnifiedHnsw}function H(){return e.rvfMigrationStage}function D(){return e.useHDCFingerprinting}function F(){return e.useCusumDriftDetection}function M(){return e.useDeltaEventSourcing}function L(){return e.useEwcPlusPlusRegularization}function x(){return e.useGraphMAEEmbeddings}function h(){return e.useHopfieldMemory}function P(){return e.useColdTierGNN}function m(){return e.useMetaLearningEnhancements}function y(){return e.useSublinearSolver}function W(){return e.useSpectralSparsification}function w(){return e.useReservoirReplay}function Q(){return e.useEpropOnlineLearning}function B(){return e.useGrangerCausality}function Y(){return e.useCognitiveRouting}function k(){return e.useHyperbolicHnsw}function z(){let n={};process.env.RUVECTOR_USE_RVF_PATTERN_STORE!==void 0&&(n.useRVFPatternStore=process.env.RUVECTOR_USE_RVF_PATTERN_STORE==="true"),process.env.RUVECTOR_USE_SONA!==void 0&&(n.useQESONA=process.env.RUVECTOR_USE_SONA==="true"),process.env.RUVECTOR_USE_FLASH_ATTENTION!==void 0&&(n.useQEFlashAttention=process.env.RUVECTOR_USE_FLASH_ATTENTION==="true"),process.env.RUVECTOR_USE_GNN_INDEX!==void 0&&(n.useQEGNNIndex=process.env.RUVECTOR_USE_GNN_INDEX==="true"),process.env.RUVECTOR_LOG_MIGRATION_METRICS!==void 0&&(n.logMigrationMetrics=process.env.RUVECTOR_LOG_MIGRATION_METRICS==="true"),process.env.RUVECTOR_USE_NATIVE_HNSW!==void 0&&(n.useNativeHNSW=process.env.RUVECTOR_USE_NATIVE_HNSW==="true"),process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION!==void 0&&(n.useTemporalCompression=process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION==="true"),process.env.RUVECTOR_USE_METADATA_FILTERING!==void 0&&(n.useMetadataFiltering=process.env.RUVECTOR_USE_METADATA_FILTERING==="true"),process.env.RUVECTOR_USE_DETERMINISTIC_DITHER!==void 0&&(n.useDeterministicDither=process.env.RUVECTOR_USE_DETERMINISTIC_DITHER==="true"),process.env.RUVECTOR_USE_NEURAL_ROUTING!==void 0&&(n.useNeuralRouting=process.env.RUVECTOR_USE_NEURAL_ROUTING==="true"),process.env.RUVECTOR_USE_SONA_THREE_LOOP!==void 0&&(n.useSONAThreeLoop=process.env.RUVECTOR_USE_SONA_THREE_LOOP==="true"),process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER!==void 0&&(n.useCrossDomainTransfer=process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER==="true"),process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR!==void 0&&(n.useHnswHealthMonitor=process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR==="true"),process.env.RUVECTOR_USE_REGRET_TRACKING!==void 0&&(n.useRegretTracking=process.env.RUVECTOR_USE_REGRET_TRACKING==="true"),process.env.RUVECTOR_USE_COHERENCE_GATE!==void 0&&(n.useCoherenceGate=process.env.RUVECTOR_USE_COHERENCE_GATE==="true"),process.env.RUVECTOR_USE_WITNESS_CHAIN!==void 0&&(n.useWitnessChain=process.env.RUVECTOR_USE_WITNESS_CHAIN==="true"),process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION!==void 0&&(n.useCNNVisualRegression=process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION==="true"),process.env.RUVECTOR_USE_DAG_ATTENTION!==void 0&&(n.useDAGAttention=process.env.RUVECTOR_USE_DAG_ATTENTION==="true"),process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE!==void 0&&(n.useCoherenceActionGate=process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE==="true"),process.env.RUVECTOR_USE_REASONING_QEC!==void 0&&(n.useReasoningQEC=process.env.RUVECTOR_USE_REASONING_QEC==="true"),process.env.RUVECTOR_USE_HDC_FINGERPRINTING!==void 0&&(n.useHDCFingerprinting=process.env.RUVECTOR_USE_HDC_FINGERPRINTING==="true"),process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION!==void 0&&(n.useCusumDriftDetection=process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION==="true"),process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING!==void 0&&(n.useDeltaEventSourcing=process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING==="true"),process.env.RUVECTOR_USE_EWC_PLUS_PLUS!==void 0&&(n.useEwcPlusPlusRegularization=process.env.RUVECTOR_USE_EWC_PLUS_PLUS==="true"),process.env.RUVECTOR_USE_META_LEARNING!==void 0&&(n.useMetaLearningEnhancements=process.env.RUVECTOR_USE_META_LEARNING==="true"),process.env.RUVECTOR_USE_SUBLINEAR_SOLVER!==void 0&&(n.useSublinearSolver=process.env.RUVECTOR_USE_SUBLINEAR_SOLVER==="true"),process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION!==void 0&&(n.useSpectralSparsification=process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION==="true"),process.env.RUVECTOR_USE_RESERVOIR_REPLAY!==void 0&&(n.useReservoirReplay=process.env.RUVECTOR_USE_RESERVOIR_REPLAY==="true"),process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING!==void 0&&(n.useEpropOnlineLearning=process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING==="true"),process.env.RUVECTOR_USE_GRANGER_CAUSALITY!==void 0&&(n.useGrangerCausality=process.env.RUVECTOR_USE_GRANGER_CAUSALITY==="true"),process.env.RUVECTOR_USE_COGNITIVE_ROUTING!==void 0&&(n.useCognitiveRouting=process.env.RUVECTOR_USE_COGNITIVE_ROUTING==="true"),process.env.RUVECTOR_USE_HYPERBOLIC_HNSW!==void 0&&(n.useHyperbolicHnsw=process.env.RUVECTOR_USE_HYPERBOLIC_HNSW==="true"),o(n)}var r,e,X=s(()=>{r={useQESONA:!0,useQEFlashAttention:!0,useQEGNNIndex:!0,logMigrationMetrics:!0,useNativeHNSW:!0,useTemporalCompression:!0,useMetadataFiltering:!0,useDeterministicDither:!0,useNeuralRouting:!0,useSONAThreeLoop:!0,useCrossDomainTransfer:!0,useHnswHealthMonitor:!0,useRegretTracking:!0,useCoherenceGate:!0,useWitnessChain:!0,useCNNVisualRegression:!0,useDAGAttention:!0,useCoherenceActionGate:!0,useReasoningQEC:!0,useRVFPatternStore:!0,useAgentMemoryBranching:!0,useUnifiedHnsw:!0,rvfMigrationStage:2,useHDCFingerprinting:!0,useCusumDriftDetection:!0,useDeltaEventSourcing:!0,useEwcPlusPlusRegularization:!0,useGraphMAEEmbeddings:!0,useHopfieldMemory:!0,useColdTierGNN:!0,useMetaLearningEnhancements:!0,useSublinearSolver:!0,useSpectralSparsification:!0,useReservoirReplay:!0,useEpropOnlineLearning:!0,useGrangerCausality:!0,useCognitiveRouting:!1,useHyperbolicHnsw:!1},e={...r}});export{r as a,u as b,o as c,i as d,a as e,E as f,R as g,l as h,_ as i,c as j,S as k,T as l,C as m,p as n,N as o,U as p,O as q,f as r,d as s,b as t,g as u,A as v,v as w,V as x,I as y,G as z,H as A,D as B,F as C,M as D,L as E,x as F,h as G,P as H,m as I,y as J,W as K,w as L,Q as M,B as N,Y as O,k as P,z as Q,K as R,X as S};
@@ -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.13.0");process.exit(0)}
2
- import{b as d,d as L}from"./chunk-G5DFYX3J.js";import{createHash as m}from"crypto";import{existsSync as g,readFileSync as R,writeFileSync as A,openSync as X,writeSync as U,closeSync as f}from"fs";var p=[`CREATE TABLE IF NOT EXISTS qe_patterns (
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.13.2");process.exit(0)}
2
+ import{b as d,d as L}from"./chunk-U2FCUBBW.js";import{createHash as m}from"crypto";import{existsSync as g,readFileSync as R,writeFileSync as A,openSync as X,writeSync as U,closeSync as f}from"fs";var p=[`CREATE TABLE IF NOT EXISTS qe_patterns (
3
3
  id TEXT PRIMARY KEY, pattern_type TEXT NOT NULL, qe_domain TEXT NOT NULL,
4
4
  domain TEXT NOT NULL, name TEXT NOT NULL, description TEXT,
5
5
  confidence REAL DEFAULT 0.5, usage_count INTEGER DEFAULT 0,
@@ -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.13.0");process.exit(0)}
2
- import{f as s,i as o,m as h}from"./chunk-G5DFYX3J.js";import{a as m}from"./chunk-HVB2L52I.js";import{c as r}from"./chunk-OXXMVQDF.js";import{a,e as u}from"./chunk-LBE2P6UC.js";h();u();m();var l=r.create("hybrid-backend"),c=class{unifiedMemory=null;config;cleanupInterval;cleanupCount=0;initialized=!1;constructor(e){this.config={sqlite:{path:e?.sqlite?.path??".agentic-qe/memory.db",walMode:e?.sqlite?.walMode??!0,poolSize:e?.sqlite?.poolSize??5,busyTimeout:e?.sqlite?.busyTimeout??a.BUSY_TIMEOUT_MS,...e?.sqlite},agentdb:{path:e?.agentdb?.path??".agentic-qe/memory.db",...e?.agentdb},enableFallback:e?.enableFallback??!0,defaultNamespace:e?.defaultNamespace??"default",cleanupInterval:e?.cleanupInterval??a.CLEANUP_INTERVAL_MS}}async initialize(e){if(this.initialized)return;let i=e?.signal;i?.throwIfAborted();let t={dbPath:this.config.sqlite.path??s.dbPath,walMode:this.config.sqlite.walMode??!0,busyTimeout:this.config.sqlite.busyTimeout??a.BUSY_TIMEOUT_MS};this.unifiedMemory=o(t),i?.throwIfAborted(),await this.unifiedMemory.initialize({signal:i}),i?.throwIfAborted(),this.cleanupInterval=setInterval(()=>this.cleanup(),this.config.cleanupInterval),this.cleanupInterval.unref&&this.cleanupInterval.unref(),this.initialized=!0,console.log(`[HybridBackend] Initialized with unified memory: ${this.unifiedMemory.getDbPath()}`)}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.initialized=!1}async set(e,i,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;await this.unifiedMemory.kvSet(e,i,n,t?.ttl)}async get(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvGet(e,t)}async delete(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace,n=await this.unifiedMemory.kvDelete(e,t),d=await this.unifiedMemory.vectorDelete(e);return n||d}async has(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvExists(e,t)}async search(e,i=100,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvSearch(e,n,i)}async vectorSearch(e,i){return this.ensureInitialized(),(await this.unifiedMemory.vectorSearch(e,i)).map(n=>({key:n.id,score:n.score,metadata:n.metadata}))}async storeVector(e,i,t){this.ensureInitialized(),await this.unifiedMemory.vectorStore(e,i,this.config.defaultNamespace,t)}getHealth(){return{sqlite:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",sqlitePersistent:!0,agentdb:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",fallback:"inactive"}}isPersistent(){return this.unifiedMemory?.isInitialized()??!1}getConfig(){return{...this.config}}async setWithBackend(e,i,t,n){await this.set(e,i,n)}async getVectorStats(){if(!this.unifiedMemory?.isInitialized())return null;let e=await this.unifiedMemory.vectorCount(),i=this.unifiedMemory.getStats();return{vectorCount:e,indexSize:i.vectorIndexSize}}getUnifiedMemory(){return this.unifiedMemory}async count(e){return this.ensureInitialized(),this.unifiedMemory.getDatabase().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.13.2");process.exit(0)}
2
+ import{f as s,i as o,m as h}from"./chunk-U2FCUBBW.js";import{a as m}from"./chunk-6UGYFYS4.js";import{c as r}from"./chunk-BSQ32ZS5.js";import{a,e as u}from"./chunk-DIPOFCBX.js";h();u();m();var l=r.create("hybrid-backend"),c=class{unifiedMemory=null;config;cleanupInterval;cleanupCount=0;initialized=!1;constructor(e){this.config={sqlite:{path:e?.sqlite?.path??".agentic-qe/memory.db",walMode:e?.sqlite?.walMode??!0,poolSize:e?.sqlite?.poolSize??5,busyTimeout:e?.sqlite?.busyTimeout??a.BUSY_TIMEOUT_MS,...e?.sqlite},agentdb:{path:e?.agentdb?.path??".agentic-qe/memory.db",...e?.agentdb},enableFallback:e?.enableFallback??!0,defaultNamespace:e?.defaultNamespace??"default",cleanupInterval:e?.cleanupInterval??a.CLEANUP_INTERVAL_MS}}async initialize(e){if(this.initialized)return;let i=e?.signal;i?.throwIfAborted();let t={dbPath:this.config.sqlite.path??s.dbPath,walMode:this.config.sqlite.walMode??!0,busyTimeout:this.config.sqlite.busyTimeout??a.BUSY_TIMEOUT_MS};this.unifiedMemory=o(t),i?.throwIfAborted(),await this.unifiedMemory.initialize({signal:i}),i?.throwIfAborted(),this.cleanupInterval=setInterval(()=>this.cleanup(),this.config.cleanupInterval),this.cleanupInterval.unref&&this.cleanupInterval.unref(),this.initialized=!0,console.log(`[HybridBackend] Initialized with unified memory: ${this.unifiedMemory.getDbPath()}`)}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.initialized=!1}async set(e,i,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;await this.unifiedMemory.kvSet(e,i,n,t?.ttl)}async get(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvGet(e,t)}async delete(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace,n=await this.unifiedMemory.kvDelete(e,t),d=await this.unifiedMemory.vectorDelete(e);return n||d}async has(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvExists(e,t)}async search(e,i=100,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvSearch(e,n,i)}async vectorSearch(e,i){return this.ensureInitialized(),(await this.unifiedMemory.vectorSearch(e,i)).map(n=>({key:n.id,score:n.score,metadata:n.metadata}))}async storeVector(e,i,t){this.ensureInitialized(),await this.unifiedMemory.vectorStore(e,i,this.config.defaultNamespace,t)}getHealth(){return{sqlite:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",sqlitePersistent:!0,agentdb:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",fallback:"inactive"}}isPersistent(){return this.unifiedMemory?.isInitialized()??!1}getConfig(){return{...this.config}}async setWithBackend(e,i,t,n){await this.set(e,i,n)}async getVectorStats(){if(!this.unifiedMemory?.isInitialized())return null;let e=await this.unifiedMemory.vectorCount(),i=this.unifiedMemory.getStats();return{vectorCount:e,indexSize:i.vectorIndexSize}}getUnifiedMemory(){return this.unifiedMemory}async count(e){return this.ensureInitialized(),this.unifiedMemory.getDatabase().prepare(`
3
3
  SELECT COUNT(*) as count FROM kv_store
4
4
  WHERE namespace LIKE ?
5
5
  AND (expires_at IS NULL OR expires_at > ?)
@@ -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.13.0");process.exit(0)}
2
- import{a as L}from"./chunk-QI4CGJNK.js";import*as w from"fs";var R={"aqe test generate":{domain:"test-generation",action:"generateTests"},"aqe test execute":{domain:"test-execution",action:"execute"},"aqe coverage analyze":{domain:"coverage-analysis",action:"analyze"},"aqe coverage gaps":{domain:"coverage-analysis",action:"detectGaps"},"aqe quality gate":{domain:"quality-assessment",action:"evaluateGate"},"aqe quality assess":{domain:"quality-assessment",action:"analyzeQuality"},"aqe security scan":{domain:"security-compliance",action:"runSASTScan"},"aqe security audit":{domain:"security-compliance",action:"runAudit"},"aqe defect predict":{domain:"defect-intelligence",action:"predictDefects"},"aqe code index":{domain:"code-intelligence",action:"index"},"aqe code impact":{domain:"code-intelligence",action:"analyzeImpact"},"aqe contract validate":{domain:"contract-testing",action:"validateContract"},"aqe chaos test":{domain:"chaos-resilience",action:"runChaosTest"},"aqe requirements validate":{domain:"requirements-validation",action:"validateRequirements"},"aqe visual test":{domain:"visual-accessibility",action:"runVisualTest"},"aqe accessibility test":{domain:"visual-accessibility",action:"runAccessibilityTest"},"aqe learn optimize":{domain:"learning-optimization",action:"optimizeAllStrategies"}},D={daily:"0 0 * * *",weekly:"0 0 * * 0",hourly:"0 * * * *",minutely:"* * * * *"},x=1e4,M=20,S=1e4,W=["__proto__","constructor","prototype"];function v(t){return!W.includes(t)}function C(t){let n=t.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.2");process.exit(0)}
2
+ import{a as L}from"./chunk-E6JJ4ZRQ.js";import*as w from"fs";var R={"aqe test generate":{domain:"test-generation",action:"generateTests"},"aqe test execute":{domain:"test-execution",action:"execute"},"aqe coverage analyze":{domain:"coverage-analysis",action:"analyze"},"aqe coverage gaps":{domain:"coverage-analysis",action:"detectGaps"},"aqe quality gate":{domain:"quality-assessment",action:"evaluateGate"},"aqe quality assess":{domain:"quality-assessment",action:"analyzeQuality"},"aqe security scan":{domain:"security-compliance",action:"runSASTScan"},"aqe security audit":{domain:"security-compliance",action:"runAudit"},"aqe defect predict":{domain:"defect-intelligence",action:"predictDefects"},"aqe code index":{domain:"code-intelligence",action:"index"},"aqe code impact":{domain:"code-intelligence",action:"analyzeImpact"},"aqe contract validate":{domain:"contract-testing",action:"validateContract"},"aqe chaos test":{domain:"chaos-resilience",action:"runChaosTest"},"aqe requirements validate":{domain:"requirements-validation",action:"validateRequirements"},"aqe visual test":{domain:"visual-accessibility",action:"runVisualTest"},"aqe accessibility test":{domain:"visual-accessibility",action:"runAccessibilityTest"},"aqe learn optimize":{domain:"learning-optimization",action:"optimizeAllStrategies"}},D={daily:"0 0 * * *",weekly:"0 0 * * 0",hourly:"0 * * * *",minutely:"* * * * *"},x=1e4,M=20,S=1e4,W=["__proto__","constructor","prototype"];function v(t){return!W.includes(t)}function C(t){let n=t.split(`
3
3
  `);if(n.length>x)throw new Error(`YAML content exceeds maximum allowed lines (${x}). File has ${n.length} lines.`);for(let i=0;i<n.length;i++)if(n[i].length>S)throw new Error(`YAML line ${i+1} exceeds maximum allowed length (${S} characters).`);let a={};for(let i=0;i<n.length;i++){let e=n[i];if(e.trim()===""||e.trim().startsWith("#")||e.search(/\S/)!==0)continue;let o=e.match(/^([\w_-]+):\s*(.+)$/);if(o){let[,c,u]=o;v(c)&&(a[c]=f(u))}}let r=["tags","stages","triggers"];for(let i of r){let e=new RegExp(`^${i}:\\s*$`),s=-1;for(let l=0;l<n.length;l++){let d=n[l];if(!(d.trim()===""||d.trim().startsWith("#"))&&e.test(d.trim())){s=l;break}}if(s===-1)continue;let o=[];a[i]=o;let c=n[s].search(/\S/),u=s+1;for(;u<n.length;){let l=n[u];if(l.trim()===""||l.trim().startsWith("#")){u++;continue}let d=l.search(/\S/),p=l.trim();if(d<=c&&!p.startsWith("-"))break;if(p.startsWith("- ")){let m=p.slice(2).trim();if(!m.includes(":")){o.push(f(m)),u++;continue}let g={},k=m.match(/^([\w_-]+):\s*(.*)$/);if(k){let[,h,y]=k;g[h]=f(y)}let T=d;for(u++;u<n.length;){let h=n[u];if(h.trim()===""||h.trim().startsWith("#")){u++;continue}let y=h.search(/\S/),q=h.trim();if(y<=T)break;let _=q.match(/^([\w_-]+):\s*(.*)$/);if(_){let[,A,$]=_;if($===""){let b=E(n,u+1,y,1);g[A]=b.value,u=b.nextLine;continue}else g[A]=f($)}u++}o.push(g)}else u++}}return a}function E(t,n,a,r=0){if(r>M)throw new Error(`YAML nesting exceeds maximum allowed depth (${M}).`);let i={},e=null,s=null,o=n;for(;o<t.length;){let u=t[o];if(u.trim()===""||u.trim().startsWith("#")){o++;continue}let l=u.search(/\S/),d=u.trim();if(l<=a)break;if(d.startsWith("- ")){let m=d.slice(2).trim();s&&!Array.isArray(i[s])&&(i[s]=[]),s?i[s].push(f(m)):(e||(e=[]),e.push(f(m))),o++;continue}let p=d.match(/^([\w_-]+):\s*(.*)$/);if(p){let[,m,g]=p;if(!v(m)){o++;continue}g===""?(s=m,i[m]=[]):(i[m]=f(g),s=null)}o++}if(e&&Object.keys(i).length===0)return{value:e,nextLine:o};let c=Object.keys(i);return c.length===1&&Array.isArray(i[c[0]])?{value:i[c[0]],nextLine:o}:{value:i,nextLine:o}}function f(t){if(t==="")return"";if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t==="true")return!0;if(t==="false")return!1;if(t==="null"||t==="~")return null;let n=Number(t);return!isNaN(n)&&t!==""?n:t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1).split(",").map(r=>f(r.trim())):t}function K(t){let n=[];if(!w.existsSync(t))return{success:!1,errors:[`File not found: ${t}`]};let a;try{a=w.readFileSync(t,"utf-8")}catch(r){return{success:!1,errors:[`Failed to read file: ${r}`]}}return Y(a,t)}function Y(t,n){let a=[],r;try{r=C(t)}catch(s){return{success:!1,errors:[`Invalid YAML syntax: ${s}`]}}if((!r.name||typeof r.name!="string")&&a.push('Pipeline must have a "name" field'),(!r.stages||!Array.isArray(r.stages))&&a.push('Pipeline must have a "stages" array'),a.length>0)return{success:!1,errors:a};let i={name:r.name,description:r.description,version:r.version||"1.0.0",schedule:r.schedule,stages:r.stages.map((s,o)=>{let c=s;return{name:c.name||`stage-${o}`,command:c.command,params:c.params,depends_on:c.depends_on,condition:c.condition,timeout:c.timeout,retry:c.retry,continue_on_failure:c.continue_on_failure}}),triggers:r.triggers,tags:r.tags,timeout:r.timeout};for(let s=0;s<i.stages.length;s++){let o=i.stages[s];o.command||a.push(`Stage ${s+1} (${o.name}) must have a "command" field`)}if(a.length>0)return{success:!1,pipeline:i,errors:a};let e=O(i,n);return{success:!0,pipeline:i,workflow:e,errors:[]}}function O(t,n){let a=`pipeline-${t.name.replace(/\s+/g,"-").toLowerCase()}`,r=t.stages.map((e,s)=>{let o=P(e.command),c={};if(e.params)for(let[l,d]of Object.entries(e.params))v(l)&&(c[l]=`input.${l}`);let u={id:`stage-${e.name.replace(/\s+/g,"-").toLowerCase()}`,name:e.name,domain:o.domain,action:o.action,inputMapping:Object.keys(c).length>0?c:void 0,dependsOn:e.depends_on?.map(l=>`stage-${l.replace(/\s+/g,"-").toLowerCase()}`),timeout:e.timeout?e.timeout*1e3:void 0,continueOnFailure:e.continue_on_failure};return e.condition&&(u.condition={path:e.condition.path,operator:e.condition.operator,value:e.condition.value}),e.retry&&(u.retry={maxAttempts:e.retry.max_attempts||3,backoffMs:(e.retry.backoff_seconds||1)*1e3}),u}),i=t.triggers?.map(e=>{let s={eventType:I(e),sourceDomain:e.source_domain};return e.condition&&(s.condition={path:e.condition.path,operator:e.condition.operator,value:e.condition.value}),s});return{id:a,name:t.name,description:t.description||`Pipeline from ${n||"inline YAML"}`,version:t.version||"1.0.0",steps:r,triggers:i,tags:t.tags,timeout:t.timeout?t.timeout*1e3:void 0}}function P(t){let n=t.trim().replace(/\s+/g," ").toLowerCase();for(let[a,r]of Object.entries(R))if(n.startsWith(a.toLowerCase()))return r;return n.includes("test")&&n.includes("generate")?{domain:"test-generation",action:"generateTests"}:n.includes("test")&&(n.includes("execute")||n.includes("run"))?{domain:"test-execution",action:"execute"}:n.includes("coverage")?{domain:"coverage-analysis",action:"analyze"}:n.includes("quality")||n.includes("gate")?{domain:"quality-assessment",action:"evaluateGate"}:n.includes("security")||n.includes("scan")?{domain:"security-compliance",action:"runSASTScan"}:n.includes("defect")||n.includes("predict")?{domain:"defect-intelligence",action:"predictDefects"}:{domain:"learning-optimization",action:"runLearningCycle"}}function I(t){let n=t.event.toLowerCase();return n==="push"?"code-intelligence.CodePushed":n==="pull_request"||n==="pr"?"code-intelligence.PullRequestOpened":n==="schedule"?"workflow.ScheduleTrigger":n==="quality_gate"?"quality-assessment.QualityGateEvaluated":n==="test_complete"?"test-execution.TestRunCompleted":n}function F(t){let n=[],a=[];if(t.name||n.push({path:"name",message:"Pipeline name is required",severity:"error"}),!t.stages||t.stages.length===0)n.push({path:"stages",message:"Pipeline must have at least one stage",severity:"error"});else{let r=new Set;for(let e=0;e<t.stages.length;e++){let s=t.stages[e],o=`stages[${e}]`;if(r.has(s.name)&&n.push({path:`${o}.name`,message:`Duplicate stage name: ${s.name}`,severity:"error"}),r.add(s.name),s.command?P(s.command).domain==="learning-optimization"&&!s.command.toLowerCase().includes("learn")&&a.push({path:`${o}.command`,message:`Command "${s.command}" not recognized, will default to learning-optimization domain`,severity:"warning"}):n.push({path:`${o}.command`,message:"Stage must have a command",severity:"error"}),s.depends_on)for(let c of s.depends_on)t.stages.some(u=>u.name===c)||n.push({path:`${o}.depends_on`,message:`Unknown dependency: ${c}`,severity:"error"});s.timeout!==void 0&&s.timeout<=0&&n.push({path:`${o}.timeout`,message:"Timeout must be a positive number",severity:"error"}),s.retry&&s.retry.max_attempts!==void 0&&s.retry.max_attempts<1&&n.push({path:`${o}.retry.max_attempts`,message:"max_attempts must be at least 1",severity:"error"})}let i=N(t.stages);i&&n.push({path:"stages",message:`Circular dependency detected: ${i}`,severity:"error"})}if(t.schedule&&(z(t.schedule)||n.push({path:"schedule",message:`Invalid cron expression: ${t.schedule}`,severity:"error"})),t.triggers)for(let r=0;r<t.triggers.length;r++){let i=t.triggers[r],e=`triggers[${r}]`;i.event||n.push({path:`${e}.event`,message:"Trigger must have an event type",severity:"error"}),i.source_domain&&!L.includes(i.source_domain)&&a.push({path:`${e}.source_domain`,message:`Unknown domain: ${i.source_domain}`,severity:"warning"})}return{valid:n.length===0,errors:n,warnings:a}}function N(t){let n=new Set,a=new Set,r=(i,e)=>{if(a.has(i))return[...e,i].join(" -> ");if(n.has(i))return null;n.add(i),a.add(i);let s=t.find(o=>o.name===i);if(s?.depends_on)for(let o of s.depends_on){let c=r(o,[...e,i]);if(c)return c}return a.delete(i),null};for(let i of t){let e=r(i.name,[]);if(e)return e}return null}function z(t){if(Object.keys(D).includes(t))return!0;let n=t.trim().split(/\s+/);if(n.length!==5)return!1;let a=[/^(\*|[0-5]?\d)(-[0-5]?\d)?(\/\d+)?$/,/^(\*|1?\d|2[0-3])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|[12]\d|3[01])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|1[0-2])(-\d+)?(\/\d+)?$/,/^(\*|[0-7])(-[0-7])?(\/\d+)?$/];for(let r=0;r<5;r++){let i=n[r].split(",");for(let e of i)if(!a[r].test(e)&&e!=="*")return!1}return!0}function G(t){let n={"@daily":"Daily at midnight","@weekly":"Weekly on Sunday at midnight","@hourly":"Every hour","@minutely":"Every minute"};if(n[t])return n[t];if(Object.keys(D).includes(t))return{daily:"Daily at midnight",weekly:"Weekly on Sunday at midnight",hourly:"Every hour",minutely:"Every minute"}[t]||t;let a=t.trim().split(/\s+/);if(a.length!==5)return t;let[r,i,e,s,o]=a;return r==="0"&&i==="0"&&e==="*"&&s==="*"&&o==="*"?"Daily at midnight":r==="0"&&e==="*"&&s==="*"&&o==="*"?`Daily at ${i}:00`:r!=="*"&&i!=="*"&&e==="*"&&s==="*"?`Daily at ${i}:${r.padStart(2,"0")}`:i==="*"&&r==="0"?"Every hour":r!=="*"&&i==="*"?`Every hour at minute ${r}`:t}function H(t,n=new Date){let a=t.trim().split(/\s+/);if(a.length!==5)return new Date(n.getTime()+1440*60*1e3);let[r,i]=a,e=new Date(n);return i!=="*"&&r!=="*"?(e.setHours(parseInt(i,10),parseInt(r,10),0,0),e<=n&&e.setDate(e.getDate()+1)):i!=="*"?(e.setHours(parseInt(i,10),0,0,0),e<=n&&e.setDate(e.getDate()+1)):r!=="*"?(e.setMinutes(parseInt(r,10),0,0),e<=n&&e.setHours(e.getHours()+1)):(e.setSeconds(0,0),e.setMinutes(e.getMinutes()+1)),e}export{C as a,K as b,F as c,G as d,H as e};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
2
- import{b as v}from"./chunk-5EIOQCGN.js";import{a as he,c as ge}from"./chunk-OETDMOOE.js";import{a as se,b as Me}from"./chunk-IPHLXAMX.js";import{a}from"./chunk-6SXKCIN5.js";import{d as fe}from"./chunk-IHQTXJAQ.js";import{b as R,c as me}from"./chunk-FBBZHATF.js";import{b as K,d as de}from"./chunk-2DIT5AUU.js";import{b as E,c as L}from"./chunk-CYL2FV23.js";import{b as pe,d as we}from"./chunk-RDU4WTV2.js";we();L();var ye={failureThreshold:5,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,includeTimeouts:!0},ne=class{state="closed";failures=[];successCount=0;totalRequests=0;totalSuccesses=0;totalFailures=0;rejectedCount=0;lastFailureTime;lastSuccessTime;openedAt;halfOpenSuccesses=0;config;providerType;constructor(t,e={}){this.providerType=t,this.config={...ye,...e}}getState(){return this.state==="open"&&this.openedAt&&Date.now()-this.openedAt.getTime()>=this.config.resetTimeoutMs&&this.transitionTo("half-open"),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t!=="open"}async execute(t){if(this.totalRequests++,this.getState()==="open")throw this.rejectedCount++,a(`Circuit breaker is open for provider ${this.providerType}`,"CIRCUIT_OPEN",{provider:this.providerType,retryable:!0,retryAfterMs:this.getTimeUntilTransition()});try{let r=await t();return this.recordSuccess(),r}catch(r){throw this.recordFailure(E(r)),r}}recordSuccess(){this.successCount++,this.totalSuccesses++,this.lastSuccessTime=new Date,this.getState()==="half-open"&&(this.halfOpenSuccesses++,this.halfOpenSuccesses>=this.config.halfOpenSuccessThreshold&&this.transitionTo("closed"))}recordFailure(t){if(this.totalFailures++,this.lastFailureTime=new Date,(t.message.toLowerCase().includes("timeout")||t.name==="TimeoutError"||t.name==="AbortError")&&!this.config.includeTimeouts)return;this.failures.push({timestamp:new Date,error:t}),this.cleanOldFailures();let r=this.getState();if(r==="half-open"){this.transitionTo("open");return}r==="closed"&&this.failures.length>=this.config.failureThreshold&&this.transitionTo("open")}getStats(){return{state:this.getState(),totalRequests:this.totalRequests,successCount:this.totalSuccesses,failureCount:this.totalFailures,rejectedCount:this.rejectedCount,lastFailureTime:this.lastFailureTime,lastSuccessTime:this.lastSuccessTime,timeUntilTransitionMs:this.getTimeUntilTransition()}}reset(){this.state="closed",this.failures=[],this.successCount=0,this.halfOpenSuccesses=0,this.openedAt=void 0}forceOpen(){this.transitionTo("open")}forceHalfOpen(){this.transitionTo("half-open")}getRecentFailures(t=5){return this.failures.slice(-t).map(e=>`[${e.timestamp.toISOString()}] ${e.error.message}`)}transitionTo(t){if(this.state!==t)switch(this.state=t,t){case"open":this.openedAt=new Date,this.halfOpenSuccesses=0;break;case"half-open":this.halfOpenSuccesses=0;break;case"closed":this.failures=[],this.openedAt=void 0,this.halfOpenSuccesses=0;break}}cleanOldFailures(){let t=Date.now()-this.config.failureWindowMs;this.failures=this.failures.filter(e=>e.timestamp.getTime()>t)}getTimeUntilTransition(){if(this.state==="open"&&this.openedAt){let t=Date.now()-this.openedAt.getTime(),e=this.config.resetTimeoutMs-t;return Math.max(0,e)}}},q=class{breakers=new Map;defaultConfig;constructor(t={}){this.defaultConfig={...ye,...t}}getBreaker(t,e){let r=this.breakers.get(t);return r||(r=new ne(t,{...this.defaultConfig,...e}),this.breakers.set(t,r)),r}getAllStats(){let t={};for(let[e,r]of this.breakers)t[e]=r.getStats();return t}getAvailableProviders(){let t=[];for(let[e,r]of this.breakers)r.canExecute()&&t.push(e);return t}resetAll(){for(let t of this.breakers.values())t.reset()}reset(t){let e=this.breakers.get(t);e&&e.reset()}};var be={maxSize:1e3,defaultTtlMs:36e5,enableLRU:!0,cacheGenerations:!0,cacheEmbeddings:!0,cacheCompletions:!0},M=class{cache=new Map;accessOrder=[];config;hits=0;misses=0;evictions=0;constructor(t={}){this.config={...be,...t}}static generateKey(t,e,r){let n=[t,r?.model??"default",String(r?.temperature??.7),String(r?.maxTokens??0),r?.systemPrompt??"",e].join("|"),s=0;for(let i=0;i<n.length;i++){let l=n.charCodeAt(i);s=(s<<5)-s+l,s=s&s}return`${t}:${Math.abs(s).toString(36)}`}get(t){let e=this.cache.get(t);if(!e){this.misses++;return}if(e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs){this.delete(t),this.misses++;return}return this.hits++,e.lastAccessedAt=new Date,e.accessCount++,this.config.enableLRU&&this.updateAccessOrder(t),e.value}set(t,e,r){this.cache.size>=this.config.maxSize&&!this.cache.has(t)&&this.evictLRU();let o={value:e,createdAt:new Date,lastAccessedAt:new Date,accessCount:1,ttlMs:r??this.config.defaultTtlMs,keyHash:t};this.cache.set(t,o),this.config.enableLRU&&this.updateAccessOrder(t)}has(t){let e=this.cache.get(t);return e?e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs?(this.delete(t),!1):!0:!1}delete(t){let e=this.cache.delete(t);if(e){let r=this.accessOrder.indexOf(t);r!==-1&&this.accessOrder.splice(r,1)}return e}clear(){this.cache.clear(),this.accessOrder=[],this.hits=0,this.misses=0,this.evictions=0}getStats(){let t=this.hits+this.misses,e=t>0?this.hits/t:0,r=0;for(let o of this.cache.values())r+=this.estimateSize(o.value);return{size:this.cache.size,maxSize:this.config.maxSize,hits:this.hits,misses:this.misses,hitRate:e,evictions:this.evictions,memoryUsageBytes:r}}keys(){return Array.from(this.cache.keys())}entries(){return Array.from(this.cache.entries())}import(t){for(let[e,r]of t)r.createdAt=new Date(r.createdAt),r.lastAccessedAt=new Date(r.lastAccessedAt),this.cache.set(e,r),this.accessOrder.push(e);for(;this.cache.size>this.config.maxSize;)this.evictLRU()}pruneExpired(){let t=Date.now(),e=0;for(let[r,o]of this.cache.entries())o.ttlMs>0&&t-o.createdAt.getTime()>o.ttlMs&&(this.delete(r),e++);return e}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e!==-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t)}evictLRU(){if(this.accessOrder.length===0){let e=this.cache.keys().next().value;e&&(this.cache.delete(e),this.evictions++);return}let t=this.accessOrder.shift();t&&(this.cache.delete(t),this.evictions++)}estimateSize(t){return t==null?0:JSON.stringify(t).length*2}},B=class{generationCache;embeddingCache;completionCache;config;constructor(t={}){this.config={...be,...t},this.generationCache=new M(t),this.embeddingCache=new M(t),this.completionCache=new M(t)}getGeneration(t,e){if(!this.config.cacheGenerations)return;let r=M.generateKey("generation",t,e);return this.generationCache.get(r)}setGeneration(t,e,r,o){if(!this.config.cacheGenerations)return;let n=M.generateKey("generation",t,r);this.generationCache.set(n,e,o)}getEmbedding(t,e){if(!this.config.cacheEmbeddings)return;let r=M.generateKey("embedding",t,e);return this.embeddingCache.get(r)}setEmbedding(t,e,r,o){if(!this.config.cacheEmbeddings)return;let n=M.generateKey("embedding",t,r);this.embeddingCache.set(n,e,o)}getCompletion(t,e){if(!this.config.cacheCompletions)return;let r=M.generateKey("completion",t,e);return this.completionCache.get(r)}setCompletion(t,e,r,o){if(!this.config.cacheCompletions)return;let n=M.generateKey("completion",t,r);this.completionCache.set(n,e,o)}getStats(){let t=this.generationCache.getStats(),e=this.embeddingCache.getStats(),r=this.completionCache.getStats(),o=t.hits+e.hits+r.hits,n=t.misses+e.misses+r.misses,s=o+n;return{generation:t,embedding:e,completion:r,total:{size:t.size+e.size+r.size,maxSize:this.config.maxSize*3,hits:o,misses:n,hitRate:s>0?o/s:0,evictions:t.evictions+e.evictions+r.evictions,memoryUsageBytes:t.memoryUsageBytes+e.memoryUsageBytes+r.memoryUsageBytes}}}clear(){this.generationCache.clear(),this.embeddingCache.clear(),this.completionCache.clear()}pruneExpired(){return this.generationCache.pruneExpired()+this.embeddingCache.pruneExpired()+this.completionCache.pruneExpired()}};var ie="(unattributed)",Ae=`
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.13.2");process.exit(0)}
2
+ import{b as v}from"./chunk-JDRYENTD.js";import{a as he,c as ge}from"./chunk-FFMUTX26.js";import{a as se,b as Me}from"./chunk-T2XXTEZV.js";import{a}from"./chunk-M4JZOCV3.js";import{d as fe}from"./chunk-73HALJY5.js";import{b as R,c as me}from"./chunk-Q45FBGVV.js";import{b as K,d as de}from"./chunk-FMYNKZ2S.js";import{b as E,c as L}from"./chunk-IIZ3HBPV.js";import{b as pe,d as we}from"./chunk-TLG56A27.js";we();L();var ye={failureThreshold:5,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,includeTimeouts:!0},ne=class{state="closed";failures=[];successCount=0;totalRequests=0;totalSuccesses=0;totalFailures=0;rejectedCount=0;lastFailureTime;lastSuccessTime;openedAt;halfOpenSuccesses=0;config;providerType;constructor(t,e={}){this.providerType=t,this.config={...ye,...e}}getState(){return this.state==="open"&&this.openedAt&&Date.now()-this.openedAt.getTime()>=this.config.resetTimeoutMs&&this.transitionTo("half-open"),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t!=="open"}async execute(t){if(this.totalRequests++,this.getState()==="open")throw this.rejectedCount++,a(`Circuit breaker is open for provider ${this.providerType}`,"CIRCUIT_OPEN",{provider:this.providerType,retryable:!0,retryAfterMs:this.getTimeUntilTransition()});try{let r=await t();return this.recordSuccess(),r}catch(r){throw this.recordFailure(E(r)),r}}recordSuccess(){this.successCount++,this.totalSuccesses++,this.lastSuccessTime=new Date,this.getState()==="half-open"&&(this.halfOpenSuccesses++,this.halfOpenSuccesses>=this.config.halfOpenSuccessThreshold&&this.transitionTo("closed"))}recordFailure(t){if(this.totalFailures++,this.lastFailureTime=new Date,(t.message.toLowerCase().includes("timeout")||t.name==="TimeoutError"||t.name==="AbortError")&&!this.config.includeTimeouts)return;this.failures.push({timestamp:new Date,error:t}),this.cleanOldFailures();let r=this.getState();if(r==="half-open"){this.transitionTo("open");return}r==="closed"&&this.failures.length>=this.config.failureThreshold&&this.transitionTo("open")}getStats(){return{state:this.getState(),totalRequests:this.totalRequests,successCount:this.totalSuccesses,failureCount:this.totalFailures,rejectedCount:this.rejectedCount,lastFailureTime:this.lastFailureTime,lastSuccessTime:this.lastSuccessTime,timeUntilTransitionMs:this.getTimeUntilTransition()}}reset(){this.state="closed",this.failures=[],this.successCount=0,this.halfOpenSuccesses=0,this.openedAt=void 0}forceOpen(){this.transitionTo("open")}forceHalfOpen(){this.transitionTo("half-open")}getRecentFailures(t=5){return this.failures.slice(-t).map(e=>`[${e.timestamp.toISOString()}] ${e.error.message}`)}transitionTo(t){if(this.state!==t)switch(this.state=t,t){case"open":this.openedAt=new Date,this.halfOpenSuccesses=0;break;case"half-open":this.halfOpenSuccesses=0;break;case"closed":this.failures=[],this.openedAt=void 0,this.halfOpenSuccesses=0;break}}cleanOldFailures(){let t=Date.now()-this.config.failureWindowMs;this.failures=this.failures.filter(e=>e.timestamp.getTime()>t)}getTimeUntilTransition(){if(this.state==="open"&&this.openedAt){let t=Date.now()-this.openedAt.getTime(),e=this.config.resetTimeoutMs-t;return Math.max(0,e)}}},q=class{breakers=new Map;defaultConfig;constructor(t={}){this.defaultConfig={...ye,...t}}getBreaker(t,e){let r=this.breakers.get(t);return r||(r=new ne(t,{...this.defaultConfig,...e}),this.breakers.set(t,r)),r}getAllStats(){let t={};for(let[e,r]of this.breakers)t[e]=r.getStats();return t}getAvailableProviders(){let t=[];for(let[e,r]of this.breakers)r.canExecute()&&t.push(e);return t}resetAll(){for(let t of this.breakers.values())t.reset()}reset(t){let e=this.breakers.get(t);e&&e.reset()}};var be={maxSize:1e3,defaultTtlMs:36e5,enableLRU:!0,cacheGenerations:!0,cacheEmbeddings:!0,cacheCompletions:!0},M=class{cache=new Map;accessOrder=[];config;hits=0;misses=0;evictions=0;constructor(t={}){this.config={...be,...t}}static generateKey(t,e,r){let n=[t,r?.model??"default",String(r?.temperature??.7),String(r?.maxTokens??0),r?.systemPrompt??"",e].join("|"),s=0;for(let i=0;i<n.length;i++){let l=n.charCodeAt(i);s=(s<<5)-s+l,s=s&s}return`${t}:${Math.abs(s).toString(36)}`}get(t){let e=this.cache.get(t);if(!e){this.misses++;return}if(e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs){this.delete(t),this.misses++;return}return this.hits++,e.lastAccessedAt=new Date,e.accessCount++,this.config.enableLRU&&this.updateAccessOrder(t),e.value}set(t,e,r){this.cache.size>=this.config.maxSize&&!this.cache.has(t)&&this.evictLRU();let o={value:e,createdAt:new Date,lastAccessedAt:new Date,accessCount:1,ttlMs:r??this.config.defaultTtlMs,keyHash:t};this.cache.set(t,o),this.config.enableLRU&&this.updateAccessOrder(t)}has(t){let e=this.cache.get(t);return e?e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs?(this.delete(t),!1):!0:!1}delete(t){let e=this.cache.delete(t);if(e){let r=this.accessOrder.indexOf(t);r!==-1&&this.accessOrder.splice(r,1)}return e}clear(){this.cache.clear(),this.accessOrder=[],this.hits=0,this.misses=0,this.evictions=0}getStats(){let t=this.hits+this.misses,e=t>0?this.hits/t:0,r=0;for(let o of this.cache.values())r+=this.estimateSize(o.value);return{size:this.cache.size,maxSize:this.config.maxSize,hits:this.hits,misses:this.misses,hitRate:e,evictions:this.evictions,memoryUsageBytes:r}}keys(){return Array.from(this.cache.keys())}entries(){return Array.from(this.cache.entries())}import(t){for(let[e,r]of t)r.createdAt=new Date(r.createdAt),r.lastAccessedAt=new Date(r.lastAccessedAt),this.cache.set(e,r),this.accessOrder.push(e);for(;this.cache.size>this.config.maxSize;)this.evictLRU()}pruneExpired(){let t=Date.now(),e=0;for(let[r,o]of this.cache.entries())o.ttlMs>0&&t-o.createdAt.getTime()>o.ttlMs&&(this.delete(r),e++);return e}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e!==-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t)}evictLRU(){if(this.accessOrder.length===0){let e=this.cache.keys().next().value;e&&(this.cache.delete(e),this.evictions++);return}let t=this.accessOrder.shift();t&&(this.cache.delete(t),this.evictions++)}estimateSize(t){return t==null?0:JSON.stringify(t).length*2}},B=class{generationCache;embeddingCache;completionCache;config;constructor(t={}){this.config={...be,...t},this.generationCache=new M(t),this.embeddingCache=new M(t),this.completionCache=new M(t)}getGeneration(t,e){if(!this.config.cacheGenerations)return;let r=M.generateKey("generation",t,e);return this.generationCache.get(r)}setGeneration(t,e,r,o){if(!this.config.cacheGenerations)return;let n=M.generateKey("generation",t,r);this.generationCache.set(n,e,o)}getEmbedding(t,e){if(!this.config.cacheEmbeddings)return;let r=M.generateKey("embedding",t,e);return this.embeddingCache.get(r)}setEmbedding(t,e,r,o){if(!this.config.cacheEmbeddings)return;let n=M.generateKey("embedding",t,r);this.embeddingCache.set(n,e,o)}getCompletion(t,e){if(!this.config.cacheCompletions)return;let r=M.generateKey("completion",t,e);return this.completionCache.get(r)}setCompletion(t,e,r,o){if(!this.config.cacheCompletions)return;let n=M.generateKey("completion",t,r);this.completionCache.set(n,e,o)}getStats(){let t=this.generationCache.getStats(),e=this.embeddingCache.getStats(),r=this.completionCache.getStats(),o=t.hits+e.hits+r.hits,n=t.misses+e.misses+r.misses,s=o+n;return{generation:t,embedding:e,completion:r,total:{size:t.size+e.size+r.size,maxSize:this.config.maxSize*3,hits:o,misses:n,hitRate:s>0?o/s:0,evictions:t.evictions+e.evictions+r.evictions,memoryUsageBytes:t.memoryUsageBytes+e.memoryUsageBytes+r.memoryUsageBytes}}}clear(){this.generationCache.clear(),this.embeddingCache.clear(),this.completionCache.clear()}pruneExpired(){return this.generationCache.pruneExpired()+this.embeddingCache.pruneExpired()+this.completionCache.pruneExpired()}};var ie="(unattributed)",Ae=`
3
3
  CREATE TABLE IF NOT EXISTS llm_spend (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  ts INTEGER NOT NULL,
@@ -17,7 +17,7 @@ CREATE INDEX IF NOT EXISTS idx_llm_spend_ts ON llm_spend(ts);
17
17
  VALUES (@ts, @provider, @model, @cost_usd, @cost_source, @prompt_tokens, @completion_tokens, @request_id, @agent_type)`).run({ts:Date.now(),provider:t.provider,model:t.model,cost_usd:t.costUsd,cost_source:t.costSource,prompt_tokens:t.promptTokens,completion_tokens:t.completionTokens,request_id:t.requestId,agent_type:t.agent??null}):this.db.prepare(`INSERT INTO llm_spend
18
18
  (ts, provider, model, cost_usd, cost_source, prompt_tokens, completion_tokens, request_id)
19
19
  VALUES (@ts, @provider, @model, @cost_usd, @cost_source, @prompt_tokens, @completion_tokens, @request_id)`).run({ts:Date.now(),provider:t.provider,model:t.model,cost_usd:t.costUsd,cost_source:t.costSource,prompt_tokens:t.promptTokens,completion_tokens:t.completionTokens,request_id:t.requestId})}catch{}}spentSince(t,e=Date.now()){try{return this.db.prepare("SELECT COALESCE(SUM(cost_usd), 0) AS total FROM llm_spend WHERE ts >= ?").get(e-t)?.total??0}catch{return 0}}spentByAgentSince(t,e=Date.now()){try{let r=this.db.prepare(`SELECT COALESCE(agent_type, ?) AS agent, COALESCE(SUM(cost_usd), 0) AS total
20
- FROM llm_spend WHERE ts >= ? GROUP BY COALESCE(agent_type, ?)`).all(ie,e-t,ie),o={};for(let n of r)o[n.agent]=n.total;return o}catch{return{}}}},N=class{entries=[];record(t){this.entries.push({ts:Date.now(),costUsd:t.costUsd,agent:t.agent??ie})}spentSince(t,e=Date.now()){let r=e-t,o=0;for(let n of this.entries)n.ts>=r&&(o+=n.costUsd);return o}spentByAgentSince(t,e=Date.now()){let r=e-t,o={};for(let n of this.entries)n.ts>=r&&(o[n.agent]=(o[n.agent]??0)+n.costUsd);return o}};async function ve(){try{let t=(await import("./unified-memory-WNYWTGVX.js")).getUnifiedMemory();return t.isInitialized()||await t.initialize(),new ae(t.getDatabase())}catch{return new N}}L();function ce(g,t,e,r){let o=Math.min(t*Math.pow(2,g),e),n=Math.random()*r*o;return o+n}var Le=1e3,Pe=3e4;function T(g,t=Le,e=Pe){return ce(g,t,e,0)}import{readFileSync as Oe}from"fs";import*as Te from"path";var le=["low","medium","high","xhigh","max"],Ie="xhigh";function G(g){return typeof g=="string"&&le.includes(g)}var $;function Se(g){try{let e=Oe(g,"utf8").match(/^\s*effort_level\s*:\s*['"]?([a-z]+)['"]?\s*$/m);return e&&G(e[1])?e[1]:null}catch{return null}}function ke(g={}){if(g.override&&G(g.override))return g.override;if(g.agentEffort&&G(g.agentEffort))return g.agentEffort;let e=(g.env??process.env).QE_EFFORT_LEVEL;if(e&&G(e))return e;let r=g.fleetDefaultsPath??Te.join(process.cwd(),"config","fleet-defaults.yaml");return $===void 0&&($=Se(r)),$||Ie}function Ee(g,t){let e=le.indexOf(g),r=le.indexOf(t);return e>r?t:g}var xe={model:"claude-sonnet-4-6",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,anthropicVersion:"2023-06-01",enableCache:!0,enableCircuitBreaker:!0},F=class{type="claude";name="Anthropic Claude";config;requestId=0;constructor(t={}){this.config={...xe,...t}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getApiKey())return{healthy:!1,error:"API key not configured. Set ANTHROPIC_API_KEY environment variable."};let e=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:this.config.model,max_tokens:1,messages:[{role:"user",content:"Hi"}]})},5e3),o=Date.now()-e;if(!r.ok){let n=await r.text();return{healthy:!1,latencyMs:o,error:`API error: ${r.status} - ${n}`}}return{healthy:!0,latencyMs:o,models:this.getSupportedModels(),details:{apiVersion:this.config.anthropicVersion,defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){if(!this.getApiKey())throw a("Anthropic API key not configured","API_KEY_MISSING",{provider:"claude",retryable:!1});let o=this.formatMessages(t),n=e?.model??this.config.model,s=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`claude-${++this.requestId}-${Date.now()}`,p=Date.now(),m={model:n,max_tokens:s,temperature:i,messages:o};e?.systemPrompt&&(m.system=this.config.enableCache!==!1?[{type:"text",text:e.systemPrompt,cache_control:{type:"ephemeral"}}]:e.systemPrompt),e?.stopSequences&&e.stopSequences.length>0&&(m.stop_sequences=e.stopSequences);try{if(fe(n).supportsEffortXHigh){let u=ke({override:e?.effort}),d=Ee(u,"xhigh");m.thinking={type:"adaptive",effort:d}}}catch{}try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(m)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),u=Date.now()-p;if(!c.ok){let k=await c.json().catch(()=>({error:{message:"Unknown error"}}));throw this.handleApiError(c.status,k,n)}let d=await c.json(),h=d.usage.cache_creation_input_tokens??0,f=d.usage.cache_read_input_tokens??0,b={promptTokens:d.usage.input_tokens,completionTokens:d.usage.output_tokens,totalTokens:d.usage.input_tokens+h+f+d.usage.output_tokens,cacheCreationTokens:h,cacheReadTokens:f},y=R.calculateCost(n,b);return v.recordTokenUsage(l,"claude-provider","llm","generate",{inputTokens:d.usage.input_tokens,outputTokens:d.usage.output_tokens,totalTokens:d.usage.input_tokens+d.usage.output_tokens,estimatedCostUsd:y.totalCost}),{content:d.content.filter(k=>k.type==="text").map(k=>k.text).join(""),model:d.model,provider:"claude",usage:b,cost:y,latencyMs:u,finishReason:this.mapFinishReason(d.stop_reason),cached:!1,requestId:l}}catch(c){throw c instanceof Error&&"code"in c?c:a(c instanceof Error?c.message:"Request failed","NETWORK_ERROR",{provider:"claude",model:n,retryable:!0,cause:c})}}async embed(t,e){throw a("Claude does not support native embeddings. Use OpenAI or Ollama for embeddings.","MODEL_NOT_FOUND",{provider:"claude",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
20
+ FROM llm_spend WHERE ts >= ? GROUP BY COALESCE(agent_type, ?)`).all(ie,e-t,ie),o={};for(let n of r)o[n.agent]=n.total;return o}catch{return{}}}},N=class{entries=[];record(t){this.entries.push({ts:Date.now(),costUsd:t.costUsd,agent:t.agent??ie})}spentSince(t,e=Date.now()){let r=e-t,o=0;for(let n of this.entries)n.ts>=r&&(o+=n.costUsd);return o}spentByAgentSince(t,e=Date.now()){let r=e-t,o={};for(let n of this.entries)n.ts>=r&&(o[n.agent]=(o[n.agent]??0)+n.costUsd);return o}};async function ve(){try{let t=(await import("./unified-memory-BEUZQTTC.js")).getUnifiedMemory();return t.isInitialized()||await t.initialize(),new ae(t.getDatabase())}catch{return new N}}L();function ce(g,t,e,r){let o=Math.min(t*Math.pow(2,g),e),n=Math.random()*r*o;return o+n}var Le=1e3,Pe=3e4;function T(g,t=Le,e=Pe){return ce(g,t,e,0)}import{readFileSync as Oe}from"fs";import*as Te from"path";var le=["low","medium","high","xhigh","max"],Ie="xhigh";function G(g){return typeof g=="string"&&le.includes(g)}var $;function Se(g){try{let e=Oe(g,"utf8").match(/^\s*effort_level\s*:\s*['"]?([a-z]+)['"]?\s*$/m);return e&&G(e[1])?e[1]:null}catch{return null}}function ke(g={}){if(g.override&&G(g.override))return g.override;if(g.agentEffort&&G(g.agentEffort))return g.agentEffort;let e=(g.env??process.env).QE_EFFORT_LEVEL;if(e&&G(e))return e;let r=g.fleetDefaultsPath??Te.join(process.cwd(),"config","fleet-defaults.yaml");return $===void 0&&($=Se(r)),$||Ie}function Ee(g,t){let e=le.indexOf(g),r=le.indexOf(t);return e>r?t:g}var xe={model:"claude-sonnet-4-6",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,anthropicVersion:"2023-06-01",enableCache:!0,enableCircuitBreaker:!0},F=class{type="claude";name="Anthropic Claude";config;requestId=0;constructor(t={}){this.config={...xe,...t}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getApiKey())return{healthy:!1,error:"API key not configured. Set ANTHROPIC_API_KEY environment variable."};let e=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:this.config.model,max_tokens:1,messages:[{role:"user",content:"Hi"}]})},5e3),o=Date.now()-e;if(!r.ok){let n=await r.text();return{healthy:!1,latencyMs:o,error:`API error: ${r.status} - ${n}`}}return{healthy:!0,latencyMs:o,models:this.getSupportedModels(),details:{apiVersion:this.config.anthropicVersion,defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){if(!this.getApiKey())throw a("Anthropic API key not configured","API_KEY_MISSING",{provider:"claude",retryable:!1});let o=this.formatMessages(t),n=e?.model??this.config.model,s=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`claude-${++this.requestId}-${Date.now()}`,p=Date.now(),m={model:n,max_tokens:s,temperature:i,messages:o};e?.systemPrompt&&(m.system=this.config.enableCache!==!1?[{type:"text",text:e.systemPrompt,cache_control:{type:"ephemeral"}}]:e.systemPrompt),e?.stopSequences&&e.stopSequences.length>0&&(m.stop_sequences=e.stopSequences);try{if(fe(n).supportsEffortXHigh){let u=ke({override:e?.effort}),d=Ee(u,"xhigh");m.thinking={type:"adaptive",effort:d}}}catch{}try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(m)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),u=Date.now()-p;if(!c.ok){let k=await c.json().catch(()=>({error:{message:"Unknown error"}}));throw this.handleApiError(c.status,k,n)}let d=await c.json(),h=d.usage.cache_creation_input_tokens??0,f=d.usage.cache_read_input_tokens??0,b={promptTokens:d.usage.input_tokens,completionTokens:d.usage.output_tokens,totalTokens:d.usage.input_tokens+h+f+d.usage.output_tokens,cacheCreationTokens:h,cacheReadTokens:f},y=R.calculateCost(n,b);return v.recordTokenUsage(l,"claude-provider","llm","generate",{inputTokens:d.usage.input_tokens,outputTokens:d.usage.output_tokens,totalTokens:d.usage.input_tokens+d.usage.output_tokens,estimatedCostUsd:y.totalCost}),{content:d.content.filter(k=>k.type==="text").map(k=>k.text).join(""),model:d.model,provider:"claude",usage:b,cost:y,latencyMs:u,finishReason:this.mapFinishReason(d.stop_reason),cached:!1,requestId:l}}catch(c){throw c instanceof Error&&"code"in c?c:a(c instanceof Error?c.message:"Request failed","NETWORK_ERROR",{provider:"claude",model:n,retryable:!0,cause:c})}}async embed(t,e){throw a("Claude does not support native embeddings. Use OpenAI or Ollama for embeddings.","MODEL_NOT_FOUND",{provider:"claude",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
21
21
 
22
22
  `,"```"]});return{completion:r.content,model:r.model,provider:"claude",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return["claude-opus-4-7","claude-sonnet-4-6","claude-haiku-4-5-20251001","claude-3-opus-20240229","claude-3-sonnet-20240229","claude-3-haiku-20240307"]}getCostPerToken(){return R.getCostPerToken(this.config.model)}async dispose(){}getApiKey(){return this.config.apiKey??process.env.ANTHROPIC_API_KEY}getBaseUrl(){return(this.config.baseUrl??process.env.ANTHROPIC_BASE_URL??"https://api.anthropic.com").replace(/\/$/,"")}getHeaders(){return{"Content-Type":"application/json","x-api-key":this.getApiKey(),"anthropic-version":this.config.anthropicVersion??"2023-06-01"}}formatMessages(t){return typeof t=="string"?[{role:"user",content:t}]:t.filter(e=>e.role!=="system").map(e=>({role:e.role,content:e.content}))}mapFinishReason(t){switch(t){case"end_turn":return"stop";case"max_tokens":return"length";case"stop_sequence":return"stop";default:return"stop"}}handleApiError(t,e,r){let o="error"in e?e.error?.message??"Unknown API error":"Unknown API error",n="error"in e&&"type"in e.error?e.error.type:"";switch(t){case 401:throw a(o,"API_KEY_INVALID",{provider:"claude",model:r,retryable:!1});case 429:throw a(o,"RATE_LIMITED",{provider:"claude",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw n==="invalid_request_error"&&o.includes("context")?a(o,"CONTEXT_LENGTH_EXCEEDED",{provider:"claude",model:r,retryable:!1}):a(o,"UNKNOWN",{provider:"claude",model:r,retryable:!1});case 500:case 502:case 503:throw a(o,"PROVIDER_UNAVAILABLE",{provider:"claude",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(o,"UNKNOWN",{provider:"claude",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){let o=new AbortController,n=setTimeout(()=>o.abort(),r);try{return await fetch(t,{...e,signal:o.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"claude",retryable:!0}):s}finally{clearTimeout(n)}}async fetchWithRetry(t,e,r,o){let n;for(let s=0;s<o;s++)try{let i=await this.fetchWithTimeout(t,e,r);if(i.status>=400&&i.status<500&&i.status!==429)return i;if((i.status>=500||i.status===429)&&s<o-1){let l=T(s);await this.sleep(l);continue}return i}catch(i){if(n=E(i),s<o-1){let l=T(s);await this.sleep(l)}}throw n??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};import{spawn as Ue}from"node:child_process";var Ne=["ANTHROPIC_API_KEY","CLAUDE_API_KEY","ANTHROPIC_AUTH_TOKEN"],De={model:"sonnet",maxTokens:4096,temperature:.7,timeoutMs:12e4,maxRetries:1,binaryPath:"claude",maxConcurrency:2,disallowedTools:["Bash","Edit","Write","NotebookEdit","WebFetch","WebSearch","Task"]},W=class g{type="claude-code";name="Claude Code (subscription)";billingMode="subscription";config;requestId=0;availabilityCache;active=0;queue=[];constructor(t={}){this.config={...De,...t};let e=Number.parseInt(process.env.AQE_CLAUDE_CODE_CONCURRENCY??"",10);Number.isFinite(e)&&e>0&&(this.config.maxConcurrency=e)}async isAvailable(){let t=Date.now();if(this.availabilityCache&&t-this.availabilityCache.at<6e4)return this.availabilityCache.available;let e=!1;try{let{code:r}=await this.runProcess(["--version"],void 0,5e3);e=r===0}catch{e=!1}return this.availabilityCache={at:t,available:e},e}async healthCheck(){let t=Date.now(),e=await this.isAvailable(),r=Date.now()-t;return e?{healthy:!0,latencyMs:r,models:this.getSupportedModels(),details:{binaryPath:this.config.binaryPath,billing:"subscription"}}:{healthy:!1,latencyMs:r,error:`Claude Code CLI ("${this.config.binaryPath}") not found or not runnable. Install Claude Code and log in with your Pro/Max account.`}}async generate(t,e){let r=this.toCliModel(e?.model??this.config.model),o=`claude-code-${++this.requestId}-${Date.now()}`,{prompt:n,systemPrompt:s}=this.flatten(t,e?.systemPrompt),i=["-p","--output-format","json","--model",r];s&&i.push("--append-system-prompt",s);let l=this.config.disallowedTools??[];l.length>0&&i.push("--disallowedTools",...l);let p=Date.now(),m=e?.timeoutMs??this.config.timeoutMs??12e4,{code:c,stdout:u,stderr:d}=await this.withConcurrency(()=>this.runProcess(i,n,m)),h=Date.now()-p;if(c!==0&&!u.trim())throw this.classifyError(d||`claude exited with code ${c}`,r);let f;try{f=JSON.parse(u)}catch{throw a(`Could not parse claude -p JSON output: ${u.slice(0,200)}`,"PROVIDER_UNAVAILABLE",{provider:"claude-code",model:r,retryable:!0})}if(f.is_error)throw this.classifyError(f.result??f.api_error_status??"claude error",r);let b=f.usage??{},y={promptTokens:b.input_tokens??0,completionTokens:b.output_tokens??0,totalTokens:(b.input_tokens??0)+(b.output_tokens??0),cacheCreationTokens:b.cache_creation_input_tokens??0,cacheReadTokens:b.cache_read_input_tokens??0},C=f.modelUsage&&Object.keys(f.modelUsage)[0]||r;return v.recordTokenUsage(o,"claude-code-provider","llm","generate",{inputTokens:y.promptTokens,outputTokens:y.completionTokens,totalTokens:y.totalTokens,estimatedCostUsd:0}),{content:f.result??"",model:C,provider:"claude-code",usage:y,cost:{inputCost:0,outputCost:0,totalCost:0,currency:"USD",source:"provider-receipt"},latencyMs:h,finishReason:this.mapFinishReason(f.stop_reason),cached:!1,requestId:o}}async embed(t,e){throw a("Claude Code provider does not support embeddings. Use openai, ollama, or cognitum.","MODEL_NOT_FOUND",{provider:"claude-code",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256});return{completion:r.content,model:r.model,provider:"claude-code",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return["opus","sonnet","haiku"]}getCostPerToken(){return{input:0,output:0}}async dispose(){}toCliModel(t){let e=t.toLowerCase();return e.includes("opus")?"opus":e.includes("haiku")?"haiku":e.includes("sonnet")?"sonnet":t}flatten(t,e){if(typeof t=="string")return{prompt:t,systemPrompt:e};let r=t.filter(n=>n.role==="system").map(n=>n.content);return e&&r.unshift(e),{prompt:t.filter(n=>n.role!=="system").map(n=>`${n.role==="assistant"?"Assistant":"User"}: ${n.content}`).join(`
23
23
 
@@ -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.13.0");process.exit(0)}
2
- import{i as c}from"./chunk-VLNPJAVH.js";import{a as p}from"./chunk-HVB2L52I.js";import{c as m}from"./chunk-OXXMVQDF.js";import{b as g,d as E}from"./chunk-2DIT5AUU.js";import{a as l,b as _}from"./chunk-SNTUKW4Q.js";_();import b from"node:path";import{existsSync as h}from"node:fs";E();p();var T=m.create("metrics-tracker"),d=class{db=null;dbPath;initialized=!1;constructor(e=process.cwd()){this.dbPath=b.join(e,".agentic-qe","memory.db")}async initialize(){if(!this.initialized){if(!h(this.dbPath))throw new Error(`Database not found: ${this.dbPath}. Run "aqe init --auto" first.`);this.db=l(this.dbPath),this.ensureMetricsTable(),this.initialized=!0}}ensureMetricsTable(){this.db&&this.db.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.2");process.exit(0)}
2
+ import{i as c}from"./chunk-FJ2L6P7O.js";import{a as p}from"./chunk-6UGYFYS4.js";import{c as m}from"./chunk-BSQ32ZS5.js";import{b as g,d as E}from"./chunk-FMYNKZ2S.js";import{a as l,b as _}from"./chunk-6DMB6WK5.js";_();import b from"node:path";import{existsSync as h}from"node:fs";E();p();var T=m.create("metrics-tracker"),d=class{db=null;dbPath;initialized=!1;constructor(e=process.cwd()){this.dbPath=b.join(e,".agentic-qe","memory.db")}async initialize(){if(!this.initialized){if(!h(this.dbPath))throw new Error(`Database not found: ${this.dbPath}. Run "aqe init --auto" first.`);this.db=l(this.dbPath),this.ensureMetricsTable(),this.initialized=!0}}ensureMetricsTable(){this.db&&this.db.exec(`
3
3
  CREATE TABLE IF NOT EXISTS learning_daily_snapshots (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  snapshot_date TEXT NOT NULL UNIQUE,
@@ -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.13.0");process.exit(0)}
2
- import{c as t}from"./chunk-ES7WCYOU.js";function o(e){try{return e.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.2");process.exit(0)}
2
+ import{c as t}from"./chunk-AJ7A52GF.js";function o(e){try{return e.prepare(`
3
3
  SELECT COUNT(*) as count FROM sqlite_master
4
4
  WHERE type='table' AND name IN ('hypergraph_nodes', 'hypergraph_edges')
5
5
  `).get().count===2}catch{return!1}}var r,a,E,n,p=t(()=>{"use strict";r=`
@@ -1,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.13.0");process.exit(0)}
2
- import{c as r}from"./chunk-ES7WCYOU.js";function o(n){return n instanceof Error?n.message:String(n)}function e(n){return n instanceof Error?n:new Error(String(n))}var t=r(()=>{"use strict"});export{o as a,e as b,t as c};
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.13.2");process.exit(0)}
2
+ import{c as r}from"./chunk-AJ7A52GF.js";function o(n){return n instanceof Error?n.message:String(n)}function e(n){return n instanceof Error?n:new Error(String(n))}var t=r(()=>{"use strict"});export{o as a,e as b,t as c};