agentic-qe 3.15.0 → 3.15.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 (359) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +87 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/cli/bundle.js +5 -5
  5. package/dist/cli/chunks/adapter-EUIELRLI.js +2 -0
  6. package/dist/cli/chunks/{agent-booster-wasm-GDHJ6QUN.js → agent-booster-wasm-664M7426.js} +2 -2
  7. package/dist/cli/chunks/{agent-handler-MPYYQ2RZ.js → agent-handler-E47ITH45.js} +2 -2
  8. package/dist/cli/chunks/{agent-memory-branch-QBSHKLA2.js → agent-memory-branch-CFWVOJX3.js} +2 -2
  9. package/dist/cli/chunks/aqe-learning-engine-LXRKHASR.js +2 -0
  10. package/dist/cli/chunks/{arena-UJE2FROF.js → arena-JM3OY263.js} +4 -4
  11. package/dist/cli/chunks/{arena-WIGSL37B.js → arena-ZU5CGBGH.js} +2 -2
  12. package/dist/cli/chunks/{audit-VT7Y2Z7V.js → audit-HVBRC5AS.js} +3 -3
  13. package/dist/cli/chunks/base-4DSLX33Y.js +2 -0
  14. package/dist/cli/chunks/{better-sqlite3-DSL7LFRK.js → better-sqlite3-45JLBQX3.js} +2 -2
  15. package/dist/cli/chunks/{brain-handler-N3C2MDMK.js → brain-handler-FKDONZYA.js} +3 -3
  16. package/dist/cli/chunks/{branch-enumerator-B6NSQ3PZ.js → branch-enumerator-M3DPS3D5.js} +2 -2
  17. package/dist/cli/chunks/{browser-KQ3YNRGW.js → browser-TG2TV6NR.js} +2 -2
  18. package/dist/cli/chunks/browser-workflow-AWCQLQZK.js +2 -0
  19. package/dist/cli/chunks/{chunk-DXA7RLYU.js → chunk-2AOAEMJG.js} +2 -2
  20. package/dist/cli/chunks/{chunk-BH2SQQ2N.js → chunk-2AWU2E6R.js} +1 -1
  21. package/dist/cli/chunks/{chunk-DZHIE5UW.js → chunk-2B2MGJ2W.js} +2 -2
  22. package/dist/cli/chunks/{chunk-ISAMM7QA.js → chunk-2JEPRQMT.js} +1 -1
  23. package/dist/cli/chunks/{chunk-7WUHVGGT.js → chunk-2Q4Y3VQ6.js} +2 -2
  24. package/dist/cli/chunks/{chunk-2ZEV3O24.js → chunk-326V7N25.js} +1 -1
  25. package/dist/cli/chunks/{chunk-URUOTHPO.js → chunk-3DCRAW43.js} +2 -2
  26. package/dist/cli/chunks/{chunk-X5RELRY7.js → chunk-3KTAMNKI.js} +2 -2
  27. package/dist/cli/chunks/{chunk-XZDPR6I2.js → chunk-3KXKJSKS.js} +2 -2
  28. package/dist/cli/chunks/{chunk-GV7P5JYF.js → chunk-3RC5UMRJ.js} +2 -2
  29. package/dist/cli/chunks/{chunk-7JC3LHA6.js → chunk-3XF7YTQC.js} +48 -48
  30. package/dist/cli/chunks/{chunk-FCSETOWZ.js → chunk-4MCO43NX.js} +1 -1
  31. package/dist/cli/chunks/{chunk-AW5OWYQ4.js → chunk-55T7PDYP.js} +2 -2
  32. package/dist/cli/chunks/{chunk-MRIZY6HB.js → chunk-56CE7UO4.js} +2 -2
  33. package/dist/cli/chunks/{chunk-P725KXHX.js → chunk-5DFPAJ5O.js} +2 -2
  34. package/dist/cli/chunks/{chunk-OBSX3I4Y.js → chunk-5TEPPW4J.js} +2 -2
  35. package/dist/cli/chunks/{chunk-A37YYHUD.js → chunk-5YS2DF5G.js} +2 -2
  36. package/dist/cli/chunks/chunk-6KEYA4EH.js +316 -0
  37. package/dist/cli/chunks/{chunk-5DJGP4TA.js → chunk-6O4KVU4K.js} +2 -2
  38. package/dist/cli/chunks/{chunk-EBK6CUBD.js → chunk-6OL2WES5.js} +1 -1
  39. package/dist/cli/chunks/{chunk-R6CZCMKD.js → chunk-6UO5YSNN.js} +2 -2
  40. package/dist/cli/chunks/{chunk-WPSGMTI4.js → chunk-6WVEICL2.js} +3 -3
  41. package/dist/cli/chunks/{chunk-XEABMIUH.js → chunk-6XLCFDIB.js} +2 -2
  42. package/dist/cli/chunks/{chunk-P4FRYNHL.js → chunk-7UA7SMM4.js} +1 -1
  43. package/dist/cli/chunks/{chunk-YFRZVNE4.js → chunk-A6L2OCMO.js} +2 -2
  44. package/dist/cli/chunks/{chunk-J4XCBOPA.js → chunk-ANI3KPB7.js} +2 -2
  45. package/dist/cli/chunks/{chunk-FZ3TQAPW.js → chunk-AR5V7VNC.js} +1 -1
  46. package/dist/cli/chunks/{chunk-FFE4XAQA.js → chunk-AS27JP67.js} +1 -1
  47. package/dist/cli/chunks/{chunk-FPTZP7W5.js → chunk-ATGIGJSL.js} +1 -1
  48. package/dist/cli/chunks/{chunk-2ORTL5WG.js → chunk-AXJ75X6I.js} +1 -1
  49. package/dist/cli/chunks/{chunk-OLD2CIDI.js → chunk-B4H66LPR.js} +1 -1
  50. package/dist/cli/chunks/{chunk-I3BH3KIF.js → chunk-BKZSTZDB.js} +1 -1
  51. package/dist/cli/chunks/{chunk-AQZSF32Y.js → chunk-BT6TZTCL.js} +2 -2
  52. package/dist/cli/chunks/{chunk-H77AUJNW.js → chunk-CFDIYZGA.js} +2 -2
  53. package/dist/cli/chunks/{chunk-PN3FYSQ6.js → chunk-CRYZXTSQ.js} +2 -2
  54. package/dist/cli/chunks/{chunk-OYVDTD3A.js → chunk-CV7E627D.js} +2 -2
  55. package/dist/cli/chunks/{chunk-GX5RFGW2.js → chunk-D75HDHX3.js} +1 -1
  56. package/dist/cli/chunks/{chunk-4DCDIKBX.js → chunk-DGKPGRBT.js} +2 -2
  57. package/dist/cli/chunks/{chunk-KUTMQBV4.js → chunk-DHSGCI6H.js} +4 -4
  58. package/dist/cli/chunks/{chunk-CZWWC7GC.js → chunk-DNS37AHW.js} +1 -1
  59. package/dist/cli/chunks/{chunk-F7JVDLOI.js → chunk-E2QHUMCR.js} +2 -2
  60. package/dist/cli/chunks/{chunk-FTFIA4I5.js → chunk-E6GANSLP.js} +2 -2
  61. package/dist/cli/chunks/{chunk-62IEVKN3.js → chunk-EATZW5T2.js} +2 -2
  62. package/dist/cli/chunks/{chunk-LLS6JYPN.js → chunk-EDRIROCG.js} +2 -2
  63. package/dist/cli/chunks/{chunk-S2GNFAOC.js → chunk-EQG3JYSV.js} +2 -2
  64. package/dist/cli/chunks/{chunk-XPUY3ZKD.js → chunk-FCMCQ6OX.js} +9 -9
  65. package/dist/cli/chunks/{chunk-UGYXUPGN.js → chunk-FH6N2LKG.js} +2 -2
  66. package/dist/cli/chunks/{chunk-6GTIJNRO.js → chunk-FNPZINHV.js} +1 -1
  67. package/dist/cli/chunks/{chunk-4FOKHGP5.js → chunk-FRZVLRVR.js} +2 -2
  68. package/dist/cli/chunks/{chunk-5PNRUMRV.js → chunk-GDSLQTJC.js} +2 -2
  69. package/dist/cli/chunks/{chunk-NZ556KZN.js → chunk-GHXNRF63.js} +2 -2
  70. package/dist/cli/chunks/{chunk-N5ZHIQAV.js → chunk-GJ7DON5S.js} +3 -3
  71. package/dist/cli/chunks/{chunk-3Y24VTZ3.js → chunk-GJTH6VBH.js} +1 -1
  72. package/dist/cli/chunks/{chunk-ZXIIB3QE.js → chunk-GSC6JXDE.js} +1 -1
  73. package/dist/cli/chunks/{chunk-4EEY23JS.js → chunk-HADOG2PT.js} +2 -2
  74. package/dist/cli/chunks/{chunk-PJU5HVWV.js → chunk-HBMBO4FD.js} +2 -2
  75. package/dist/cli/chunks/{chunk-VYERAOQL.js → chunk-HFF5ERIE.js} +2 -2
  76. package/dist/cli/chunks/{chunk-GRN47ANK.js → chunk-HMDSBWF6.js} +2 -2
  77. package/dist/cli/chunks/{chunk-LDJ5DZT5.js → chunk-HOBBYORR.js} +1 -1
  78. package/dist/cli/chunks/{chunk-EQ4SDE4L.js → chunk-HS3O763N.js} +3 -3
  79. package/dist/cli/chunks/{chunk-YIDZ3TEN.js → chunk-HSXLHNSS.js} +2 -2
  80. package/dist/cli/chunks/{chunk-4YPL3OXS.js → chunk-HXT4XDQO.js} +2 -2
  81. package/dist/cli/chunks/{chunk-S7CROKX4.js → chunk-HYWW4A2E.js} +2 -2
  82. package/dist/cli/chunks/chunk-I7ECEOFV.js +2 -0
  83. package/dist/cli/chunks/{chunk-FTS6NGBP.js → chunk-I7J2ESGR.js} +2 -2
  84. package/dist/cli/chunks/{chunk-JYRBOSOF.js → chunk-IAOB2G3X.js} +2 -2
  85. package/dist/cli/chunks/{chunk-MEYSIVMP.js → chunk-IBAXNCR2.js} +2 -2
  86. package/dist/cli/chunks/{chunk-JLPNYHJJ.js → chunk-IHKRKRAV.js} +1 -1
  87. package/dist/cli/chunks/{chunk-JJ7WAU4I.js → chunk-IM67YHDK.js} +2 -2
  88. package/dist/cli/chunks/{chunk-DSGRXW6K.js → chunk-IQB5ZBYO.js} +3 -3
  89. package/dist/cli/chunks/{chunk-WR54SKKL.js → chunk-IT753IPZ.js} +2 -2
  90. package/dist/cli/chunks/{chunk-WBR4VRQE.js → chunk-ITM26I6O.js} +2 -2
  91. package/dist/cli/chunks/{chunk-VT5SMBEM.js → chunk-J4EJMAH3.js} +1 -1
  92. package/dist/cli/chunks/{chunk-7JABIXP3.js → chunk-JCB6K24D.js} +2 -2
  93. package/dist/cli/chunks/{chunk-VWCFXCSV.js → chunk-JFFVYCTV.js} +2 -2
  94. package/dist/cli/chunks/{chunk-OTJ22IO2.js → chunk-JIRX6KUR.js} +3 -3
  95. package/dist/cli/chunks/{chunk-X7JEBPEW.js → chunk-JSTKSPYT.js} +1 -1
  96. package/dist/cli/chunks/{chunk-N2MDNEF7.js → chunk-KQMCCHPO.js} +2 -2
  97. package/dist/cli/chunks/{chunk-Z6CRROLU.js → chunk-KTLYL3BS.js} +2 -2
  98. package/dist/cli/chunks/{chunk-QVX22EIM.js → chunk-L77Z3Q6L.js} +2 -2
  99. package/dist/cli/chunks/{chunk-O5AUOBGU.js → chunk-LH3H4V7C.js} +2 -2
  100. package/dist/cli/chunks/{chunk-VQVFGFYK.js → chunk-LRVR56PD.js} +1 -1
  101. package/dist/cli/chunks/{chunk-6MN4L6BS.js → chunk-LVDZ25VX.js} +2 -2
  102. package/dist/cli/chunks/{chunk-7D6NVIGP.js → chunk-LW4BCFIV.js} +2 -2
  103. package/dist/cli/chunks/{chunk-GCHDMO5V.js → chunk-M36DAETL.js} +2 -2
  104. package/dist/cli/chunks/{chunk-P2PPJUGD.js → chunk-MDDECCAC.js} +10 -10
  105. package/dist/cli/chunks/{chunk-C6M27NQE.js → chunk-MEUJWTOX.js} +2 -2
  106. package/dist/cli/chunks/{chunk-DGRE6ZAA.js → chunk-MOSXT6AO.js} +2 -2
  107. package/dist/cli/chunks/{chunk-4BWDCUZZ.js → chunk-MY2XZHW3.js} +1 -1
  108. package/dist/cli/chunks/{chunk-QRALXNNX.js → chunk-MYDZBABD.js} +2 -2
  109. package/dist/cli/chunks/{chunk-F76SYOBT.js → chunk-N4MNSEKY.js} +1 -1
  110. package/dist/cli/chunks/{chunk-CMYZWIXS.js → chunk-N653RGT3.js} +2 -2
  111. package/dist/cli/chunks/{chunk-ZPH2YT3J.js → chunk-NBV37CEK.js} +2 -2
  112. package/dist/cli/chunks/{chunk-XELFJC77.js → chunk-NKWMTXBL.js} +3 -3
  113. package/dist/cli/chunks/{chunk-VTGRGYY4.js → chunk-NL6HKEPR.js} +3 -3
  114. package/dist/cli/chunks/{chunk-P7MNF2SK.js → chunk-NLY5NUHZ.js} +2 -2
  115. package/dist/cli/chunks/{chunk-J46XGXPS.js → chunk-NP2WWIZ3.js} +1 -1
  116. package/dist/cli/chunks/{chunk-ISGFAMHZ.js → chunk-NWYAV2UG.js} +2 -2
  117. package/dist/cli/chunks/{chunk-HBIV7PQH.js → chunk-O6QTCUSL.js} +1 -1
  118. package/dist/cli/chunks/{chunk-IRHBR56R.js → chunk-OWZ3F7DJ.js} +1 -1
  119. package/dist/cli/chunks/{chunk-WDV6CBED.js → chunk-PZK7O445.js} +2 -2
  120. package/dist/cli/chunks/{chunk-W6H2SOIK.js → chunk-Q32UGPWK.js} +2 -2
  121. package/dist/cli/chunks/{chunk-KLGFEHEN.js → chunk-QB7H62A4.js} +2 -2
  122. package/dist/cli/chunks/{chunk-JO2YLIZH.js → chunk-QGCFMACF.js} +2 -2
  123. package/dist/cli/chunks/{chunk-WO7NPGUD.js → chunk-QJGKL67W.js} +3 -3
  124. package/dist/cli/chunks/{chunk-D7NOHASX.js → chunk-QJN5RW2U.js} +3 -3
  125. package/dist/cli/chunks/{chunk-JIWMFLHV.js → chunk-QR5ILM34.js} +2 -2
  126. package/dist/cli/chunks/{chunk-ILKMNDUM.js → chunk-QZNFZ5IQ.js} +2 -2
  127. package/dist/cli/chunks/{chunk-L6PUBB6L.js → chunk-RIAKRZCZ.js} +2 -2
  128. package/dist/cli/chunks/{chunk-ROK5YQ5P.js → chunk-RLQ4MYB6.js} +2 -2
  129. package/dist/cli/chunks/{chunk-M5EKZA7Q.js → chunk-RO6HAZLV.js} +1 -1
  130. package/dist/cli/chunks/{chunk-ANUZGOLQ.js → chunk-SKQTRYE7.js} +2 -2
  131. package/dist/cli/chunks/{chunk-S7QUHLXV.js → chunk-SVHFSOGT.js} +1 -1
  132. package/dist/cli/chunks/{chunk-32YSI6OT.js → chunk-SZYK5JL7.js} +1 -1
  133. package/dist/cli/chunks/{chunk-LPCFIFZF.js → chunk-T5N2PIPS.js} +2 -2
  134. package/dist/cli/chunks/{chunk-P4WE6VRR.js → chunk-T75PWWK4.js} +2 -2
  135. package/dist/cli/chunks/{chunk-BAPMEDWC.js → chunk-TC4B5D4Z.js} +1 -1
  136. package/dist/cli/chunks/{chunk-S644OORE.js → chunk-TMYGGYRY.js} +1 -1
  137. package/dist/cli/chunks/{chunk-AAQNRZKT.js → chunk-TZH2QAFZ.js} +2 -2
  138. package/dist/cli/chunks/{chunk-KU4WLKDK.js → chunk-UKRK3IE3.js} +2 -2
  139. package/dist/cli/chunks/{chunk-ATXAMGVE.js → chunk-URWT3EQT.js} +2 -2
  140. package/dist/cli/chunks/{chunk-Q4RCUCHD.js → chunk-UX4BOI6K.js} +1 -1
  141. package/dist/cli/chunks/{chunk-AV3RX2L5.js → chunk-UZL4JYVW.js} +2 -2
  142. package/dist/cli/chunks/{chunk-Y63DADOR.js → chunk-V67UQRQN.js} +2 -2
  143. package/dist/cli/chunks/{chunk-EZPWSS3B.js → chunk-VTGAPHJE.js} +2 -2
  144. package/dist/cli/chunks/{chunk-AGYPPPXR.js → chunk-W5EKSBS4.js} +2 -2
  145. package/dist/cli/chunks/{chunk-EPEKEUCF.js → chunk-W6PLBRRS.js} +1 -1
  146. package/dist/cli/chunks/{chunk-MM57SD2F.js → chunk-W7P7EOJ4.js} +1 -1
  147. package/dist/cli/chunks/{chunk-URRPJ3M7.js → chunk-WBCE6V2N.js} +1 -1
  148. package/dist/cli/chunks/{chunk-B6QTNTCU.js → chunk-WBZIOTY6.js} +2 -2
  149. package/dist/cli/chunks/{chunk-VCYOFWMG.js → chunk-WJ7657IX.js} +2 -2
  150. package/dist/cli/chunks/{chunk-5KN4QL3G.js → chunk-WMNVFCKY.js} +2 -2
  151. package/dist/cli/chunks/{chunk-JSYNSJDQ.js → chunk-WUSSZ2S6.js} +2 -2
  152. package/dist/cli/chunks/{chunk-4OQSAUKR.js → chunk-X43HA3RF.js} +2 -2
  153. package/dist/cli/chunks/{chunk-G35KP72N.js → chunk-X4CADOSD.js} +2 -2
  154. package/dist/cli/chunks/{chunk-WQMXQO3O.js → chunk-XQBH3366.js} +2 -2
  155. package/dist/cli/chunks/{chunk-KEZ4PXVF.js → chunk-Y5VPLOA7.js} +1 -1
  156. package/dist/cli/chunks/{chunk-5LN7FQZI.js → chunk-YH7VOLBP.js} +2 -2
  157. package/dist/cli/chunks/{chunk-MFGLRMO4.js → chunk-YJSKT6G6.js} +1 -1
  158. package/dist/cli/chunks/{chunk-X4OESN7M.js → chunk-YYVLMW65.js} +2 -2
  159. package/dist/cli/chunks/{chunk-PPFW3H7E.js → chunk-Z3K4JZXQ.js} +1 -1
  160. package/dist/cli/chunks/{chunk-MO3QXLF2.js → chunk-Z3PANQUT.js} +1 -1
  161. package/dist/cli/chunks/{chunk-VY4557VF.js → chunk-Z7XCXHEB.js} +2 -2
  162. package/dist/cli/chunks/{chunk-HOPXHZA3.js → chunk-ZIKH7U5A.js} +2 -2
  163. package/dist/cli/chunks/{chunk-WPOYFV4X.js → chunk-ZSKQPXRW.js} +1 -1
  164. package/dist/cli/chunks/{chunk-ZV7LJPSI.js → chunk-ZVQSIH7Y.js} +5 -5
  165. package/dist/cli/chunks/{ci-63JINRNB.js → ci-JNBOR6FP.js} +3 -3
  166. package/dist/cli/chunks/{ci-output-CRFWLUAA.js → ci-output-FYNKONEQ.js} +2 -2
  167. package/dist/cli/chunks/{circuit-breaker-PJLG3WYL.js → circuit-breaker-KOIXRDAD.js} +2 -2
  168. package/dist/cli/chunks/{claude-flow-setup-UKHSQMJU.js → claude-flow-setup-4CO7KHRN.js} +2 -2
  169. package/dist/cli/chunks/client-UJVHZXNQ.js +2 -0
  170. package/dist/cli/chunks/{cline-installer-PYQ27AS3.js → cline-installer-CMYAPKK5.js} +2 -2
  171. package/dist/cli/chunks/{code-K7VGLZ3W.js → code-WFIAEP3H.js} +3 -3
  172. package/dist/cli/chunks/{code-index-extractor-NNWAVWSL.js → code-index-extractor-IYM6HWJN.js} +2 -2
  173. package/dist/cli/chunks/{codex-installer-U4VJIKRN.js → codex-installer-DORVWRSU.js} +2 -2
  174. package/dist/cli/chunks/{completions-DOCI3P4W.js → completions-54VM2MX2.js} +2 -2
  175. package/dist/cli/chunks/{complexity-analyzer-RFW2QRFR.js → complexity-analyzer-EGZDP5N4.js} +2 -2
  176. package/dist/cli/chunks/{continuedev-installer-S5WXXOBU.js → continuedev-installer-4SDVDD4T.js} +2 -2
  177. package/dist/cli/chunks/{copilot-installer-AAQ6YLVJ.js → copilot-installer-7FJQ7PCL.js} +2 -2
  178. package/dist/cli/chunks/core-handlers-AFXZOSH3.js +2 -0
  179. package/dist/cli/chunks/{cost-tracker-R4VOHTWQ.js → cost-tracker-D6YSKTQC.js} +2 -2
  180. package/dist/cli/chunks/{coverage-P54HPCLV.js → coverage-DI5LDRJ7.js} +3 -3
  181. package/dist/cli/chunks/cross-domain-router-ZLNVKLIR.js +2 -0
  182. package/dist/cli/chunks/{cursor-installer-VHBWZE5A.js → cursor-installer-RTSZP5YD.js} +2 -2
  183. package/dist/cli/chunks/{daemon-JLH5TTWZ.js → daemon-LM7LETPV.js} +4 -4
  184. package/dist/cli/chunks/{daemon-BTRSWNB4.js → daemon-SP3APEZY.js} +3 -3
  185. package/dist/cli/chunks/{dag-attention-scheduler-5Z6DCRFK.js → dag-attention-scheduler-C3QBODFE.js} +2 -2
  186. package/dist/cli/chunks/{detect-NWGASRJJ.js → detect-I4RBUFFJ.js} +2 -2
  187. package/dist/cli/chunks/{dist-node-XMNNSEFJ.js → dist-node-PT6TCBCO.js} +2 -2
  188. package/dist/cli/chunks/{domain-handler-BWVBZTNR.js → domain-handler-MJMTMB5X.js} +2 -2
  189. package/dist/cli/chunks/{domain-plugins-YAD4USA4.js → domain-plugins-Y4A2WYJW.js} +2 -2
  190. package/dist/cli/chunks/{domain-transfer-Z3MRPZEZ.js → domain-transfer-DUO42TLA.js} +2 -2
  191. package/dist/cli/chunks/dream-4OPJXXEG.js +2 -0
  192. package/dist/cli/chunks/{embed-and-insert-pattern-5CCO45WC.js → embed-and-insert-pattern-66ZQK4AI.js} +2 -2
  193. package/dist/cli/chunks/{eval-JEMLTGY4.js → eval-NQ7H27UF.js} +2 -2
  194. package/dist/cli/chunks/{experience-capture-middleware-FKVYBBAN.js → experience-capture-middleware-MHEYPTIG.js} +3 -3
  195. package/dist/cli/chunks/{fast-paths-TFL32H3C.js → fast-paths-YYDGN6ZC.js} +2 -2
  196. package/dist/cli/chunks/{feature-flags-CNGAUUMT.js → feature-flags-FY4DOYS2.js} +2 -2
  197. package/dist/cli/chunks/{feature-flags-OHGD2NCW.js → feature-flags-YFGUORHY.js} +2 -2
  198. package/dist/cli/chunks/{file-discovery-IHGDYW34.js → file-discovery-TOMDY7TK.js} +2 -2
  199. package/dist/cli/chunks/{fleet-OGTSDGJ2.js → fleet-MO3UCWB4.js} +3 -3
  200. package/dist/cli/chunks/{gnn-wrapper-QYTTKNCE.js → gnn-wrapper-SLW4PPXQ.js} +2 -2
  201. package/dist/cli/chunks/{heartbeat-handler-R5OD2SKN.js → heartbeat-handler-36RFCP4E.js} +4 -4
  202. package/dist/cli/chunks/heartbeat-scheduler-J5KLHO6C.js +2 -0
  203. package/dist/cli/chunks/hnsw-adapter-56P6XSFR.js +2 -0
  204. package/dist/cli/chunks/hnsw-index-GFZ6XCEW.js +2 -0
  205. package/dist/cli/chunks/{hnsw-legacy-bridge-ULJWYXBQ.js → hnsw-legacy-bridge-BJLWBKHE.js} +2 -2
  206. package/dist/cli/chunks/{hnswlib-node-SYKJXGE2.js → hnswlib-node-RAYNVJCJ.js} +2 -2
  207. package/dist/cli/chunks/{hooks-XAJXPXTU.js → hooks-JMHFWVEQ.js} +10 -10
  208. package/dist/cli/chunks/hybrid-backend-TUBWJDDN.js +2 -0
  209. package/dist/cli/chunks/{hypergraph-engine-GIBPGW4N.js → hypergraph-engine-JUDBKPOX.js} +2 -2
  210. package/dist/cli/chunks/{hypergraph-handler-ENFK6IDN.js → hypergraph-handler-AXTWXOZU.js} +3 -3
  211. package/dist/cli/chunks/impact-analyzer-FXVGKS6B.js +2 -0
  212. package/dist/cli/chunks/init-handler-PARJNZFF.js +86 -0
  213. package/dist/cli/chunks/init-wizard-LK73HQ7W.js +2 -0
  214. package/dist/cli/chunks/kernel-TCZDKRSI.js +2 -0
  215. package/dist/cli/chunks/{kilocode-installer-YXFIRTSA.js → kilocode-installer-22HX2E4V.js} +2 -2
  216. package/dist/cli/chunks/{kiro-installer-JW3BG2MQ.js → kiro-installer-OVPBLY7J.js} +2 -2
  217. package/dist/cli/chunks/knowledge-graph-TWMB2GH2.js +2 -0
  218. package/dist/cli/chunks/{learning-BDBZ7ZVG.js → learning-DWXPJ3R6.js} +3 -3
  219. package/dist/cli/chunks/{llm-router-CCX2DYTC.js → llm-router-7PPVVKNG.js} +4 -4
  220. package/dist/cli/chunks/llm-router-service-HPDH3P77.js +2 -0
  221. package/dist/cli/chunks/{load-UJTTEOOK.js → load-VI5XHNZA.js} +2 -2
  222. package/dist/cli/chunks/load-test-HTYOUYSN.js +2 -0
  223. package/dist/cli/chunks/{mcp-2NAJYREC.js → mcp-UW4Z3Z64.js} +2 -2
  224. package/dist/cli/chunks/{memory-C3UQSN5F.js → memory-UD2KCB5M.js} +5 -5
  225. package/dist/cli/chunks/memory-backend-X5BE2MPK.js +2 -0
  226. package/dist/cli/chunks/{memory-handlers-ESFIJENU.js → memory-handlers-SQXMFX5X.js} +2 -2
  227. package/dist/cli/chunks/{multi-model-executor-SIHSHAD7.js → multi-model-executor-5O4WWU5Z.js} +2 -2
  228. package/dist/cli/chunks/{opencode-installer-KDYHUGPG.js → opencode-installer-DTRFDGM7.js} +2 -2
  229. package/dist/cli/chunks/{orchestrator-MJHIQEHD.js → orchestrator-ENJIKV6Z.js} +18 -18
  230. package/dist/cli/chunks/pattern-null-store-OCQGQZU6.js +2 -0
  231. package/dist/cli/chunks/{pattern-usage-recorder-OLBE4UIF.js → pattern-usage-recorder-QPNIU5PD.js} +2 -2
  232. package/dist/cli/chunks/{pipeline-IOK2CV3U.js → pipeline-G3JYDNPE.js} +2 -2
  233. package/dist/cli/chunks/{platform-53JQ7JXN.js → platform-P4WR6N3D.js} +2 -2
  234. package/dist/cli/chunks/{plugin-L5SDIWDI.js → plugin-C7763Q5W.js} +2 -2
  235. package/dist/cli/chunks/{prime-radiant-advanced-wasm-2DS67JFS.js → prime-radiant-advanced-wasm-DH6R3XSZ.js} +2 -2
  236. package/dist/cli/chunks/{project-root-LQMOFO2Z.js → project-root-7DTXDLEG.js} +2 -2
  237. package/dist/cli/chunks/protocol-executor-CYEQHQCL.js +2 -0
  238. package/dist/cli/chunks/{protocol-handler-NXG2M43B.js → protocol-handler-EODULGOZ.js} +2 -2
  239. package/dist/cli/chunks/{prove-7K7PFSSX.js → prove-A7G3SIOF.js} +2 -2
  240. package/dist/cli/chunks/qe-reasoning-bank-GSTA5WJ4.js +2 -0
  241. package/dist/cli/chunks/{quality-ATILUGMJ.js → quality-JTURFUX3.js} +2 -2
  242. package/dist/cli/chunks/{quality-gate-MPZMDPIZ.js → quality-gate-M2EI754V.js} +3 -3
  243. package/dist/cli/chunks/queen-coordinator-Y2Q5RQL7.js +2 -0
  244. package/dist/cli/chunks/{real-embeddings-VZN3KIAI.js → real-embeddings-DI7JMCG7.js} +2 -2
  245. package/dist/cli/chunks/{ref-validation-EUATPVXX.js → ref-validation-MSFMNKDR.js} +2 -2
  246. package/dist/cli/chunks/{roocode-installer-7M2GOUNZ.js → roocode-installer-XIMFFHOH.js} +2 -2
  247. package/dist/cli/chunks/router-4QB5L4IW.js +2 -0
  248. package/dist/cli/chunks/routing-feedback-YBVHJY5L.js +2 -0
  249. package/dist/cli/chunks/{routing-handler-VWANE652.js → routing-handler-MCDKNBQW.js} +2 -2
  250. package/dist/cli/chunks/{ruvector-commands-B2YIPGOV.js → ruvector-commands-OBSYAK2X.js} +2 -2
  251. package/dist/cli/chunks/rvf-dual-writer-T5B456SW.js +2 -0
  252. package/dist/cli/chunks/rvf-migration-adapter-2O2NL7ZF.js +2 -0
  253. package/dist/cli/chunks/{rvf-migration-coordinator-RQXOQJ5T.js → rvf-migration-coordinator-4DTRIHY6.js} +2 -2
  254. package/dist/cli/chunks/rvf-native-adapter-RDB3GWTW.js +2 -0
  255. package/dist/cli/chunks/{rvf-store-integrity-7P5YDXRH.js → rvf-store-integrity-CWAVMRC4.js} +2 -2
  256. package/dist/cli/chunks/safe-db-YXVMLFU4.js +2 -0
  257. package/dist/cli/chunks/schedule-K6XWCCSK.js +2 -0
  258. package/dist/cli/chunks/scheduler-4MW22D6Q.js +2 -0
  259. package/dist/cli/chunks/{security-VJ7TVSQF.js → security-74TWSO74.js} +3 -3
  260. package/dist/cli/chunks/{shared-rvf-adapter-63NXQFBX.js → shared-rvf-adapter-ZHNAGE5H.js} +2 -2
  261. package/dist/cli/chunks/{shared-rvf-dual-writer-JQRP7P5A.js → shared-rvf-dual-writer-BS5WAVCC.js} +2 -2
  262. package/dist/cli/chunks/sqlite-persistence-UVDHUSAU.js +2 -0
  263. package/dist/cli/chunks/{standalone-memory-WJ72PH5P.js → standalone-memory-3HGHTE7S.js} +2 -2
  264. package/dist/cli/chunks/{status-handler-G72ZSLAX.js → status-handler-XWEEGNGH.js} +2 -2
  265. package/dist/cli/chunks/{structural-health-HYBGP4BD.js → structural-health-TB5JGMVS.js} +2 -2
  266. package/dist/cli/chunks/{sync-5YMZZIF4.js → sync-LSPNSVDI.js} +2 -2
  267. package/dist/cli/chunks/{sync-O5FQAHT7.js → sync-T4VLBURM.js} +2 -2
  268. package/dist/cli/chunks/{task-handler-E6IFNHZG.js → task-handler-RQ65QKXX.js} +2 -2
  269. package/dist/cli/chunks/{task-handlers-P3GC2L5L.js → task-handlers-USYWJ4H2.js} +3 -3
  270. package/dist/cli/chunks/test-M2XTKD62.js +33 -0
  271. package/dist/cli/chunks/{test-scheduling-3HY4I3HY.js → test-scheduling-GYXJQHJL.js} +3 -3
  272. package/dist/cli/chunks/{token-bootstrap-A5QA4CWK.js → token-bootstrap-OTEMRUFR.js} +2 -2
  273. package/dist/cli/chunks/{token-usage-MUNQVPFT.js → token-usage-CISTB5K5.js} +2 -2
  274. package/dist/cli/chunks/{transformers-IEO25W5V.js → transformers-C7LV763N.js} +2 -2
  275. package/dist/cli/chunks/{tree-sitter-wasm-parser-T2EQHEAY.js → tree-sitter-wasm-parser-P26JC3YV.js} +2 -2
  276. package/dist/cli/chunks/{types-ODCPGCID.js → types-YMVMKIWB.js} +2 -2
  277. package/dist/cli/chunks/unified-memory-UUK77NSE.js +2 -0
  278. package/dist/cli/chunks/unified-memory-hnsw-JOUE6WNF.js +2 -0
  279. package/dist/cli/chunks/unified-persistence-3DRJGNQE.js +2 -0
  280. package/dist/cli/chunks/{upgrade-4DN6EIW2.js → upgrade-U2REOPAW.js} +2 -2
  281. package/dist/cli/chunks/{validate-TBNAPDE3.js → validate-NDTCKN7P.js} +2 -2
  282. package/dist/cli/chunks/{validate-swarm-ZN7XXUY4.js → validate-swarm-OJUGVH5Q.js} +2 -2
  283. package/dist/cli/chunks/visual-security-EM7FQG5X.js +2 -0
  284. package/dist/cli/chunks/{web-tree-sitter-DWAWVD2X.js → web-tree-sitter-2CLRSA7K.js} +2 -2
  285. package/dist/cli/chunks/{windsurf-installer-U6EROS5S.js → windsurf-installer-DSUJJ4PG.js} +2 -2
  286. package/dist/cli/chunks/witness-chain-7NZ6IIUN.js +2 -0
  287. package/dist/cli/chunks/{witness-chain-EQEJS2P4.js → witness-chain-TEGL4ZWB.js} +2 -2
  288. package/dist/cli/chunks/{witness-chain-repair-KBXDRXS3.js → witness-chain-repair-ZWS5WXFL.js} +2 -2
  289. package/dist/cli/chunks/{witness-chain-verifier-HSQGZ4R4.js → witness-chain-verifier-SPXKFC67.js} +2 -2
  290. package/dist/cli/chunks/{witness-key-manager-RAODG73T.js → witness-key-manager-EALOV4OV.js} +2 -2
  291. package/dist/cli/chunks/{workflow-KNFJNNKG.js → workflow-PYI6HCAG.js} +4 -4
  292. package/dist/cli/chunks/workflow-orchestrator-3C3S5FIM.js +2 -0
  293. package/dist/cli/chunks/{wrappers-NIJBA22T.js → wrappers-NXJHGK3W.js} +2 -2
  294. package/dist/cli/commands/test.js +17 -2
  295. package/dist/cli/handlers/init-flags.d.ts +45 -0
  296. package/dist/cli/handlers/init-flags.js +35 -0
  297. package/dist/cli/handlers/init-handler.d.ts +6 -0
  298. package/dist/cli/handlers/init-handler.js +24 -10
  299. package/dist/coordination/task-executor.js +4 -2
  300. package/dist/init/claude-plugin-detection.d.ts +63 -0
  301. package/dist/init/claude-plugin-detection.js +118 -0
  302. package/dist/init/init-wizard-hooks.d.ts +6 -1
  303. package/dist/init/init-wizard-hooks.js +9 -1
  304. package/dist/init/init-wizard.d.ts +4 -0
  305. package/dist/init/init-wizard.js +3 -1
  306. package/dist/init/orchestrator.js +1 -0
  307. package/dist/init/phases/08-mcp.d.ts +7 -0
  308. package/dist/init/phases/08-mcp.js +22 -0
  309. package/dist/init/phases/phase-interface.d.ts +5 -1
  310. package/dist/mcp/bundle.js +298 -298
  311. package/dist/mcp/handlers/domain-handler-configs.js +3 -1
  312. package/dist/mcp/handlers/handler-factory.js +5 -0
  313. package/dist/mcp/handlers/save-results-option.d.ts +35 -0
  314. package/dist/mcp/handlers/save-results-option.js +59 -0
  315. package/dist/mcp/protocol-server.js +2 -1
  316. package/dist/mcp/types.d.ts +9 -0
  317. package/package.json +1 -1
  318. package/dist/cli/chunks/adapter-D7G5MIDQ.js +0 -2
  319. package/dist/cli/chunks/aqe-learning-engine-G6TUFGHC.js +0 -2
  320. package/dist/cli/chunks/base-B45BOC7E.js +0 -2
  321. package/dist/cli/chunks/browser-workflow-MIBU4XMV.js +0 -2
  322. package/dist/cli/chunks/chunk-3DKYBHNA.js +0 -316
  323. package/dist/cli/chunks/chunk-AIE6OKCD.js +0 -2
  324. package/dist/cli/chunks/client-A4FTITK3.js +0 -2
  325. package/dist/cli/chunks/core-handlers-FO3QTNWI.js +0 -2
  326. package/dist/cli/chunks/cross-domain-router-LIV6SRWF.js +0 -2
  327. package/dist/cli/chunks/dream-DNLGHYXY.js +0 -2
  328. package/dist/cli/chunks/heartbeat-scheduler-DL4LXXJF.js +0 -2
  329. package/dist/cli/chunks/hnsw-adapter-Y64M43J4.js +0 -2
  330. package/dist/cli/chunks/hnsw-index-5V6DDMTA.js +0 -2
  331. package/dist/cli/chunks/hybrid-backend-JWT2V4FQ.js +0 -2
  332. package/dist/cli/chunks/impact-analyzer-XUZQSZZC.js +0 -2
  333. package/dist/cli/chunks/init-handler-CSA62LGT.js +0 -81
  334. package/dist/cli/chunks/init-wizard-KDJKHEPN.js +0 -2
  335. package/dist/cli/chunks/kernel-MUDYPGFR.js +0 -2
  336. package/dist/cli/chunks/knowledge-graph-GR52N7PU.js +0 -2
  337. package/dist/cli/chunks/llm-router-service-QL6LVKZ4.js +0 -2
  338. package/dist/cli/chunks/load-test-76V75WZ5.js +0 -2
  339. package/dist/cli/chunks/memory-backend-SMQRS5QN.js +0 -2
  340. package/dist/cli/chunks/pattern-null-store-MWAJMOYU.js +0 -2
  341. package/dist/cli/chunks/protocol-executor-32X3GAJT.js +0 -2
  342. package/dist/cli/chunks/qe-reasoning-bank-KAFV3TGI.js +0 -2
  343. package/dist/cli/chunks/queen-coordinator-L3SODGRX.js +0 -2
  344. package/dist/cli/chunks/router-DDCSSXYQ.js +0 -2
  345. package/dist/cli/chunks/routing-feedback-RFASKYCD.js +0 -2
  346. package/dist/cli/chunks/rvf-dual-writer-HCIF2G56.js +0 -2
  347. package/dist/cli/chunks/rvf-migration-adapter-UVAHQ7SV.js +0 -2
  348. package/dist/cli/chunks/rvf-native-adapter-F2I5FFHK.js +0 -2
  349. package/dist/cli/chunks/safe-db-6ZAA4S23.js +0 -2
  350. package/dist/cli/chunks/schedule-SM5Q6UVP.js +0 -2
  351. package/dist/cli/chunks/scheduler-4EYP4EZ6.js +0 -2
  352. package/dist/cli/chunks/sqlite-persistence-KLN2K266.js +0 -2
  353. package/dist/cli/chunks/test-OU6ERW67.js +0 -33
  354. package/dist/cli/chunks/unified-memory-B5IA2KKQ.js +0 -2
  355. package/dist/cli/chunks/unified-memory-hnsw-YF74LL3Z.js +0 -2
  356. package/dist/cli/chunks/unified-persistence-VZMGNGWY.js +0 -2
  357. package/dist/cli/chunks/visual-security-ZV3BLLSH.js +0 -2
  358. package/dist/cli/chunks/witness-chain-OA24MQWX.js +0 -2
  359. package/dist/cli/chunks/workflow-orchestrator-IMX2LSVE.js +0 -2
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
- import{a as P}from"./chunk-P4FRYNHL.js";import{b as w}from"./chunk-MM57SD2F.js";import{e as S}from"./chunk-I3BH3KIF.js";import{b as T,d as $}from"./chunk-ATXAMGVE.js";import{a as q}from"./chunk-AIE6OKCD.js";import{e as v}from"./chunk-OYVDTD3A.js";import{S as H,j as E}from"./chunk-URUOTHPO.js";$();var W=["oracle:test-exec","judge:llm","proxy:structural"],d="proxy:structural";function j(n){return n&&W.includes(n)?n:d}function m(n,e={}){switch(j(n)){case"oracle:test-exec":return!0;case"judge:llm":return e.allowJudgeTier===!0;default:return!1}}import{createHash as O}from"node:crypto";function D(n,e){let t=n.length;if(t===0)return-1/0;let r=e?.iters??2e3,a=e?.alpha??.05,s=(e?.seed??2654435761)>>>0,o=()=>(s=Math.imul(s,1664525)+1013904223>>>0,s/4294967296),c=new Array(r);for(let u=0;u<r;u++){let l=0;for(let h=0;h<t;h++)l+=n[Math.floor(o()*t)];c[u]=l/t}c.sort((u,l)=>u-l);let i=Math.min(Math.floor(a*r),r-1);return c[i]}function L(n,e){let t=Math.min(n.length,e.length),r=new Array(t);for(let a=0;a<t;a++)r[a]=n[a]-e[a];return r}var U=n=>m(n.provenanceTier,{allowJudgeTier:n.allowJudgeTier})?n.candidateHeldOut>n.baselineHeldOut?w(n.candidateAnchorMean,n.baselineAnchorMean,n.anchorTol)?{promote:!0,reason:"held-out gain, no anchor regression, oracle-tier evidence"}:{promote:!1,reason:`anchor regression: ${n.candidateAnchorMean} < ${n.baselineAnchorMean} - ${n.anchorTol}`}:{promote:!1,reason:`held-out ${n.candidateHeldOut} did not beat baseline ${n.baselineHeldOut}`}:{promote:!1,reason:`provenance tier '${n.provenanceTier}' not allowed to promote`},C=8,x=1e-6,N=n=>n.reduce((e,t)=>e+t,0)/n.length,V=n=>{let e=U(n);if(!e.promote)return e;let t=n.candidateHeldOutSamples,r=n.baselineHeldOutSamples;if(!t||!r||t.length===0||t.length!==r.length)return{promote:!1,reason:"significance gate: missing/mismatched paired held-out samples (need equal-length candidate & baseline per-task vectors)"};if(t.length<C)return{promote:!1,reason:`significance gate: only ${t.length} paired samples (< ${C}) \u2014 a bootstrap CI is not meaningful; fail closed rather than certify noise`};if(Math.abs(N(t)-n.candidateHeldOut)>x||Math.abs(N(r)-n.baselineHeldOut)>x)return{promote:!1,reason:"significance gate: sealed sample means do not match the sealed held-out scalars \u2014 inconsistent/forged evaluation"};let a=D(L(t,r));return a>0?{promote:!0,reason:`${e.reason}; paired gain significant (CI low ${a.toFixed(4)} > 0)`}:{promote:!1,reason:`significance gate: paired held-out gain not significant (95% CI lower bound ${a.toFixed(4)} \u2264 0)`}},se=Object.freeze({"accept/v1":U,"accept/v1+sig":V});function _(n){if(n===null||typeof n!="object")return JSON.stringify(n)??"null";if(Array.isArray(n))return`[${n.map(_).join(",")}]`;let e=n;return`{${Object.keys(e).filter(r=>e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${_(e[r])}`).join(",")}}`}var Q="aqe:promotion-path-rule:v1+sig",J=n=>m(n.provenanceTier,{allowJudgeTier:n.allowJudgeTier})?n.reward===void 0||n.rewardThreshold===void 0||!(n.reward>=n.rewardThreshold)?{promote:!1,reason:`reward ${n.reward} below threshold ${n.rewardThreshold}`}:n.occurrences===void 0||n.occurrenceThreshold===void 0||!(n.occurrences>=n.occurrenceThreshold)?{promote:!1,reason:`occurrences ${n.occurrences} below threshold ${n.occurrenceThreshold}`}:n.successRate===void 0||n.successRateThreshold===void 0||!(n.successRate>=n.successRateThreshold)?{promote:!1,reason:`success rate ${n.successRate} below threshold ${n.successRateThreshold}`}:n.withinActivityWindow!==!0?{promote:!1,reason:"pattern outside promotion activity window (stale)"}:{promote:!0,reason:"tier allowed; reward/occurrence/success-rate thresholds met; within activity window"}:{promote:!1,reason:`provenance tier '${n.provenanceTier}' not allowed to promote`},G=n=>m(n.provenanceTier,{allowJudgeTier:n.allowJudgeTier})?n.insightConfidence===void 0||n.insightConfidenceThreshold===void 0||!(n.insightConfidence>=n.insightConfidenceThreshold)?{promote:!1,reason:`insight confidence ${n.insightConfidence} below threshold ${n.insightConfidenceThreshold}`}:n.insightActionable!==!0?{promote:!1,reason:"insight produced no actionable reorganization"}:{promote:!0,reason:"tier allowed; insight confidence meets threshold; actionable"}:{promote:!1,reason:`provenance tier '${n.provenanceTier}' not allowed to apply`},M=Object.freeze({"pattern-promote/v1":J,"dream-apply/v1":G});function b(n){return O("sha256").update(_(n)).digest("hex")}function y(n){if(!(n in M))throw new Error(`Unknown promotion-path rule version '${n}' \u2014 cannot fingerprint an unregistered rule.`);return O("sha256").update(Q).update("\0").update(n).digest("hex")}function R(n,e){let t=M[n];if(!t)throw new Error(`Unknown promotion-path rule version '${n}' \u2014 refusing to re-execute an unregistered rule.`);return t(e)}function I(n,e={}){let t=[],r=b(n.sealed)===n.sealedHash;r||t.push("sealIntact");let a=!1;try{let c=y(n.ruleVersion);a=n.ruleFingerprint===c&&(e.pinnedRuleFingerprint===void 0||n.ruleFingerprint===e.pinnedRuleFingerprint)}catch{a=!1}a||t.push("gateUnchanged");let s=!1;r&&a&&(s=(R(n.ruleVersion,n.sealed).promote?"promote":"reject")===n.recordedVerdict),s||t.push("gateReExecutes");let o=t.length===0;return{valid:o,checks:{sealIntact:r,gateUnchanged:a,gateReExecutes:s},failures:t,reason:o?"promotion verified: sealed inputs intact, rule unchanged, frozen rule re-execution reproduces the recorded verdict":`promotion INVALID (failed: ${t.join(", ")}) \u2014 the recorded verdict is not reproducible under the frozen rule`}}q();H();var p=v.create("pattern-lifecycle"),z={promotionRewardThreshold:.7,promotionMinOccurrences:S,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3,maxAgeForActivePatterns:90,promotionActivityWindowDays:30,asymmetricLearning:{},allowJudgeTierPromotion:!1},k=5,B=.9,X=2;function Y(n,e){return e<k||!Number.isFinite(n)?0:Math.min(Math.max(n,0),1)}var A=class{constructor(e,t={}){this.db=e;this.config={...z,...t},this.asymmetricEngine=new P(this.config.asymmetricLearning),this.ensureSchema()}db;config;asymmetricEngine;_witnessChain=null;set witnessChain(e){this._witnessChain=e}_compressionService=null;set compressionService(e){this._compressionService=e}ensureSchema(){try{this.db.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.2");process.exit(0)}
2
+ import{a as P}from"./chunk-7UA7SMM4.js";import{b as w}from"./chunk-W7P7EOJ4.js";import{e as S}from"./chunk-BKZSTZDB.js";import{b as T,d as $}from"./chunk-URWT3EQT.js";import{a as q}from"./chunk-I7ECEOFV.js";import{e as v}from"./chunk-CV7E627D.js";import{S as H,j as E}from"./chunk-3DCRAW43.js";$();var W=["oracle:test-exec","judge:llm","proxy:structural"],d="proxy:structural";function j(n){return n&&W.includes(n)?n:d}function m(n,e={}){switch(j(n)){case"oracle:test-exec":return!0;case"judge:llm":return e.allowJudgeTier===!0;default:return!1}}import{createHash as O}from"node:crypto";function D(n,e){let t=n.length;if(t===0)return-1/0;let r=e?.iters??2e3,a=e?.alpha??.05,s=(e?.seed??2654435761)>>>0,o=()=>(s=Math.imul(s,1664525)+1013904223>>>0,s/4294967296),c=new Array(r);for(let u=0;u<r;u++){let l=0;for(let h=0;h<t;h++)l+=n[Math.floor(o()*t)];c[u]=l/t}c.sort((u,l)=>u-l);let i=Math.min(Math.floor(a*r),r-1);return c[i]}function L(n,e){let t=Math.min(n.length,e.length),r=new Array(t);for(let a=0;a<t;a++)r[a]=n[a]-e[a];return r}var U=n=>m(n.provenanceTier,{allowJudgeTier:n.allowJudgeTier})?n.candidateHeldOut>n.baselineHeldOut?w(n.candidateAnchorMean,n.baselineAnchorMean,n.anchorTol)?{promote:!0,reason:"held-out gain, no anchor regression, oracle-tier evidence"}:{promote:!1,reason:`anchor regression: ${n.candidateAnchorMean} < ${n.baselineAnchorMean} - ${n.anchorTol}`}:{promote:!1,reason:`held-out ${n.candidateHeldOut} did not beat baseline ${n.baselineHeldOut}`}:{promote:!1,reason:`provenance tier '${n.provenanceTier}' not allowed to promote`},C=8,x=1e-6,N=n=>n.reduce((e,t)=>e+t,0)/n.length,V=n=>{let e=U(n);if(!e.promote)return e;let t=n.candidateHeldOutSamples,r=n.baselineHeldOutSamples;if(!t||!r||t.length===0||t.length!==r.length)return{promote:!1,reason:"significance gate: missing/mismatched paired held-out samples (need equal-length candidate & baseline per-task vectors)"};if(t.length<C)return{promote:!1,reason:`significance gate: only ${t.length} paired samples (< ${C}) \u2014 a bootstrap CI is not meaningful; fail closed rather than certify noise`};if(Math.abs(N(t)-n.candidateHeldOut)>x||Math.abs(N(r)-n.baselineHeldOut)>x)return{promote:!1,reason:"significance gate: sealed sample means do not match the sealed held-out scalars \u2014 inconsistent/forged evaluation"};let a=D(L(t,r));return a>0?{promote:!0,reason:`${e.reason}; paired gain significant (CI low ${a.toFixed(4)} > 0)`}:{promote:!1,reason:`significance gate: paired held-out gain not significant (95% CI lower bound ${a.toFixed(4)} \u2264 0)`}},se=Object.freeze({"accept/v1":U,"accept/v1+sig":V});function _(n){if(n===null||typeof n!="object")return JSON.stringify(n)??"null";if(Array.isArray(n))return`[${n.map(_).join(",")}]`;let e=n;return`{${Object.keys(e).filter(r=>e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${_(e[r])}`).join(",")}}`}var Q="aqe:promotion-path-rule:v1+sig",J=n=>m(n.provenanceTier,{allowJudgeTier:n.allowJudgeTier})?n.reward===void 0||n.rewardThreshold===void 0||!(n.reward>=n.rewardThreshold)?{promote:!1,reason:`reward ${n.reward} below threshold ${n.rewardThreshold}`}:n.occurrences===void 0||n.occurrenceThreshold===void 0||!(n.occurrences>=n.occurrenceThreshold)?{promote:!1,reason:`occurrences ${n.occurrences} below threshold ${n.occurrenceThreshold}`}:n.successRate===void 0||n.successRateThreshold===void 0||!(n.successRate>=n.successRateThreshold)?{promote:!1,reason:`success rate ${n.successRate} below threshold ${n.successRateThreshold}`}:n.withinActivityWindow!==!0?{promote:!1,reason:"pattern outside promotion activity window (stale)"}:{promote:!0,reason:"tier allowed; reward/occurrence/success-rate thresholds met; within activity window"}:{promote:!1,reason:`provenance tier '${n.provenanceTier}' not allowed to promote`},G=n=>m(n.provenanceTier,{allowJudgeTier:n.allowJudgeTier})?n.insightConfidence===void 0||n.insightConfidenceThreshold===void 0||!(n.insightConfidence>=n.insightConfidenceThreshold)?{promote:!1,reason:`insight confidence ${n.insightConfidence} below threshold ${n.insightConfidenceThreshold}`}:n.insightActionable!==!0?{promote:!1,reason:"insight produced no actionable reorganization"}:{promote:!0,reason:"tier allowed; insight confidence meets threshold; actionable"}:{promote:!1,reason:`provenance tier '${n.provenanceTier}' not allowed to apply`},M=Object.freeze({"pattern-promote/v1":J,"dream-apply/v1":G});function b(n){return O("sha256").update(_(n)).digest("hex")}function y(n){if(!(n in M))throw new Error(`Unknown promotion-path rule version '${n}' \u2014 cannot fingerprint an unregistered rule.`);return O("sha256").update(Q).update("\0").update(n).digest("hex")}function R(n,e){let t=M[n];if(!t)throw new Error(`Unknown promotion-path rule version '${n}' \u2014 refusing to re-execute an unregistered rule.`);return t(e)}function I(n,e={}){let t=[],r=b(n.sealed)===n.sealedHash;r||t.push("sealIntact");let a=!1;try{let c=y(n.ruleVersion);a=n.ruleFingerprint===c&&(e.pinnedRuleFingerprint===void 0||n.ruleFingerprint===e.pinnedRuleFingerprint)}catch{a=!1}a||t.push("gateUnchanged");let s=!1;r&&a&&(s=(R(n.ruleVersion,n.sealed).promote?"promote":"reject")===n.recordedVerdict),s||t.push("gateReExecutes");let o=t.length===0;return{valid:o,checks:{sealIntact:r,gateUnchanged:a,gateReExecutes:s},failures:t,reason:o?"promotion verified: sealed inputs intact, rule unchanged, frozen rule re-execution reproduces the recorded verdict":`promotion INVALID (failed: ${t.join(", ")}) \u2014 the recorded verdict is not reproducible under the frozen rule`}}q();H();var p=v.create("pattern-lifecycle"),z={promotionRewardThreshold:.7,promotionMinOccurrences:S,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3,maxAgeForActivePatterns:90,promotionActivityWindowDays:30,asymmetricLearning:{},allowJudgeTierPromotion:!1},k=5,B=.9,X=2;function Y(n,e){return e<k||!Number.isFinite(n)?0:Math.min(Math.max(n,0),1)}var A=class{constructor(e,t={}){this.db=e;this.config={...z,...t},this.asymmetricEngine=new P(this.config.asymmetricLearning),this.ensureSchema()}db;config;asymmetricEngine;_witnessChain=null;set witnessChain(e){this._witnessChain=e}_compressionService=null;set compressionService(e){this._compressionService=e}ensureSchema(){try{this.db.prepare(`
3
3
  SELECT deprecated_at FROM qe_patterns LIMIT 1
4
4
  `).get()}catch(e){p.debug("Adding missing deprecated_at column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
5
5
  ALTER TABLE qe_patterns ADD COLUMN deprecated_at TEXT DEFAULT NULL
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
- import{b as T}from"./chunk-GX5RFGW2.js";var S,E,t,N,_=T(()=>{"use strict";S={MMAP_SIZE_BYTES:67108864,CACHE_SIZE_KB:-32e3,BUSY_TIMEOUT_MS:5e3,DEFAULT_VECTOR_DIMENSIONS:384,DEFAULT_SEARCH_LIMIT:100,CLEANUP_INTERVAL_MS:6e4,TTL_MULTIPLIER_MS:1e3},E={M_CONNECTIONS:16,EF_CONSTRUCTION:200,EF_SEARCH:100,DEFAULT_K_NEIGHBORS:10,COVERAGE_VECTOR_DIMENSION:384},t={MAX_CONCURRENT_AGENTS:15,DEFAULT_AGENT_TTL_MS:36e5,DEFAULT_AGENT_TIMEOUT_MS:12e4,MAX_POOL_SIZE:10},N={MAX_HISTORY_SIZE:1e4}});export{S as a,E as b,t as c,N as d,_ as e};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.2");process.exit(0)}
2
+ import{b as T}from"./chunk-D75HDHX3.js";var S,E,t,N,_=T(()=>{"use strict";S={MMAP_SIZE_BYTES:67108864,CACHE_SIZE_KB:-32e3,BUSY_TIMEOUT_MS:5e3,DEFAULT_VECTOR_DIMENSIONS:384,DEFAULT_SEARCH_LIMIT:100,CLEANUP_INTERVAL_MS:6e4,TTL_MULTIPLIER_MS:1e3},E={M_CONNECTIONS:16,EF_CONSTRUCTION:200,EF_SEARCH:100,DEFAULT_K_NEIGHBORS:10,COVERAGE_VECTOR_DIMENSION:384},t={MAX_CONCURRENT_AGENTS:15,DEFAULT_AGENT_TTL_MS:36e5,DEFAULT_AGENT_TIMEOUT_MS:12e4,MAX_POOL_SIZE:10},N={MAX_HISTORY_SIZE:1e4}});export{S as a,E as b,t as c,N as d,_ as e};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.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.15.2");process.exit(0)}
2
2
  import{createHash as l}from"crypto";var u="0".repeat(64);function k(t){return l("sha256").update(t,"utf-8").digest("hex")}function v(t){try{return l("shake256",{outputLength:32}).update(t,"utf-8").digest("hex")}catch{return k(t)}}function o(t,e){return t==="shake256"?v(e):k(e)}function h(t){return JSON.stringify({id:t.id,prev_hash:t.prev_hash,action_hash:t.action_hash,action_type:t.action_type,action_data:t.action_data,timestamp:t.timestamp,actor:t.actor})}function c(t){return Buffer.from(t.prev_hash+t.action_hash+t.action_type+t.timestamp+t.actor,"utf-8")}var m="CHAIN_REANCHOR";function y(t){return o(t.hash_algo||"sha256",h(t))}var f=class{constructor(e,n,i={}){this.db=e;this.keyManager=n;this.options=i}db;keyManager;options;archiveRows=null;parentIndex=new Map;acks=new Map;pins=[];forks=[];tamper;signatureFailures=0;firstSignatureFailure;entriesChecked=0;archiveExists;run(){let e=g(this.db,"witness_chain")?this.db.prepare("SELECT * FROM witness_chain ORDER BY id ASC").all():[];return e.length===0?this.getArchive().length>0?(this.tamper={id:1,reason:"live-chain-missing"},this.result(1)):{valid:!0,entriesChecked:0,status:"valid",tampered:!1,forks:[],acknowledgedForks:[],forkDetails:[]}:(this.walk(e,"live")&&this.options.includeArchive&&this.walk(this.getArchive(),"archive"),this.tamper||this.checkPins(),this.result(e[0].id))}walk(e,n){for(let i=0;i<e.length;i++){let r=e[i];this.entriesChecked++;let s=this.classify(r,i>0?e[i-1]:void 0);if(s.kind==="tamper")return this.tamper={id:r.id,reason:s.reason},!1;if(s.kind==="fork")this.forks.push({id:r.id,parentId:s.parentId,prevHash:r.prev_hash,actionHash:r.action_hash,table:n,acknowledged:!1});else if(r.action_type===m){if(this.checkSignature(r)==="invalid")return this.tamper={id:r.id,reason:"reanchor-signature-invalid"},!1;this.registerReanchor(r)}this.checkAllSignatures(r)}return!0}classify(e,n){let i=e.hash_algo||"sha256";if(e.action_hash!==o(i,e.action_data))return{kind:"tamper",reason:"action-hash-mismatch"};if(e.id===1)return e.prev_hash===u?{kind:"linked"}:{kind:"tamper",reason:"genesis-link-mismatch"};if(n&&e.prev_hash===o(i,h(n)))return this.idsContiguous(n.id,e.id)?{kind:"linked"}:{kind:"tamper",reason:"id-gap"};let r=this.findEntryById(e.id-1);if(r&&e.prev_hash===o(i,h(r)))return{kind:"linked"};let s=this.lookupParent(i,e.prev_hash);return s!==void 0&&s<e.id?this.idsContiguous(s,e.id)?this.checkSignature(e)==="invalid"?{kind:"tamper",reason:"fork-signature-invalid"}:{kind:"fork",parentId:s}:{kind:"tamper",reason:"id-gap"}:{kind:"tamper",reason:e.prev_hash===u?"unlinked-genesis-prev-hash":"unlinked-prev-hash"}}findEntryById(e){return this.db.prepare("SELECT * FROM witness_chain WHERE id = ?").get(e)??(this.hasArchive()?this.db.prepare("SELECT * FROM witness_chain_archive WHERE id = ?").get(e):void 0)}getArchive(){return this.archiveRows||(this.archiveRows=this.hasArchive()?this.db.prepare("SELECT * FROM witness_chain_archive ORDER BY id ASC").all():[]),this.archiveRows}hasArchive(){return this.archiveExists===void 0&&(this.archiveExists=g(this.db,"witness_chain_archive")),this.archiveExists}lookupParent(e,n){let i=this.parentIndex.get(e);if(!i){i=new Map;let r=this.db.prepare("SELECT * FROM witness_chain").iterate();for(let s of r)i.set(o(e,h(s)),s.id);for(let s of this.getArchive()){let d=o(e,h(s));i.has(d)||i.set(d,s.id)}this.parentIndex.set(e,i)}return i.get(n)}idsContiguous(e,n){let i=n-e-1;return i<=0?!0:(this.hasArchive()?this.db.prepare(`SELECT COUNT(*) AS n FROM (
3
3
  SELECT id FROM witness_chain WHERE id > ? AND id < ?
4
4
  UNION SELECT id FROM witness_chain_archive WHERE id > ? AND id < ?)`).get(e,n,e,n):this.db.prepare("SELECT COUNT(*) AS n FROM witness_chain WHERE id > ? AND id < ?").get(e,n)).n===i}checkSignature(e){return!e.signature||!e.signer_key_id?"unsigned":!this.keyManager||!this.keyManager.hasKey(e.signer_key_id)?"unverifiable":this.keyManager.verify(c(e),Buffer.from(e.signature,"hex"),e.signer_key_id)?"ok":"invalid"}checkAllSignatures(e){if(this.options.checkSignatures!==!0||!this.keyManager||!e.signature||!e.signer_key_id)return;this.keyManager.verify(c(e),Buffer.from(e.signature,"hex"),e.signer_key_id)||(this.signatureFailures++,this.firstSignatureFailure??=e.id)}registerReanchor(e){let n;try{n=JSON.parse(e.action_data)??{}}catch{return}if(Array.isArray(n.forks))for(let i of n.forks){if(typeof i?.id!="number"||i.id>=e.id||typeof i.parentId!="number"||typeof i.prevHash!="string"||typeof i.actionHash!="string")continue;let r=this.acks.get(i.id)??[];r.push({id:i.id,parentId:i.parentId,prevHash:i.prevHash,actionHash:i.actionHash}),this.acks.set(i.id,r)}if(Array.isArray(n.pins))for(let i of n.pins)typeof i?.id=="number"&&typeof i.hash=="string"&&this.pins.push({id:i.id,hash:i.hash})}checkPins(){for(let e of this.pins){let n=this.findEntryById(e.id);if(!n||y(n)!==e.hash){this.tamper={id:e.id,reason:"reanchored-row-changed"};return}}}result(e){for(let a of this.forks)a.acknowledged=(this.acks.get(a.id)??[]).some(p=>p.parentId===a.parentId&&p.prevHash===a.prevHash&&p.actionHash===a.actionHash);let n=this.forks.filter(a=>!a.acknowledged),i=this.tamper!==void 0||this.signatureFailures>0,r=i?"tampered":n.length>0?"forked":this.forks.length>0?"valid-with-forks":"valid",s=r==="valid"||r==="valid-with-forks",d=n[0]?.id??this.tamper?.id??(this.signatureFailures>0?e:void 0);return{valid:s,entriesChecked:this.entriesChecked,signatureFailures:this.signatureFailures,status:r,tampered:i,forks:this.forks.map(a=>a.id),acknowledgedForks:this.forks.filter(a=>a.acknowledged).map(a=>a.id),forkDetails:this.forks,...d!==void 0&&!s?{brokenAt:d}:{},...i?{tamperedAt:this.tamper?.id??this.firstSignatureFailure,tamperReason:this.tamper?.reason??"signature-invalid"}:{}}}};function R(t,e,n){return new f(t,e,n).run()}function g(t,e){return t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}export{u as a,k as b,v as c,o as d,h as e,c as f,m as g,y as h,f as i,R as j,g as k};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
- import{a as W}from"./chunk-ISGFAMHZ.js";import{c as q,d as V}from"./chunk-N5ZHIQAV.js";import{c as x}from"./chunk-VCYOFWMG.js";import{b as E,d as $}from"./chunk-ATXAMGVE.js";import{a as M,b as U,d as ee}from"./chunk-UGYXUPGN.js";import{i as v}from"./chunk-MO3QXLF2.js";import{a as G}from"./chunk-AIE6OKCD.js";import{e as R}from"./chunk-OYVDTD3A.js";import{a as C,e as H}from"./chunk-X5RELRY7.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.15.2");process.exit(0)}
2
+ import{a as W}from"./chunk-NWYAV2UG.js";import{c as q,d as V}from"./chunk-GJ7DON5S.js";import{c as x}from"./chunk-WJ7657IX.js";import{b as E,d as $}from"./chunk-URWT3EQT.js";import{a as M,b as U,d as ee}from"./chunk-FH6N2LKG.js";import{i as v}from"./chunk-Z3PANQUT.js";import{a as G}from"./chunk-I7ECEOFV.js";import{e as R}from"./chunk-CV7E627D.js";import{a as C,e as H}from"./chunk-3KTAMNKI.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 W}from"./chunk-ISGFAMHZ.js";import{c as q,d as V}from"./chunk-N5ZHIQ
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-CNGAUUMT.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-FY4DOYS2.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 W}from"./chunk-ISGFAMHZ.js";import{c as q,d as V}from"./chunk-N5ZHIQ
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-B45BOC7E.js"),{createQEReasoningBank:i}=await import("./qe-reasoning-bank-KAFV3TGI.js"),r=await n(),a=i(r);await a.initialize();try{let{getSharedRvfDualWriter:d}=await import("./shared-rvf-dual-writer-JQRP7P5A.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-4DSLX33Y.js"),{createQEReasoningBank:i}=await import("./qe-reasoning-bank-GSTA5WJ4.js"),r=await n(),a=i(r);await a.initialize();try{let{getSharedRvfDualWriter:d}=await import("./shared-rvf-dual-writer-BS5WAVCC.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 W}from"./chunk-ISGFAMHZ.js";import{c as q,d as V}from"./chunk-N5ZHIQ
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-CNGAUUMT.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-63NXQFBX.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 V}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-63NXQFBX.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-JQRP7P5A.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 W,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=q.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,Z as b,L as c,de as d,P as e,T as f,te as g,B as h,O as i,F as j,j as k,w as l,Q as m,_ as n,A as o,b as p,X as q,N as r,oe as s,ce as t,pe as u,z as v};
120
+ `).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:E(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function se(p){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[p]||"test-template"}function oe(p){let e=new N(p);return import("./feature-flags-FY4DOYS2.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-ZHNAGE5H.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 V}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-ZHNAGE5H.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-BS5WAVCC.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 W,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=q.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,Z as b,L as c,de as d,P as e,T as f,te as g,B as h,O as i,F as j,j as k,w as l,Q as m,_ as n,A as o,b as p,X as q,N as r,oe as s,ce as t,pe as u,z as v};
@@ -1,6 +1,6 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
- import{a as Y}from"./chunk-S644OORE.js";import{d as O,e as k}from"./chunk-4BWDCUZZ.js";import{c as N,d as Q}from"./chunk-ZXIIB3QE.js";import"./chunk-GX5RFGW2.js";import{Command as se}from"commander";import d from"chalk";import*as S from"fs";import*as w from"path";import*as R from"fs";import*as h from"path";import{isCollection as H,isScalar as J,parseDocument as K,visit as V}from"yaml";var E={version:"1",name:"aqe-ci",phases:[{name:"Test Generation",type:"test",enabled:!0,config:{target:".",framework:"vitest",type:"unit"},continueOnFailure:!1,timeout:300},{name:"Coverage Analysis",type:"coverage",enabled:!0,config:{target:".",threshold:80},continueOnFailure:!0,timeout:300},{name:"Security Scan",type:"security",enabled:!0,config:{sast:!0},continueOnFailure:!0,timeout:300},{name:"Quality Gate",type:"quality-gate",enabled:!0,config:{},continueOnFailure:!1,timeout:60}],output:{format:"json",directory:".aqe-ci-output",combinedReport:!0},qualityGate:{enforced:!0,thresholds:{coverage:80,security:"medium",quality:70}}},Z=[".aqe-ci.yml",".aqe-ci.yaml","aqe-ci.yml","aqe-ci.yaml"];function T(n=process.cwd()){let r=h.resolve(n);for(let s=0;s<10;s++){for(let a of Z){let e=h.join(r,a);if(R.existsSync(e))return e}let u=h.dirname(r);if(u===r)break;r=u}return null}function L(n){if(!R.existsSync(n))return{success:!1,errors:[`Config file not found: ${n}`]};let r;try{r=R.readFileSync(n,"utf-8")}catch(s){return{success:!1,errors:[`Failed to read config: ${s}`]}}return ne(r,n)}var U=1e4,W=1e4,j=20,ee=new Set(["__proto__","constructor","prototype"]);function F(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&(Object.getPrototypeOf(n)===Object.prototype||Object.getPrototypeOf(n)===null)}function te(n){let r=n.split(`
3
- `);if(r.length>U)throw new Error(`YAML exceeds maximum allowed lines (${U})`);if(r.some(e=>e.length>W))throw new Error(`YAML exceeds maximum line length (${W})`);let s=K(n,{prettyErrors:!1,merge:!0});if(s.errors.length)throw new Error(s.errors.map(e=>e.message).join("; "));V(s,{Collection:(e,i,c)=>{if(c.filter(H).length>=j)throw new Error(`YAML exceeds maximum depth (${j})`)},Pair:(e,i)=>{if(J(i.key)&&ee.has(String(i.key.value)))throw new Error(`Unsafe YAML key: ${i.key.value}`)}});let u=s.contents===null?{}:s.toJS({maxAliasCount:100});function a(e,i,c){if(!(e===null||typeof e!="object")){if(i>j)throw new Error(`YAML exceeds maximum depth (${j})`);if(c.has(e))throw new Error("Cyclic YAML aliases are not supported");c.add(e);for(let m of Object.values(e))a(m,i+1,c);c.delete(e)}}if(a(u,0,new Set),!F(u))throw new Error("CI config must be a YAML mapping");return u}function ne(n,r){let s;try{s=te(n)}catch(l){return{success:!1,errors:[`Invalid YAML: ${l}`]}}let u=[],a=M();function e(l,t,o,g){let p=l[t];return p===void 0?o:typeof p!="string"||!p.trim()?(u.push(`${g} must be a non-empty string`),o):p}function i(l,t,o,g){let p=l[t];return p===void 0?o:typeof p!="boolean"?(u.push(`${g} must be a boolean`),o):p}if(s.version!==void 0&&(typeof s.version=="number"&&Number.isFinite(s.version)?a.version=String(s.version):a.version=e(s,"version",a.version,"version")),a.name=e(s,"name",a.name,"name"),s.output!==void 0&&(F(s.output)?(a.output.format=e(s.output,"format",a.output.format,"output.format"),a.output.directory=e(s.output,"directory",a.output.directory,"output.directory"),a.output.combinedReport=i(s.output,"combined_report",a.output.combinedReport,"output.combined_report")):u.push("output must be a mapping")),s.quality_gate!==void 0)if(!F(s.quality_gate))u.push("quality_gate must be a mapping");else{let l=s.quality_gate;if(a.qualityGate.enforced=i(l,"enforced",a.qualityGate.enforced,"quality_gate.enforced"),l.thresholds!==void 0)if(!F(l.thresholds))u.push("quality_gate.thresholds must be a mapping");else{for(let t of["coverage","quality"]){let o=l.thresholds[t];o!==void 0&&(typeof o!="number"||!Number.isFinite(o)||o<0||o>100?u.push(`quality_gate.thresholds.${t} must be a finite number between 0 and 100`):a.qualityGate.thresholds[t]=o)}if(l.thresholds.security!==void 0){let t=l.thresholds.security;typeof t!="string"||!["none","low","medium","high"].includes(t)?u.push("quality_gate.thresholds.security must be none, low, medium or high"):a.qualityGate.thresholds.security=t}}}if(s.phases!==void 0)if(a.phases=[],!Array.isArray(s.phases))u.push("phases must be a sequence");else for(let[l,t]of s.phases.entries()){if(!F(t)){u.push(`Phase ${l+1} must be a mapping`);continue}t.name===void 0&&u.push(`Phase ${l+1} must have a name`);let o=e(t,"name","",`Phase ${l+1} name`),g=["test","coverage","security","quality-gate","code-intelligence","custom"];if(!g.includes(t.type)){u.push(`Phase "${o}" has invalid type "${t.type}". Valid: ${g.join(", ")}`);continue}let p=300;t.timeout!==void 0&&(typeof t.timeout!="number"||!Number.isFinite(t.timeout)||t.timeout<=0?u.push(`Phase "${o}" timeout must be a positive finite number`):p=t.timeout),t.config!==void 0&&!F(t.config)&&u.push(`Phase "${o}" config must be a mapping`),a.phases.push({name:o,type:t.type,timeout:p,enabled:i(t,"enabled",!0,`Phase "${o}" enabled`),continueOnFailure:i(t,"continue_on_failure",!1,`Phase "${o}" continue_on_failure`),config:F(t.config)?{...t.config}:{}})}a.phases.length===0&&u.push("Config must have at least one phase");let c=h.resolve(r?h.dirname(r):process.cwd());function m(l){let t=l,o=[];for(;!R.existsSync(t);){let g=h.dirname(t);if(g===t)break;o.unshift(h.basename(t)),t=g}return h.resolve(R.realpathSync(t),...o)}function b(l,t){if(typeof l!="string"||!l.trim()||l.includes("\0")){u.push(`${t} must be a non-empty relative path`);return}let o=h.resolve(c,l),g=h.relative(c,o);if(h.isAbsolute(l)||h.win32.isAbsolute(l)||g===".."||g.startsWith(`..${h.sep}`)||h.isAbsolute(g)){u.push(`${t} must stay inside the project and use a relative path`);return}try{let p=h.relative(m(c),m(o));if(p===".."||p.startsWith(`..${h.sep}`)||h.isAbsolute(p)){u.push(`${t} must stay inside the project (symlink escapes are not allowed)`);return}}catch(p){u.push(`${t} cannot be resolved safely: ${p}`);return}return r?o:l}a.output.directory=b(a.output.directory,"output.directory")??a.output.directory;for(let l of a.phases)if(l.config.target!==void 0){let t=b(l.config.target,`Phase "${l.name}" config.target`);t!==void 0&&(l.config.target=t)}return u.length>0?{success:!1,config:a,errors:u}:{success:!0,config:a,errors:[],configPath:r}}function M(){return{...E,phases:E.phases.map(n=>({...n,config:{...n.config}})),output:{...E.output},qualityGate:{...E.qualityGate,thresholds:{...E.qualityGate.thresholds}}}}async function oe(n,r,s,u,a){let e=Date.now(),i=[];if(!n.enabled)return{phase:n.name,type:n.type,status:"skipped",duration:0,exitCode:0,summary:"Phase disabled",artifacts:[]};try{let c={},m="passed",b="";switch(n.type){case"test":{let t=await r.kernel.getDomainAPIAsync("test-generation");if(!t)return D(n,e,"failed",1,"Test generation domain not available",i);let o=n.config.target||".",{walkSourceFiles:g}=await import("./file-discovery-IHGDYW34.js"),p=w.resolve(o),q=g(p,{includeTests:!1}),$=await t.generateTests({sourceFiles:q,testType:n.config.type||"unit",framework:n.config.framework||"vitest",coverageTarget:80});if($.success&&$.value){let C=$.value;c={testsGenerated:C.tests.length,coverageEstimate:C.coverageEstimate},b=`Generated ${C.tests.length} tests (${C.coverageEstimate==null?"coverage unmeasured":`est. ${C.coverageEstimate}% coverage`})`;let y=w.join(s,"test-generation.json");S.writeFileSync(y,k(C),"utf-8"),i.push(y)}else m="failed",b=$.error?.message||"Test generation failed";break}case"coverage":{let t=await r.kernel.getDomainAPIAsync("coverage-analysis");if(!t)return D(n,e,"failed",1,"Coverage analysis domain not available",i);let o=n.config.target||".",g=n.config.threshold||80,{walkSourceFiles:p}=await import("./file-discovery-IHGDYW34.js"),q=w.resolve(o),$=p(q,{includeTests:!1}),C=Y($),y=await t.analyze({coverageData:C,threshold:g,includeFileDetails:!0});if(y.success&&y.value){let I=y.value;c={...I.summary,meetsThreshold:I.meetsThreshold,threshold:g},m=I.meetsThreshold?"passed":"warning",b=`Line: ${I.summary.line}%, Branch: ${I.summary.branch}% \u2014 ${I.meetsThreshold?"meets":"below"} ${g}% threshold`;let x=w.join(s,"coverage.json");S.writeFileSync(x,k(y.value),"utf-8"),i.push(x)}else m="failed",b=y.error?.message||"Coverage analysis failed";break}case"security":{let t=await r.kernel.getDomainAPIAsync("security-compliance");if(!t)return D(n,e,"failed",1,"Security domain not available",i);let o=n.config.target||".",{walkSourceFiles:g}=await import("./file-discovery-IHGDYW34.js"),p=w.resolve(o),q=g(p,{includeTests:!0}),$=await t.runSASTScan(q);if($.success&&$.value){let C=$.value,y=C.vulnerabilities||[],I=y.filter(f=>f.severity==="high"||f.severity==="critical").length;c={vulnerabilities:y.length,high:I},m=I>0?"failed":y.length>0?"warning":"passed",b=y.length===0?"No vulnerabilities found":`${y.length} vulnerabilities (${I} high/critical)`;let{toSARIF:x}=await import("./ci-output-CRFWLUAA.js"),G=w.join(s,"security.sarif");S.writeFileSync(G,x({vulnerabilities:y,target:o,scanType:"SAST"}),"utf-8"),i.push(G);let A=w.join(s,"security.json");S.writeFileSync(A,k(C),"utf-8"),i.push(A)}else m="failed",b=$.error?.message||"Security scan failed";break}case"quality-gate":{try{let o=await N(r.kernel.memory),g=Q(o,{coverage:a});c={...g,metrics:o,evidenceStatus:"measured"},m=g.passed?"passed":"failed",b=`Quality gate: ${g.passed?"PASSED":"FAILED"} (${g.checks.filter(p=>p.passed).length}/${g.checks.length} measured checks passed)`}catch(o){m="failed",b=`Quality gate: ${o instanceof Error?o.message:String(o)}`,c={passed:!1,evidenceStatus:"unavailable",error:b,checks:[]}}let t=w.join(s,`quality-gate-${u+1}.json`);S.writeFileSync(t,k(c),"utf-8"),i.push(t);break}case"code-intelligence":{let t=await r.kernel.getDomainAPIAsync("code-intelligence");if(!t)return D(n,e,"failed",1,"Code intelligence domain not available",i);let o=n.config.target||".",{walkSourceFiles:g}=await import("./file-discovery-IHGDYW34.js"),p=w.resolve(o),q=g(p,{includeTests:!1}),$=await t.index({paths:q,incremental:!0});if($.success&&$.value){let C=$.value;c=C,b=`Indexed ${C.filesIndexed} files, ${C.nodesCreated} nodes`;let y=w.join(s,"code-intelligence.json");S.writeFileSync(y,k(C),"utf-8"),i.push(y)}else m="warning",b=$.error?.message||"Code intelligence indexing incomplete";break}default:b=`Custom phase "${n.name}" \u2014 no built-in handler`,m="warning"}let l=Date.now()-e;return{phase:n.name,type:n.type,status:m,duration:l,exitCode:m==="failed"?1:0,summary:b,artifacts:i,details:c}}catch(c){let m=Date.now()-e;return{phase:n.name,type:n.type,status:"failed",duration:m,exitCode:1,summary:`Error: ${c instanceof Error?c.message:String(c)}`,artifacts:i}}}function D(n,r,s,u,a,e){return{phase:n.name,type:n.type,status:s,duration:Date.now()-r,exitCode:u,summary:a,artifacts:e}}function z(n){let r=`# AQE CI/CD Report
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.2");process.exit(0)}
2
+ import{a as Y}from"./chunk-TMYGGYRY.js";import{d as O,e as k}from"./chunk-MY2XZHW3.js";import{c as N,d as Q}from"./chunk-GSC6JXDE.js";import"./chunk-D75HDHX3.js";import{Command as se}from"commander";import d from"chalk";import*as S from"fs";import*as w from"path";import*as R from"fs";import*as h from"path";import{isCollection as H,isScalar as J,parseDocument as K,visit as V}from"yaml";var E={version:"1",name:"aqe-ci",phases:[{name:"Test Generation",type:"test",enabled:!0,config:{target:".",framework:"vitest",type:"unit"},continueOnFailure:!1,timeout:300},{name:"Coverage Analysis",type:"coverage",enabled:!0,config:{target:".",threshold:80},continueOnFailure:!0,timeout:300},{name:"Security Scan",type:"security",enabled:!0,config:{sast:!0},continueOnFailure:!0,timeout:300},{name:"Quality Gate",type:"quality-gate",enabled:!0,config:{},continueOnFailure:!1,timeout:60}],output:{format:"json",directory:".aqe-ci-output",combinedReport:!0},qualityGate:{enforced:!0,thresholds:{coverage:80,security:"medium",quality:70}}},Z=[".aqe-ci.yml",".aqe-ci.yaml","aqe-ci.yml","aqe-ci.yaml"];function T(n=process.cwd()){let r=h.resolve(n);for(let s=0;s<10;s++){for(let a of Z){let e=h.join(r,a);if(R.existsSync(e))return e}let u=h.dirname(r);if(u===r)break;r=u}return null}function L(n){if(!R.existsSync(n))return{success:!1,errors:[`Config file not found: ${n}`]};let r;try{r=R.readFileSync(n,"utf-8")}catch(s){return{success:!1,errors:[`Failed to read config: ${s}`]}}return ne(r,n)}var U=1e4,W=1e4,j=20,ee=new Set(["__proto__","constructor","prototype"]);function F(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&(Object.getPrototypeOf(n)===Object.prototype||Object.getPrototypeOf(n)===null)}function te(n){let r=n.split(`
3
+ `);if(r.length>U)throw new Error(`YAML exceeds maximum allowed lines (${U})`);if(r.some(e=>e.length>W))throw new Error(`YAML exceeds maximum line length (${W})`);let s=K(n,{prettyErrors:!1,merge:!0});if(s.errors.length)throw new Error(s.errors.map(e=>e.message).join("; "));V(s,{Collection:(e,i,c)=>{if(c.filter(H).length>=j)throw new Error(`YAML exceeds maximum depth (${j})`)},Pair:(e,i)=>{if(J(i.key)&&ee.has(String(i.key.value)))throw new Error(`Unsafe YAML key: ${i.key.value}`)}});let u=s.contents===null?{}:s.toJS({maxAliasCount:100});function a(e,i,c){if(!(e===null||typeof e!="object")){if(i>j)throw new Error(`YAML exceeds maximum depth (${j})`);if(c.has(e))throw new Error("Cyclic YAML aliases are not supported");c.add(e);for(let m of Object.values(e))a(m,i+1,c);c.delete(e)}}if(a(u,0,new Set),!F(u))throw new Error("CI config must be a YAML mapping");return u}function ne(n,r){let s;try{s=te(n)}catch(l){return{success:!1,errors:[`Invalid YAML: ${l}`]}}let u=[],a=M();function e(l,t,o,g){let p=l[t];return p===void 0?o:typeof p!="string"||!p.trim()?(u.push(`${g} must be a non-empty string`),o):p}function i(l,t,o,g){let p=l[t];return p===void 0?o:typeof p!="boolean"?(u.push(`${g} must be a boolean`),o):p}if(s.version!==void 0&&(typeof s.version=="number"&&Number.isFinite(s.version)?a.version=String(s.version):a.version=e(s,"version",a.version,"version")),a.name=e(s,"name",a.name,"name"),s.output!==void 0&&(F(s.output)?(a.output.format=e(s.output,"format",a.output.format,"output.format"),a.output.directory=e(s.output,"directory",a.output.directory,"output.directory"),a.output.combinedReport=i(s.output,"combined_report",a.output.combinedReport,"output.combined_report")):u.push("output must be a mapping")),s.quality_gate!==void 0)if(!F(s.quality_gate))u.push("quality_gate must be a mapping");else{let l=s.quality_gate;if(a.qualityGate.enforced=i(l,"enforced",a.qualityGate.enforced,"quality_gate.enforced"),l.thresholds!==void 0)if(!F(l.thresholds))u.push("quality_gate.thresholds must be a mapping");else{for(let t of["coverage","quality"]){let o=l.thresholds[t];o!==void 0&&(typeof o!="number"||!Number.isFinite(o)||o<0||o>100?u.push(`quality_gate.thresholds.${t} must be a finite number between 0 and 100`):a.qualityGate.thresholds[t]=o)}if(l.thresholds.security!==void 0){let t=l.thresholds.security;typeof t!="string"||!["none","low","medium","high"].includes(t)?u.push("quality_gate.thresholds.security must be none, low, medium or high"):a.qualityGate.thresholds.security=t}}}if(s.phases!==void 0)if(a.phases=[],!Array.isArray(s.phases))u.push("phases must be a sequence");else for(let[l,t]of s.phases.entries()){if(!F(t)){u.push(`Phase ${l+1} must be a mapping`);continue}t.name===void 0&&u.push(`Phase ${l+1} must have a name`);let o=e(t,"name","",`Phase ${l+1} name`),g=["test","coverage","security","quality-gate","code-intelligence","custom"];if(!g.includes(t.type)){u.push(`Phase "${o}" has invalid type "${t.type}". Valid: ${g.join(", ")}`);continue}let p=300;t.timeout!==void 0&&(typeof t.timeout!="number"||!Number.isFinite(t.timeout)||t.timeout<=0?u.push(`Phase "${o}" timeout must be a positive finite number`):p=t.timeout),t.config!==void 0&&!F(t.config)&&u.push(`Phase "${o}" config must be a mapping`),a.phases.push({name:o,type:t.type,timeout:p,enabled:i(t,"enabled",!0,`Phase "${o}" enabled`),continueOnFailure:i(t,"continue_on_failure",!1,`Phase "${o}" continue_on_failure`),config:F(t.config)?{...t.config}:{}})}a.phases.length===0&&u.push("Config must have at least one phase");let c=h.resolve(r?h.dirname(r):process.cwd());function m(l){let t=l,o=[];for(;!R.existsSync(t);){let g=h.dirname(t);if(g===t)break;o.unshift(h.basename(t)),t=g}return h.resolve(R.realpathSync(t),...o)}function b(l,t){if(typeof l!="string"||!l.trim()||l.includes("\0")){u.push(`${t} must be a non-empty relative path`);return}let o=h.resolve(c,l),g=h.relative(c,o);if(h.isAbsolute(l)||h.win32.isAbsolute(l)||g===".."||g.startsWith(`..${h.sep}`)||h.isAbsolute(g)){u.push(`${t} must stay inside the project and use a relative path`);return}try{let p=h.relative(m(c),m(o));if(p===".."||p.startsWith(`..${h.sep}`)||h.isAbsolute(p)){u.push(`${t} must stay inside the project (symlink escapes are not allowed)`);return}}catch(p){u.push(`${t} cannot be resolved safely: ${p}`);return}return r?o:l}a.output.directory=b(a.output.directory,"output.directory")??a.output.directory;for(let l of a.phases)if(l.config.target!==void 0){let t=b(l.config.target,`Phase "${l.name}" config.target`);t!==void 0&&(l.config.target=t)}return u.length>0?{success:!1,config:a,errors:u}:{success:!0,config:a,errors:[],configPath:r}}function M(){return{...E,phases:E.phases.map(n=>({...n,config:{...n.config}})),output:{...E.output},qualityGate:{...E.qualityGate,thresholds:{...E.qualityGate.thresholds}}}}async function oe(n,r,s,u,a){let e=Date.now(),i=[];if(!n.enabled)return{phase:n.name,type:n.type,status:"skipped",duration:0,exitCode:0,summary:"Phase disabled",artifacts:[]};try{let c={},m="passed",b="";switch(n.type){case"test":{let t=await r.kernel.getDomainAPIAsync("test-generation");if(!t)return D(n,e,"failed",1,"Test generation domain not available",i);let o=n.config.target||".",{walkSourceFiles:g}=await import("./file-discovery-TOMDY7TK.js"),p=w.resolve(o),q=g(p,{includeTests:!1}),$=await t.generateTests({sourceFiles:q,testType:n.config.type||"unit",framework:n.config.framework||"vitest",coverageTarget:80});if($.success&&$.value){let C=$.value;c={testsGenerated:C.tests.length,coverageEstimate:C.coverageEstimate},b=`Generated ${C.tests.length} tests (${C.coverageEstimate==null?"coverage unmeasured":`est. ${C.coverageEstimate}% coverage`})`;let y=w.join(s,"test-generation.json");S.writeFileSync(y,k(C),"utf-8"),i.push(y)}else m="failed",b=$.error?.message||"Test generation failed";break}case"coverage":{let t=await r.kernel.getDomainAPIAsync("coverage-analysis");if(!t)return D(n,e,"failed",1,"Coverage analysis domain not available",i);let o=n.config.target||".",g=n.config.threshold||80,{walkSourceFiles:p}=await import("./file-discovery-TOMDY7TK.js"),q=w.resolve(o),$=p(q,{includeTests:!1}),C=Y($),y=await t.analyze({coverageData:C,threshold:g,includeFileDetails:!0});if(y.success&&y.value){let I=y.value;c={...I.summary,meetsThreshold:I.meetsThreshold,threshold:g},m=I.meetsThreshold?"passed":"warning",b=`Line: ${I.summary.line}%, Branch: ${I.summary.branch}% \u2014 ${I.meetsThreshold?"meets":"below"} ${g}% threshold`;let x=w.join(s,"coverage.json");S.writeFileSync(x,k(y.value),"utf-8"),i.push(x)}else m="failed",b=y.error?.message||"Coverage analysis failed";break}case"security":{let t=await r.kernel.getDomainAPIAsync("security-compliance");if(!t)return D(n,e,"failed",1,"Security domain not available",i);let o=n.config.target||".",{walkSourceFiles:g}=await import("./file-discovery-TOMDY7TK.js"),p=w.resolve(o),q=g(p,{includeTests:!0}),$=await t.runSASTScan(q);if($.success&&$.value){let C=$.value,y=C.vulnerabilities||[],I=y.filter(f=>f.severity==="high"||f.severity==="critical").length;c={vulnerabilities:y.length,high:I},m=I>0?"failed":y.length>0?"warning":"passed",b=y.length===0?"No vulnerabilities found":`${y.length} vulnerabilities (${I} high/critical)`;let{toSARIF:x}=await import("./ci-output-FYNKONEQ.js"),G=w.join(s,"security.sarif");S.writeFileSync(G,x({vulnerabilities:y,target:o,scanType:"SAST"}),"utf-8"),i.push(G);let A=w.join(s,"security.json");S.writeFileSync(A,k(C),"utf-8"),i.push(A)}else m="failed",b=$.error?.message||"Security scan failed";break}case"quality-gate":{try{let o=await N(r.kernel.memory),g=Q(o,{coverage:a});c={...g,metrics:o,evidenceStatus:"measured"},m=g.passed?"passed":"failed",b=`Quality gate: ${g.passed?"PASSED":"FAILED"} (${g.checks.filter(p=>p.passed).length}/${g.checks.length} measured checks passed)`}catch(o){m="failed",b=`Quality gate: ${o instanceof Error?o.message:String(o)}`,c={passed:!1,evidenceStatus:"unavailable",error:b,checks:[]}}let t=w.join(s,`quality-gate-${u+1}.json`);S.writeFileSync(t,k(c),"utf-8"),i.push(t);break}case"code-intelligence":{let t=await r.kernel.getDomainAPIAsync("code-intelligence");if(!t)return D(n,e,"failed",1,"Code intelligence domain not available",i);let o=n.config.target||".",{walkSourceFiles:g}=await import("./file-discovery-TOMDY7TK.js"),p=w.resolve(o),q=g(p,{includeTests:!1}),$=await t.index({paths:q,incremental:!0});if($.success&&$.value){let C=$.value;c=C,b=`Indexed ${C.filesIndexed} files, ${C.nodesCreated} nodes`;let y=w.join(s,"code-intelligence.json");S.writeFileSync(y,k(C),"utf-8"),i.push(y)}else m="warning",b=$.error?.message||"Code intelligence indexing incomplete";break}default:b=`Custom phase "${n.name}" \u2014 no built-in handler`,m="warning"}let l=Date.now()-e;return{phase:n.name,type:n.type,status:m,duration:l,exitCode:m==="failed"?1:0,summary:b,artifacts:i,details:c}}catch(c){let m=Date.now()-e;return{phase:n.name,type:n.type,status:"failed",duration:m,exitCode:1,summary:`Error: ${c instanceof Error?c.message:String(c)}`,artifacts:i}}}function D(n,r,s,u,a,e){return{phase:n.name,type:n.type,status:s,duration:Date.now()-r,exitCode:u,summary:a,artifacts:e}}function z(n){let r=`# AQE CI/CD Report
4
4
 
5
5
  `;r+=`**Status:** ${n.overallStatus==="passed"?"PASSED":n.overallStatus==="warning"?"WARNING":"FAILED"}
6
6
  `,r+=`**Duration:** ${(n.duration/1e3).toFixed(1)}s
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
- import{a,b,c,d,e,f,g,h,i,j,k}from"./chunk-4BWDCUZZ.js";import"./chunk-GX5RFGW2.js";export{b as FORMAT_OPTION,c as OUTPUT_OPTION,h as coverageToMarkdown,i as qualityGateToMarkdown,a as securityExecutionStatus,j as securityToMarkdown,k as testRunToMarkdown,e as toJSON,g as toJUnit,f as toSARIF,d as writeOutput};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.2");process.exit(0)}
2
+ import{a,b,c,d,e,f,g,h,i,j,k}from"./chunk-MY2XZHW3.js";import"./chunk-D75HDHX3.js";export{b as FORMAT_OPTION,c as OUTPUT_OPTION,h as coverageToMarkdown,i as qualityGateToMarkdown,a as securityExecutionStatus,j as securityToMarkdown,k as testRunToMarkdown,e as toJSON,g as toJUnit,f as toSARIF,d as writeOutput};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
- import{a,b}from"./chunk-S7QUHLXV.js";import"./chunk-GX5RFGW2.js";export{a as AdvisorCircuitBreaker,b as AdvisorCircuitBreakerError};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.2");process.exit(0)}
2
+ import{a,b}from"./chunk-SVHFSOGT.js";import"./chunk-D75HDHX3.js";export{a as AdvisorCircuitBreaker,b as AdvisorCircuitBreakerError};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
- import{a as g}from"./chunk-KLGFEHEN.js";import{b as p}from"./chunk-PN3FYSQ6.js";import{b as f,d as h}from"./chunk-ATXAMGVE.js";import{a as d,e as v}from"./chunk-X5RELRY7.js";import{a as b}from"./chunk-GX5RFGW2.js";import{existsSync as c,readFileSync as m}from"node:fs";h();v();import{join as a}from"node:path";async function C(t,e){let o=p(t);if(e&&o.available&&console.log(`[ClaudeFlow] Detected via ${o.method}${o.version?`: v${o.version}`:""}`),!o.available)return{available:!1};let r={"mcp-config":"mcp","local-binary":"cli","npx-cached":"cli","npm-dependency":"npm"};return{available:!0,version:o.version,method:o.method?r[o.method]:void 0}}async function F(t){return{trajectories:!0,modelRouting:!0,pretrain:!0,workers:!0,patternSearch:!0}}function S(t,e){return{version:"1.0",projectRoot:t,integration:{enabled:!0,features:{trajectories:e.trajectories,modelRouting:e.modelRouting,pretrain:e.pretrain,workers:e.workers}},learning:{trajectoryStorage:e.trajectories?"claude-flow":"local",patternSearch:e.patternSearch?"claude-flow":"local"},routing:{modelRouting:e.modelRouting?"claude-flow":"rule-based",preferences:{simple:"haiku",standard:"sonnet",complex:"opus"}},pretrain:{enabled:e.pretrain,depth:"medium",autoRun:!0},workers:{enabled:e.workers,autoDispatch:["optimize","consolidate"]}}}function R(t){let e=a(t,".claude","settings.json"),o={};if(c(e))try{o=f(m(e,"utf-8"))}catch{}o.mcpServers||(o.mcpServers={});let r=o.mcpServers;!r.ruflo&&!r["claude-flow"]&&(r.ruflo={command:"npx",args:["ruflo@3.5.18","mcp"],env:{}}),g(e,JSON.stringify(o,null,2))}async function O(t){let{projectRoot:e,force:o,checkOnly:r,debug:s}=t,n=await C(e,s);if(!n.available&&!o)return{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,workers:!1,patternSearch:!1}};let l=await F(e);if(r)return{available:n.available,version:n.version,features:l};let w=a(e,".agentic-qe"),u=a(w,"claude-flow-integration.json");try{let i=S(e,l);g(u,JSON.stringify(i,null,2)),s&&console.log(`[ClaudeFlow] Config written to: ${u}`)}catch(i){return{available:n.available,version:n.version,features:l,error:`Failed to write config: ${d(i)}`}}try{R(e)}catch(i){s&&console.log("[ClaudeFlow] MCP config update failed:",d(i))}return{available:!0,version:n.version,features:l,configPath:u}}function $(t){let e=a(t,".agentic-qe","claude-flow-integration.json");return c(e)}function D(t){let e=a(t,".agentic-qe","claude-flow-integration.json");if(!c(e))return null;try{return f(m(e,"utf-8"))}catch{return null}}function M(t){let e=a(t,".agentic-qe","claude-flow-integration.json");if(c(e))try{return b("node:fs").rmSync(e),!0}catch{return!1}return!0}export{D as getClaudeFlowConfig,$ as isClaudeFlowConfigured,M as removeClaudeFlowIntegration,O as setupClaudeFlowIntegration};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.2");process.exit(0)}
2
+ import{a as g}from"./chunk-QB7H62A4.js";import{b as p}from"./chunk-CRYZXTSQ.js";import{b as f,d as h}from"./chunk-URWT3EQT.js";import{a as d,e as v}from"./chunk-3KTAMNKI.js";import{a as b}from"./chunk-D75HDHX3.js";import{existsSync as c,readFileSync as m}from"node:fs";h();v();import{join as a}from"node:path";async function C(t,e){let o=p(t);if(e&&o.available&&console.log(`[ClaudeFlow] Detected via ${o.method}${o.version?`: v${o.version}`:""}`),!o.available)return{available:!1};let r={"mcp-config":"mcp","local-binary":"cli","npx-cached":"cli","npm-dependency":"npm"};return{available:!0,version:o.version,method:o.method?r[o.method]:void 0}}async function F(t){return{trajectories:!0,modelRouting:!0,pretrain:!0,workers:!0,patternSearch:!0}}function S(t,e){return{version:"1.0",projectRoot:t,integration:{enabled:!0,features:{trajectories:e.trajectories,modelRouting:e.modelRouting,pretrain:e.pretrain,workers:e.workers}},learning:{trajectoryStorage:e.trajectories?"claude-flow":"local",patternSearch:e.patternSearch?"claude-flow":"local"},routing:{modelRouting:e.modelRouting?"claude-flow":"rule-based",preferences:{simple:"haiku",standard:"sonnet",complex:"opus"}},pretrain:{enabled:e.pretrain,depth:"medium",autoRun:!0},workers:{enabled:e.workers,autoDispatch:["optimize","consolidate"]}}}function R(t){let e=a(t,".claude","settings.json"),o={};if(c(e))try{o=f(m(e,"utf-8"))}catch{}o.mcpServers||(o.mcpServers={});let r=o.mcpServers;!r.ruflo&&!r["claude-flow"]&&(r.ruflo={command:"npx",args:["ruflo@3.5.18","mcp"],env:{}}),g(e,JSON.stringify(o,null,2))}async function O(t){let{projectRoot:e,force:o,checkOnly:r,debug:s}=t,n=await C(e,s);if(!n.available&&!o)return{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,workers:!1,patternSearch:!1}};let l=await F(e);if(r)return{available:n.available,version:n.version,features:l};let w=a(e,".agentic-qe"),u=a(w,"claude-flow-integration.json");try{let i=S(e,l);g(u,JSON.stringify(i,null,2)),s&&console.log(`[ClaudeFlow] Config written to: ${u}`)}catch(i){return{available:n.available,version:n.version,features:l,error:`Failed to write config: ${d(i)}`}}try{R(e)}catch(i){s&&console.log("[ClaudeFlow] MCP config update failed:",d(i))}return{available:!0,version:n.version,features:l,configPath:u}}function $(t){let e=a(t,".agentic-qe","claude-flow-integration.json");return c(e)}function D(t){let e=a(t,".agentic-qe","claude-flow-integration.json");if(!c(e))return null;try{return f(m(e,"utf-8"))}catch{return null}}function M(t){let e=a(t,".agentic-qe","claude-flow-integration.json");if(c(e))try{return b("node:fs").rmSync(e),!0}catch{return!1}return!0}export{D as getClaudeFlowConfig,$ as isClaudeFlowConfigured,M as removeClaudeFlowIntegration,O as setupClaudeFlowIntegration};
@@ -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.15.2");process.exit(0)}
2
+ import{c as a,d as b,e as c}from"./chunk-56CE7UO4.js";import"./chunk-HYWW4A2E.js";import"./chunk-3KTAMNKI.js";import"./chunk-D75HDHX3.js";c();export{a as VibiumClientImpl,b as VibiumClientProvider};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
- import{b as f}from"./chunk-LDJ5DZT5.js";import{a as m,e as v}from"./chunk-X5RELRY7.js";import"./chunk-GX5RFGW2.js";v();import{existsSync as s,mkdirSync as p,readFileSync as u,writeFileSync as a}from"fs";import{join as h,dirname as d}from"path";var l=class{projectRoot;overwrite;options;generator;constructor(e){this.projectRoot=e.projectRoot,this.overwrite=e.overwrite??!1,this.options=e,this.generator=f()}async install(){let e={success:!0,mcpConfigured:!1,modeInstalled:!1,errors:[],configPath:"",modePath:""};try{let t=this.generator.generateMcpConfig("cline",{memoryBackend:this.options.memoryBackend}),r=h(this.projectRoot,t.path);if(e.configPath=r,!s(r)||this.overwrite){let o=d(r);if(s(o)||p(o,{recursive:!0}),s(r)&&this.overwrite){let c=this.mergeExistingConfig(r,t.content);a(r,c)}else a(r,t.content);e.mcpConfigured=!0}let n=this.generator.generateBehavioralRules("cline"),i=h(this.projectRoot,n.path);if(e.modePath=i,!s(i)||this.overwrite){let o=d(i);if(s(o)||p(o,{recursive:!0}),s(i)&&this.overwrite){let c=this.mergeExistingModes(i,n.content);a(i,c)}else a(i,n.content);e.modeInstalled=!0}}catch(t){e.success=!1,e.errors.push(`Cline installation failed: ${m(t)}`)}return e}mergeExistingConfig(e,t){try{let r=JSON.parse(u(e,"utf-8")),n=JSON.parse(t);return r.mcpServers||(r.mcpServers={}),Object.assign(r.mcpServers,n.mcpServers),JSON.stringify(r,null,2)+`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.2");process.exit(0)}
2
+ import{b as f}from"./chunk-HOBBYORR.js";import{a as m,e as v}from"./chunk-3KTAMNKI.js";import"./chunk-D75HDHX3.js";v();import{existsSync as s,mkdirSync as p,readFileSync as u,writeFileSync as a}from"fs";import{join as h,dirname as d}from"path";var l=class{projectRoot;overwrite;options;generator;constructor(e){this.projectRoot=e.projectRoot,this.overwrite=e.overwrite??!1,this.options=e,this.generator=f()}async install(){let e={success:!0,mcpConfigured:!1,modeInstalled:!1,errors:[],configPath:"",modePath:""};try{let t=this.generator.generateMcpConfig("cline",{memoryBackend:this.options.memoryBackend}),r=h(this.projectRoot,t.path);if(e.configPath=r,!s(r)||this.overwrite){let o=d(r);if(s(o)||p(o,{recursive:!0}),s(r)&&this.overwrite){let c=this.mergeExistingConfig(r,t.content);a(r,c)}else a(r,t.content);e.mcpConfigured=!0}let n=this.generator.generateBehavioralRules("cline"),i=h(this.projectRoot,n.path);if(e.modePath=i,!s(i)||this.overwrite){let o=d(i);if(s(o)||p(o,{recursive:!0}),s(i)&&this.overwrite){let c=this.mergeExistingModes(i,n.content);a(i,c)}else a(i,n.content);e.modeInstalled=!0}}catch(t){e.success=!1,e.errors.push(`Cline installation failed: ${m(t)}`)}return e}mergeExistingConfig(e,t){try{let r=JSON.parse(u(e,"utf-8")),n=JSON.parse(t);return r.mcpServers||(r.mcpServers={}),Object.assign(r.mcpServers,n.mcpServers),JSON.stringify(r,null,2)+`
3
3
  `}catch{return t}}mergeExistingModes(e,t){try{let r=JSON.parse(u(e,"utf-8")),n=JSON.parse(t);if(!Array.isArray(r))return t;let i=r.filter(o=>o.slug!=="qe-engineer");return i.push(...n),JSON.stringify(i,null,2)+`
4
4
  `}catch{return t}}};function x(g){return new l(g)}export{l as ClineInstaller,x as createClineInstaller};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
- import{a as T,b as I}from"./chunk-M5EKZA7Q.js";import{d as $,e as C}from"./chunk-4BWDCUZZ.js";import"./chunk-GX5RFGW2.js";import{Command as z}from"commander";import e from"chalk";function O(A,y,P){return new z("code").description("Code intelligence analysis").argument("<action>","Action (index|search|impact|deps|complexity|c4)").argument("[target]","Target path or query").option("--depth <depth>","Analysis depth","3").option("--include-tests","Include test files").option("--incremental","Incremental indexing (index action only)").option("--git-since <ref>","Index changes since git ref (index action only)").option("--level <level>","C4 level for c4 action (context|container|component|all)","all").option("-F, --format <format>","Output format (text|json)","text").option("-o, --output <path>","Write output to file").addHelpText("after",`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.2");process.exit(0)}
2
+ import{a as T,b as I}from"./chunk-RO6HAZLV.js";import{d as $,e as C}from"./chunk-MY2XZHW3.js";import"./chunk-D75HDHX3.js";import{Command as z}from"commander";import e from"chalk";function O(A,y,P){return new z("code").description("Code intelligence analysis").argument("<action>","Action (index|search|impact|deps|complexity|c4)").argument("[target]","Target path or query").option("--depth <depth>","Analysis depth","3").option("--include-tests","Include test files").option("--incremental","Incremental indexing (index action only)").option("--git-since <ref>","Index changes since git ref (index action only)").option("--level <level>","C4 level for c4 action (context|container|component|all)","all").option("-F, --format <format>","Output format (text|json)","text").option("-o, --output <path>","Write output to file").addHelpText("after",`
3
3
  Examples:
4
4
  aqe code index src/ Index source files into knowledge graph
5
5
  aqe code index src/ --incremental Incremental index (only changed files)
@@ -13,7 +13,7 @@ Examples:
13
13
  aqe code c4 . --format json -o c4.json Full C4 result as JSON
14
14
  `).action(async(b,m,c)=>{if(await P())try{let u=await A.kernel.getDomainAPIAsync("code-intelligence");if(!u){console.log(e.red("Code intelligence domain not available"));return}let v=await import("path"),D=c.format||"text",F=parseInt(c.depth);if(isNaN(F)||F<1){console.log(e.red(`Invalid --depth value: "${c.depth}" (must be a positive integer)`));return}if(b==="index"){let g=c.incremental||!1,l=c.gitSince,r=g?"Incrementally indexing":"Indexing";console.log(e.blue(`
15
15
  ${r} codebase at ${m||"."}${l?` (since ${l})`:""}...
16
- `));let n=v.resolve(m||"."),a;if(l){let{getGitRefError:t}=await import("./ref-validation-EUATPVXX.js"),d=t(l,"--git-since ref");if(d)return console.log(e.red(d)),await y(1);let{execFileSync:f}=await import("child_process");try{let h=f("git",["diff","--name-only","--diff-filter=ACMR",l,"--",n],{encoding:"utf-8",cwd:process.cwd()}).trim();a=h?h.split(`
16
+ `));let n=v.resolve(m||"."),a;if(l){let{getGitRefError:t}=await import("./ref-validation-MSFMNKDR.js"),d=t(l,"--git-since ref");if(d)return console.log(e.red(d)),await y(1);let{execFileSync:f}=await import("child_process");try{let h=f("git",["diff","--name-only","--diff-filter=ACMR",l,"--",n],{encoding:"utf-8",cwd:process.cwd()}).trim();a=h?h.split(`
17
17
  `).filter(p=>T.has(v.extname(p))).map(p=>v.resolve(p)):[]}catch{console.log(e.yellow(` Warning: git diff failed for ref "${l}", falling back to full scan`)),a=I(n,{includeTests:c.includeTests||!1})}}else a=I(n,{includeTests:c.includeTests||!1});console.log(e.gray(` Found ${a.length} files to index...
18
18
  `));let o=await u.index({paths:a,incremental:g,includeTests:c.includeTests||!1});if(o.success&&o.value){let t=o.value;if(D==="json")$(C(t),c.output);else{if(console.log(e.green(`Indexing complete
19
19
  `)),console.log(e.cyan(" Results:")),console.log(` Files indexed: ${e.white(t.filesIndexed)}`),console.log(` Nodes created: ${e.white(t.nodesCreated)}`),console.log(` Edges created: ${e.white(t.edgesCreated)}`),console.log(` Duration: ${e.yellow(t.duration+"ms")}`),t.warnings&&t.warnings.length>0){console.log(e.yellow(`
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
- import"./chunk-GX5RFGW2.js";import{readFile as m}from"fs/promises";var d=new Set(["if","for","while","switch","catch","return","new","throw","import","export","constructor"]),h=50;function x(o,c){let n=c.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.15.2");process.exit(0)}
2
+ import"./chunk-D75HDHX3.js";import{readFile as m}from"fs/promises";var d=new Set(["if","for","while","switch","catch","return","new","throw","import","export","constructor"]),h=50;function x(o,c){let n=c.split(`
3
3
  `),e=[],i=[];for(let t=0;t<n.length;t++){let s=n[t],a=s.match(/(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+(\w+)/);if(a){e.push({type:"function",name:a[1],lineStart:t+1});continue}let l=s.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[a-zA-Z_]\w*)\s*(?::\s*[^=]+)?\s*=>/);if(l){e.push({type:"function",name:l[1],lineStart:t+1});continue}let u=s.match(/(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+(\w+)/);if(u){e.push({type:"class",name:u[1],lineStart:t+1});continue}let f=s.match(/(?:export\s+)?interface\s+(\w+)/);if(f){e.push({type:"interface",name:f[1],lineStart:t+1});continue}let r=s.match(/^\s+(?:(?:public|private|protected|static|readonly|override|abstract|async)\s+)*(\w+)\s*(?:<[^>]*>)?\s*\([^)]*\)\s*(?::\s*[^{]+)?\s*\{?\s*$/);if(r&&!d.has(r[1])){e.push({type:"function",name:r[1],lineStart:t+1});continue}let p=s.match(/(?:import|from)\s+['"](\.[^'"]+)['"]/);p&&i.push(p[1])}return{path:o,entities:e,imports:i}}async function y(o){let c=[];for(let n=0;n<o.length;n+=h){let e=o.slice(n,n+h),i=await Promise.allSettled(e.map(async t=>{let s=await m(t,"utf-8");return x(t,s)}));for(let t of i)t.status==="fulfilled"&&c.push(t.value)}return{files:c}}export{y as extractCodeIndex};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
- import{a as N}from"./chunk-J46XGXPS.js";import{a as P}from"./chunk-KLGFEHEN.js";import{a as j}from"./chunk-OLD2CIDI.js";import{b as I}from"./chunk-LDJ5DZT5.js";import"./chunk-ATXAMGVE.js";import{a as b,e as B}from"./chunk-X5RELRY7.js";import"./chunk-GX5RFGW2.js";B();import{copyFileSync as E,existsSync as l,mkdirSync as k,readFileSync as v,readdirSync as G,statSync as w,writeFileSync as C}from"fs";import{join as n,dirname as S}from"path";import{fileURLToPath as $}from"url";var U=512,D=`# Agentic QE
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.2");process.exit(0)}
2
+ import{a as N}from"./chunk-NP2WWIZ3.js";import{a as P}from"./chunk-QB7H62A4.js";import{a as j}from"./chunk-B4H66LPR.js";import{b as I}from"./chunk-HOBBYORR.js";import"./chunk-URWT3EQT.js";import{a as b,e as B}from"./chunk-3KTAMNKI.js";import"./chunk-D75HDHX3.js";B();import{copyFileSync as E,existsSync as l,mkdirSync as k,readFileSync as v,readdirSync as G,statSync as w,writeFileSync as C}from"fs";import{join as n,dirname as S}from"path";import{fileURLToPath as $}from"url";var U=512,D=`# Agentic QE
3
3
 
4
4
  Preserve project data, especially .agentic-qe/memory.db. Read affected code and tests before editing, validate inputs at system boundaries, and run focused checks before broader gates. Discover AQE tools and skills from their live schemas.`,O=class y{projectRoot;overwrite;options;generator;static AGENTS_START="<!-- BEGIN AGENTIC-QE CODEX -->";static AGENTS_END="<!-- END AGENTIC-QE CODEX -->";constructor(e){this.projectRoot=e.projectRoot,this.overwrite=e.overwrite??!1,this.options=e,this.generator=I()}async install(){let e={success:!0,mcpConfigured:!1,agentsMdInstalled:!1,hooksConfigured:!1,skillsInstalled:0,errors:[],configPath:"",agentsMdPath:"",hooksPath:n(this.projectRoot,".codex","hooks.json"),skillsPath:n(this.projectRoot,".agents","skills"),guidancePolicy:this.options.guidancePolicy??"full",ownedGuidanceBytes:0,components:{mcp:{status:"skipped"},rules:{status:"skipped"},hooks:{status:"unavailable"},skills:{status:"unavailable"}}};try{let t=this.generator.generateMcpConfig("codex",{memoryBackend:this.options.memoryBackend}),s=n(this.projectRoot,t.path);e.configPath=s;let o=l(s);if(this.options.installMcp!==!1&&(!o||this.overwrite)){let r=S(s);if(l(r)||k(r,{recursive:!0}),l(s)&&this.overwrite){let c=this.mergeExistingTomlConfig(s,t.content);C(s,c)}else C(s,t.content);e.mcpConfigured=!0,e.components.mcp.status=o?"updated":"installed"}else this.options.installMcp!==!1&&o&&(e.components.mcp.status="preserved")}catch(t){this.recordComponentFailure(e,"mcp",t)}try{let t=this.options.guidancePolicy??"full",s=this.generator.generateBehavioralRules("codex"),o=n(this.projectRoot,s.path);e.agentsMdPath=o;let r=l(o);if(t==="none")if(!r)e.components.rules.status="skipped";else{let c=v(o,"utf-8"),i=this.removeOwnedAgentsSections(c);i!==c?(C(o,i),e.components.rules.status="updated"):e.components.rules.status="preserved"}else if(r){let c=t==="compact"?D:s.content,i=v(o,"utf-8"),d=this.mergeExistingAgentsMdContent(i,c);d!==i?(C(o,d),e.agentsMdInstalled=!0,e.components.rules.status="updated"):e.components.rules.status="preserved",e.ownedGuidanceBytes=this.measureOwnedAgentsSection(d)}else{let c=t==="compact"?D:s.content,i=this.markAgentsSection(c);C(o,i),e.agentsMdInstalled=!0,e.ownedGuidanceBytes=Buffer.byteLength(i),e.components.rules.status="installed"}}catch(t){this.recordComponentFailure(e,"rules",t)}try{e.components.hooks.status=this.installCodexHooks(e)}catch(t){this.recordComponentFailure(e,"hooks",t)}try{let t=this.installCodexSkills();e.skillsInstalled=t.count,e.components.skills.status=t.status}catch(t){this.recordComponentFailure(e,"skills",t)}for(let t of["hooks","skills"])if(e.components[t].status==="unavailable"){let s=`Codex ${t} unavailable: packaged assets could not be located`;e.components[t].error=s,e.errors.push(s)}return e.success=e.errors.length===0,e}recordComponentFailure(e,t,s){let o=b(s);e.components[t]={status:"failed",error:o},e.errors.push(`Codex ${t} installation failed: ${o}`)}installCodexHooks(e){let t=this.resolvePackageRoot();if(!t)return"unavailable";let s=n(t,".codex","hooks.json"),o=n(t,".codex","hooks");if(!l(s)||!l(o))return"unavailable";let r=n(this.projectRoot,".codex"),c=n(r,"hooks");k(c,{recursive:!0});for(let a of G(o)){if(!this.options.includeRuflo&&a==="ruflo-codex-hook.cjs")continue;let u=n(o,a);if(!w(u).isFile())continue;let f=n(c,a);(!l(f)||this.overwrite)&&E(u,f)}let i=[{source:n(t,".claude","hooks","aqe-hook.cjs"),target:n(c,"aqe-runtime.cjs")},...this.options.includeRuflo?[{source:n(t,".claude","helpers","ruflo-hook.cjs"),target:n(c,"ruflo-runtime.cjs")}]:[]];for(let a of i)l(a.source)&&(!l(a.target)||this.overwrite)&&E(a.source,a.target);let d=JSON.parse(v(s,"utf-8")),g=a=>a.flatMap(u=>{if(!u||typeof u!="object")return[u];let f=u;if(!Array.isArray(f.hooks))return JSON.stringify(u).includes("ruflo-codex-hook.cjs")?[]:[u];let R=f.hooks.filter(F=>!JSON.stringify(F).includes("ruflo-codex-hook.cjs"));return R.length>0?[{...f,hooks:R}]:[]}),h={...d,hooks:Object.fromEntries(Object.entries(d.hooks||{}).map(([a,u])=>[a,this.options.includeRuflo?u:g(u)]))},p=n(r,"hooks.json");if(!l(p))return C(p,JSON.stringify(h,null,2)+`
5
5
  `),e.hooksConfigured=!0,"installed";let m=JSON.parse(v(p,"utf-8")),x=a=>JSON.stringify(a).includes("/.codex/hooks/aqe-codex-hook.cjs")||JSON.stringify(a).includes("/.codex/hooks/ruflo-codex-hook.cjs"),A={},T=new Set([...Object.keys(m.hooks||{}),...Object.keys(h.hooks||{})]);for(let a of T){let u=(m.hooks?.[a]||[]).filter(f=>!x(f));A[a]=[...u,...h.hooks?.[a]||[]]}let M=P(p,JSON.stringify({...m,description:h.description,hooks:A},null,2)+`
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
- import"./chunk-GX5RFGW2.js";import{Command as v}from"commander";import o from"chalk";var c=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"],a=["qe-tdd-specialist","qe-test-architect","qe-parallel-executor","qe-flaky-hunter","qe-retry-handler","qe-coverage-specialist","qe-gap-detector","qe-quality-gate","qe-deployment-advisor","qe-code-complexity","qe-qx-partner","qe-security-scanner","qe-security-auditor","qe-contract-validator","qe-integration-tester","qe-graphql-tester","qe-visual-tester","qe-accessibility-auditor","qe-responsive-tester","qe-performance-tester","qe-load-tester","qe-chaos-engineer","qe-code-intelligence","qe-dependency-mapper","qe-kg-builder","qe-requirements-validator","qe-bdd-generator","qe-defect-predictor","qe-root-cause-analyzer","qe-regression-analyzer","qe-impact-analyzer","qe-risk-assessor","qe-learning-coordinator","qe-pattern-learner","qe-transfer-specialist","qe-metrics-optimizer","qe-fleet-commander","qe-queen-coordinator","qe-property-tester","qe-mutation-tester","qe-tdd-red","qe-tdd-green","qe-tdd-refactor","qe-code-reviewer","qe-integration-reviewer","qe-performance-reviewer","qe-security-reviewer"],i=["tester","reviewer","security-auditor","security-architect","performance-engineer","code-analyzer","cicd-engineer","reasoningbank-learner","adr-architect","ddd-domain-expert","v3-integration-architect","memory-specialist","claims-authorizer","sparc-orchestrator","sona-learning-optimizer","safla-neural","production-validator","tdd-london-swarm","queen-coordinator","swarm-memory-manager","worker-specialist","collective-intelligence-coordinator","scout-explorer","adaptive-coordinator","mesh-coordinator","hierarchical-coordinator","consensus-coordinator","byzantine-coordinator","raft-manager","crdt-synchronizer","n8n-workflow-executor","n8n-unit-tester","n8n-integration-test","n8n-trigger-test","n8n-security-auditor"],P=[...a,...i];var p=["generate-tests","execute-tests","analyze-coverage","assess-quality","predict-defects","validate-requirements","analyze-code","scan-security","validate-contracts","test-accessibility","chaos-test","optimize-learning"],b=["p0","p1","p2","p3"],y=["pending","running","completed","failed","cancelled"],d=["jest","vitest","pytest","junit","playwright","cypress","go-test","node-test"],w=["unit","integration","e2e"],C=["sqlite","agentdb","hybrid"];function q(){return`#!/bin/bash
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.2");process.exit(0)}
2
+ import"./chunk-D75HDHX3.js";import{Command as v}from"commander";import o from"chalk";var c=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"],a=["qe-tdd-specialist","qe-test-architect","qe-parallel-executor","qe-flaky-hunter","qe-retry-handler","qe-coverage-specialist","qe-gap-detector","qe-quality-gate","qe-deployment-advisor","qe-code-complexity","qe-qx-partner","qe-security-scanner","qe-security-auditor","qe-contract-validator","qe-integration-tester","qe-graphql-tester","qe-visual-tester","qe-accessibility-auditor","qe-responsive-tester","qe-performance-tester","qe-load-tester","qe-chaos-engineer","qe-code-intelligence","qe-dependency-mapper","qe-kg-builder","qe-requirements-validator","qe-bdd-generator","qe-defect-predictor","qe-root-cause-analyzer","qe-regression-analyzer","qe-impact-analyzer","qe-risk-assessor","qe-learning-coordinator","qe-pattern-learner","qe-transfer-specialist","qe-metrics-optimizer","qe-fleet-commander","qe-queen-coordinator","qe-property-tester","qe-mutation-tester","qe-tdd-red","qe-tdd-green","qe-tdd-refactor","qe-code-reviewer","qe-integration-reviewer","qe-performance-reviewer","qe-security-reviewer"],i=["tester","reviewer","security-auditor","security-architect","performance-engineer","code-analyzer","cicd-engineer","reasoningbank-learner","adr-architect","ddd-domain-expert","v3-integration-architect","memory-specialist","claims-authorizer","sparc-orchestrator","sona-learning-optimizer","safla-neural","production-validator","tdd-london-swarm","queen-coordinator","swarm-memory-manager","worker-specialist","collective-intelligence-coordinator","scout-explorer","adaptive-coordinator","mesh-coordinator","hierarchical-coordinator","consensus-coordinator","byzantine-coordinator","raft-manager","crdt-synchronizer","n8n-workflow-executor","n8n-unit-tester","n8n-integration-test","n8n-trigger-test","n8n-security-auditor"],P=[...a,...i];var p=["generate-tests","execute-tests","analyze-coverage","assess-quality","predict-defects","validate-requirements","analyze-code","scan-security","validate-contracts","test-accessibility","chaos-test","optimize-learning"],b=["p0","p1","p2","p3"],y=["pending","running","completed","failed","cancelled"],d=["jest","vitest","pytest","junit","playwright","cypress","go-test","node-test"],w=["unit","integration","e2e"],C=["sqlite","agentdb","hybrid"];function q(){return`#!/bin/bash
3
3
  # AQE CLI Bash Completion Script
4
4
  # Generated by aqe completions bash
5
5
  # ADR-041: Shell Completions for Enhanced Developer Experience
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
- import{a,b,c,d,e,f,g,h,i}from"./chunk-LLS6JYPN.js";import"./chunk-Y63DADOR.js";import"./chunk-3Y24VTZ3.js";import"./chunk-H77AUJNW.js";import"./chunk-GX5RFGW2.js";export{g as ComplexityAnalyzer,c as ScoreCalculator,a as SignalCollector,e as TierRecommender,h as createComplexityAnalyzer,i as createComplexityAnalyzerWithDependencies,d as createScoreCalculator,b as createSignalCollector,f as createTierRecommender};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.2");process.exit(0)}
2
+ import{a,b,c,d,e,f,g,h,i}from"./chunk-EDRIROCG.js";import"./chunk-V67UQRQN.js";import"./chunk-GJTH6VBH.js";import"./chunk-CFDIYZGA.js";import"./chunk-D75HDHX3.js";export{g as ComplexityAnalyzer,c as ScoreCalculator,a as SignalCollector,e as TierRecommender,h as createComplexityAnalyzer,i as createComplexityAnalyzerWithDependencies,d as createScoreCalculator,b as createSignalCollector,f as createTierRecommender};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
- import{b as m}from"./chunk-LDJ5DZT5.js";import{a as u,e as h}from"./chunk-X5RELRY7.js";import"./chunk-GX5RFGW2.js";h();import{existsSync as i,mkdirSync as g,readFileSync as d,writeFileSync as a}from"fs";import{join as f,dirname as p}from"path";var c=class{projectRoot;overwrite;options;generator;constructor(e){this.projectRoot=e.projectRoot,this.overwrite=e.overwrite??!1,this.options=e,this.generator=m()}async install(){let e={success:!0,mcpConfigured:!1,rulesInstalled:!1,errors:[],configPath:"",rulesPath:""};try{let r=this.generator.generateMcpConfig("continuedev",{memoryBackend:this.options.memoryBackend}),t=f(this.projectRoot,r.path);if(e.configPath=t,!i(t)||this.overwrite){let o=p(t);if(i(o)||g(o,{recursive:!0}),i(t)&&this.overwrite){let v=this.mergeExistingYamlConfig(t,r.content);a(t,v)}else a(t,r.content);e.mcpConfigured=!0}let s=this.generator.generateBehavioralRules("continuedev"),n=f(this.projectRoot,s.path);if(e.rulesPath=n,!i(n)||this.overwrite){let o=p(n);i(o)||g(o,{recursive:!0}),a(n,s.content),e.rulesInstalled=!0}}catch(r){e.success=!1,e.errors.push(`Continue.dev installation failed: ${u(r)}`)}return e}mergeExistingYamlConfig(e,r){try{let t=d(e,"utf-8");if(t.includes("agentic-qe"))return t;if(t.includes("mcpServers:")){let n=` - name: agentic-qe
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.2");process.exit(0)}
2
+ import{b as m}from"./chunk-HOBBYORR.js";import{a as u,e as h}from"./chunk-3KTAMNKI.js";import"./chunk-D75HDHX3.js";h();import{existsSync as i,mkdirSync as g,readFileSync as d,writeFileSync as a}from"fs";import{join as f,dirname as p}from"path";var c=class{projectRoot;overwrite;options;generator;constructor(e){this.projectRoot=e.projectRoot,this.overwrite=e.overwrite??!1,this.options=e,this.generator=m()}async install(){let e={success:!0,mcpConfigured:!1,rulesInstalled:!1,errors:[],configPath:"",rulesPath:""};try{let r=this.generator.generateMcpConfig("continuedev",{memoryBackend:this.options.memoryBackend}),t=f(this.projectRoot,r.path);if(e.configPath=t,!i(t)||this.overwrite){let o=p(t);if(i(o)||g(o,{recursive:!0}),i(t)&&this.overwrite){let v=this.mergeExistingYamlConfig(t,r.content);a(t,v)}else a(t,r.content);e.mcpConfigured=!0}let s=this.generator.generateBehavioralRules("continuedev"),n=f(this.projectRoot,s.path);if(e.rulesPath=n,!i(n)||this.overwrite){let o=p(n);i(o)||g(o,{recursive:!0}),a(n,s.content),e.rulesInstalled=!0}}catch(r){e.success=!1,e.errors.push(`Continue.dev installation failed: ${u(r)}`)}return e}mergeExistingYamlConfig(e,r){try{let t=d(e,"utf-8");if(t.includes("agentic-qe"))return t;if(t.includes("mcpServers:")){let n=` - name: agentic-qe
3
3
  command: npx
4
4
  args:
5
5
  - "-y"
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
- import{b as g}from"./chunk-LDJ5DZT5.js";import{a as p,e as v}from"./chunk-X5RELRY7.js";import"./chunk-GX5RFGW2.js";v();import{existsSync as s,mkdirSync as f,readFileSync as C,writeFileSync as l}from"fs";import{join as u,dirname as m}from"path";var a=class{projectRoot;overwrite;options;generator;constructor(t){this.projectRoot=t.projectRoot,this.overwrite=t.overwrite??!1,this.options=t,this.generator=g()}async install(){let t={success:!0,mcpConfigured:!1,rulesInstalled:!1,errors:[],configPath:"",rulesPath:""};try{let r=this.generator.generateMcpConfig("copilot",{memoryBackend:this.options.memoryBackend}),e=u(this.projectRoot,r.path);if(t.configPath=e,!s(e)||this.overwrite){let o=m(e);if(s(o)||f(o,{recursive:!0}),s(e)&&this.overwrite){let h=this.mergeExistingConfig(e,r.content);l(e,h)}else l(e,r.content);t.mcpConfigured=!0}let i=this.generator.generateBehavioralRules("copilot"),n=u(this.projectRoot,i.path);if(t.rulesPath=n,!s(n)||this.overwrite){let o=m(n);s(o)||f(o,{recursive:!0}),l(n,i.content),t.rulesInstalled=!0}}catch(r){t.success=!1,t.errors.push(`Copilot installation failed: ${p(r)}`)}return t}mergeExistingConfig(t,r){try{let e=JSON.parse(C(t,"utf-8")),i=JSON.parse(r);return e.servers||(e.servers={}),Object.assign(e.servers,i.servers),JSON.stringify(e,null,2)+`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.2");process.exit(0)}
2
+ import{b as g}from"./chunk-HOBBYORR.js";import{a as p,e as v}from"./chunk-3KTAMNKI.js";import"./chunk-D75HDHX3.js";v();import{existsSync as s,mkdirSync as f,readFileSync as C,writeFileSync as l}from"fs";import{join as u,dirname as m}from"path";var a=class{projectRoot;overwrite;options;generator;constructor(t){this.projectRoot=t.projectRoot,this.overwrite=t.overwrite??!1,this.options=t,this.generator=g()}async install(){let t={success:!0,mcpConfigured:!1,rulesInstalled:!1,errors:[],configPath:"",rulesPath:""};try{let r=this.generator.generateMcpConfig("copilot",{memoryBackend:this.options.memoryBackend}),e=u(this.projectRoot,r.path);if(t.configPath=e,!s(e)||this.overwrite){let o=m(e);if(s(o)||f(o,{recursive:!0}),s(e)&&this.overwrite){let h=this.mergeExistingConfig(e,r.content);l(e,h)}else l(e,r.content);t.mcpConfigured=!0}let i=this.generator.generateBehavioralRules("copilot"),n=u(this.projectRoot,i.path);if(t.rulesPath=n,!s(n)||this.overwrite){let o=m(n);s(o)||f(o,{recursive:!0}),l(n,i.content),t.rulesInstalled=!0}}catch(r){t.success=!1,t.errors.push(`Copilot installation failed: ${p(r)}`)}return t}mergeExistingConfig(t,r){try{let e=JSON.parse(C(t,"utf-8")),i=JSON.parse(r);return e.servers||(e.servers={}),Object.assign(e.servers,i.servers),JSON.stringify(e,null,2)+`
3
3
  `}catch{return r}}};function R(c){return new a(c)}export{a as CopilotInstaller,R as createCopilotInstaller};