agentic-qe 3.14.7 → 3.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (428) hide show
  1. package/.claude/helpers/.helpers-version +1 -1
  2. package/.claude/helpers/auto-memory-hook.mjs +18 -9
  3. package/.claude/helpers/helpers.manifest.json +6 -5
  4. package/.claude/helpers/hook-handler.cjs +40 -12
  5. package/.claude/helpers/memory.cjs +86 -0
  6. package/.claude/helpers/router.cjs +105 -0
  7. package/.claude/helpers/session.cjs +166 -0
  8. package/.claude/helpers/statusline.cjs +73 -621
  9. package/.claude/skills/release/SKILL.md +6 -0
  10. package/.claude/skills/skills-manifest.json +1 -1
  11. package/CHANGELOG.md +275 -0
  12. package/README.md +143 -366
  13. package/assets/readme/credit-ruflo.svg +1 -0
  14. package/assets/readme/credit-ruvector.svg +1 -0
  15. package/assets/readme/project-header.svg +1 -0
  16. package/assets/readme/quality-loop.svg +1 -0
  17. package/assets/skills/skills-manifest.json +1 -1
  18. package/dist/adapters/a2a/notifications/retry-queue.js +10 -1
  19. package/dist/adapters/ag-ui/json-patch.js +14 -7
  20. package/dist/adapters/ag-ui/state-delta-cache.js +20 -12
  21. package/dist/adapters/claude-flow/pretrain-bridge.js +3 -2
  22. package/dist/agents/claim-verifier/verifiers/file-verifier.js +3 -2
  23. package/dist/cli/bundle.js +6 -6
  24. package/dist/cli/chunks/adapter-D7G5MIDQ.js +2 -0
  25. package/dist/cli/chunks/{agent-booster-wasm-AK2W76RG.js → agent-booster-wasm-GDHJ6QUN.js} +2 -2
  26. package/dist/cli/chunks/{agent-handler-MGZCWHIY.js → agent-handler-MPYYQ2RZ.js} +2 -2
  27. package/dist/cli/chunks/{agent-memory-branch-JZ54MCSP.js → agent-memory-branch-QBSHKLA2.js} +2 -2
  28. package/dist/cli/chunks/aqe-learning-engine-G6TUFGHC.js +2 -0
  29. package/dist/cli/chunks/{arena-YSWTKBCL.js → arena-UJE2FROF.js} +4 -4
  30. package/dist/cli/chunks/{arena-CUVH3V7H.js → arena-WIGSL37B.js} +2 -2
  31. package/dist/cli/chunks/{audit-LVU76QGA.js → audit-VT7Y2Z7V.js} +3 -3
  32. package/dist/cli/chunks/base-B45BOC7E.js +2 -0
  33. package/dist/cli/chunks/{better-sqlite3-DB3LOJQU.js → better-sqlite3-DSL7LFRK.js} +2 -2
  34. package/dist/cli/chunks/{brain-handler-SD63KOQ6.js → brain-handler-N3C2MDMK.js} +4 -4
  35. package/dist/cli/chunks/{branch-enumerator-4MNOPUC7.js → branch-enumerator-B6NSQ3PZ.js} +2 -2
  36. package/dist/cli/chunks/{browser-OLPNTWQE.js → browser-KQ3YNRGW.js} +2 -2
  37. package/dist/cli/chunks/browser-workflow-MIBU4XMV.js +2 -0
  38. package/dist/cli/chunks/{chunk-ZWEKAEEV.js → chunk-2ORTL5WG.js} +1 -1
  39. package/dist/cli/chunks/{chunk-KD2BLA5Y.js → chunk-2ZEV3O24.js} +1 -1
  40. package/dist/cli/chunks/{chunk-25P6JA6V.js → chunk-32YSI6OT.js} +1 -1
  41. package/dist/cli/chunks/{chunk-A5MA7A23.js → chunk-3DKYBHNA.js} +6 -6
  42. package/dist/cli/chunks/{chunk-JOZ47MV6.js → chunk-3Y24VTZ3.js} +1 -1
  43. package/dist/cli/chunks/{chunk-2G63VIJE.js → chunk-4BWDCUZZ.js} +1 -1
  44. package/dist/cli/chunks/{chunk-36VKMAMN.js → chunk-4DCDIKBX.js} +2 -2
  45. package/dist/cli/chunks/chunk-4EEY23JS.js +4 -0
  46. package/dist/cli/chunks/{chunk-BD7FEUN3.js → chunk-4FOKHGP5.js} +3 -3
  47. package/dist/cli/chunks/{chunk-MQZ53OR3.js → chunk-4OQSAUKR.js} +2 -2
  48. package/dist/cli/chunks/{chunk-EYXE2XKP.js → chunk-4YPL3OXS.js} +2 -2
  49. package/dist/cli/chunks/{chunk-PCJQCEBA.js → chunk-5DJGP4TA.js} +2 -2
  50. package/dist/cli/chunks/{chunk-RC2A4JZ5.js → chunk-5KN4QL3G.js} +2 -2
  51. package/dist/cli/chunks/chunk-5LN7FQZI.js +2 -0
  52. package/dist/cli/chunks/{chunk-LU2EDWQK.js → chunk-5PNRUMRV.js} +2 -2
  53. package/dist/cli/chunks/{chunk-YRHTQZU4.js → chunk-62IEVKN3.js} +2 -2
  54. package/dist/cli/chunks/{chunk-DOBKEXMJ.js → chunk-6GTIJNRO.js} +1 -1
  55. package/dist/cli/chunks/{chunk-O5V7RHVG.js → chunk-6MN4L6BS.js} +2 -2
  56. package/dist/cli/chunks/{chunk-6PJPQGF4.js → chunk-7D6NVIGP.js} +6 -6
  57. package/dist/cli/chunks/{chunk-B2YGVSOP.js → chunk-7JABIXP3.js} +2 -2
  58. package/dist/cli/chunks/chunk-7JC3LHA6.js +742 -0
  59. package/dist/cli/chunks/{chunk-P7XSPP5D.js → chunk-7WUHVGGT.js} +2 -2
  60. package/dist/cli/chunks/{chunk-RKI3IQKQ.js → chunk-A37YYHUD.js} +3 -3
  61. package/dist/cli/chunks/{chunk-UBJG3IHT.js → chunk-AAQNRZKT.js} +2 -2
  62. package/dist/cli/chunks/{chunk-ND4QTZOL.js → chunk-AGYPPPXR.js} +2 -2
  63. package/dist/cli/chunks/chunk-AIE6OKCD.js +2 -0
  64. package/dist/cli/chunks/{chunk-JHJUSSAU.js → chunk-ANUZGOLQ.js} +2 -2
  65. package/dist/cli/chunks/{chunk-RLW25X66.js → chunk-AQZSF32Y.js} +2 -2
  66. package/dist/cli/chunks/{chunk-OIDWDGLG.js → chunk-ATXAMGVE.js} +2 -2
  67. package/dist/cli/chunks/{chunk-GLGKQX2V.js → chunk-AV3RX2L5.js} +2 -2
  68. package/dist/cli/chunks/{chunk-7QYOTUOX.js → chunk-AW5OWYQ4.js} +2 -2
  69. package/dist/cli/chunks/{chunk-B4I43GE2.js → chunk-B6QTNTCU.js} +2 -2
  70. package/dist/cli/chunks/{chunk-P2UPYSDJ.js → chunk-BAPMEDWC.js} +1 -1
  71. package/dist/cli/chunks/{chunk-Y6AKKQIQ.js → chunk-BH2SQQ2N.js} +1 -1
  72. package/dist/cli/chunks/{chunk-O6MO5KMR.js → chunk-C6M27NQE.js} +2 -2
  73. package/dist/cli/chunks/{chunk-XBYQ2BS4.js → chunk-CMYZWIXS.js} +2 -2
  74. package/dist/cli/chunks/{chunk-DYTQHRUS.js → chunk-CZWWC7GC.js} +1 -1
  75. package/dist/cli/chunks/{chunk-WF6UISKW.js → chunk-D7NOHASX.js} +4 -4
  76. package/dist/cli/chunks/{chunk-H5RQPO3X.js → chunk-DGRE6ZAA.js} +2 -2
  77. package/dist/cli/chunks/{chunk-53BXTTRO.js → chunk-DSGRXW6K.js} +3 -3
  78. package/dist/cli/chunks/{chunk-A2VUCUTT.js → chunk-DXA7RLYU.js} +2 -2
  79. package/dist/cli/chunks/{chunk-GVVFTFMB.js → chunk-DZHIE5UW.js} +2 -2
  80. package/dist/cli/chunks/{chunk-MZB2UV2O.js → chunk-EBK6CUBD.js} +1 -1
  81. package/dist/cli/chunks/{chunk-WIH522AP.js → chunk-EPEKEUCF.js} +1 -1
  82. package/dist/cli/chunks/{chunk-SRPLERER.js → chunk-EQ4SDE4L.js} +25 -25
  83. package/dist/cli/chunks/{chunk-EGOIIUBD.js → chunk-EZPWSS3B.js} +2 -2
  84. package/dist/cli/chunks/{chunk-EADSQN5T.js → chunk-F76SYOBT.js} +1 -1
  85. package/dist/cli/chunks/{chunk-XL5KIYE3.js → chunk-F7JVDLOI.js} +2 -2
  86. package/dist/cli/chunks/{chunk-QGOWNVVG.js → chunk-FCSETOWZ.js} +4 -4
  87. package/dist/cli/chunks/{chunk-A3DK3XNZ.js → chunk-FFE4XAQA.js} +1 -1
  88. package/dist/cli/chunks/{chunk-7EZ2Z2CK.js → chunk-FPTZP7W5.js} +1 -1
  89. package/dist/cli/chunks/{chunk-GV4DYPJP.js → chunk-FTFIA4I5.js} +2 -2
  90. package/dist/cli/chunks/{chunk-SM2YJ2AL.js → chunk-FTS6NGBP.js} +2 -2
  91. package/dist/cli/chunks/{chunk-XWYELBZS.js → chunk-FZ3TQAPW.js} +1 -1
  92. package/dist/cli/chunks/{chunk-HPWWYT67.js → chunk-G35KP72N.js} +2 -2
  93. package/dist/cli/chunks/{chunk-HZY42OVU.js → chunk-GCHDMO5V.js} +2 -2
  94. package/dist/cli/chunks/{chunk-23CX7JNL.js → chunk-GRN47ANK.js} +2 -2
  95. package/dist/cli/chunks/{chunk-HYFQUWNB.js → chunk-GV7P5JYF.js} +2 -2
  96. package/dist/cli/chunks/{chunk-YO4ESCB4.js → chunk-GX5RFGW2.js} +1 -1
  97. package/dist/cli/chunks/{chunk-TFK2AYIN.js → chunk-H77AUJNW.js} +2 -2
  98. package/dist/cli/chunks/{chunk-NBLDBVAW.js → chunk-HBIV7PQH.js} +1 -1
  99. package/dist/cli/chunks/{chunk-VYDVI6FZ.js → chunk-HOPXHZA3.js} +2 -2
  100. package/dist/cli/chunks/{chunk-HYOPJHHW.js → chunk-I3BH3KIF.js} +1 -1
  101. package/dist/cli/chunks/{chunk-ZELWDJXT.js → chunk-ILKMNDUM.js} +2 -2
  102. package/dist/cli/chunks/{chunk-C3FXFU2T.js → chunk-IRHBR56R.js} +1 -1
  103. package/dist/cli/chunks/{chunk-FYPX5WBJ.js → chunk-ISAMM7QA.js} +1 -1
  104. package/dist/cli/chunks/{chunk-V5AK56DA.js → chunk-ISGFAMHZ.js} +2 -2
  105. package/dist/cli/chunks/{chunk-KUHLTVWC.js → chunk-J46XGXPS.js} +1 -1
  106. package/dist/cli/chunks/{chunk-ZS4XVJGV.js → chunk-J4XCBOPA.js} +2 -2
  107. package/dist/cli/chunks/{chunk-BEFTQVEW.js → chunk-JIWMFLHV.js} +2 -2
  108. package/dist/cli/chunks/{chunk-UFSVUBTR.js → chunk-JJ7WAU4I.js} +2 -2
  109. package/dist/cli/chunks/{chunk-WOV6XI3A.js → chunk-JLPNYHJJ.js} +1 -1
  110. package/dist/cli/chunks/{chunk-77QZHIVX.js → chunk-JO2YLIZH.js} +2 -2
  111. package/dist/cli/chunks/{chunk-J7AQZLIH.js → chunk-JSYNSJDQ.js} +4 -4
  112. package/dist/cli/chunks/{chunk-OAZX6WFU.js → chunk-JYRBOSOF.js} +2 -2
  113. package/dist/cli/chunks/{chunk-EJ6MMYLK.js → chunk-KEZ4PXVF.js} +1 -1
  114. package/dist/cli/chunks/{chunk-N5XOXPHZ.js → chunk-KLGFEHEN.js} +2 -2
  115. package/dist/cli/chunks/{chunk-7MIOK72I.js → chunk-KU4WLKDK.js} +7 -7
  116. package/dist/cli/chunks/{chunk-Z4Q5PCRZ.js → chunk-KUTMQBV4.js} +4 -4
  117. package/dist/cli/chunks/{chunk-VW6FRMLW.js → chunk-L6PUBB6L.js} +2 -2
  118. package/dist/cli/chunks/{chunk-OEPNNLR4.js → chunk-LDJ5DZT5.js} +1 -1
  119. package/dist/cli/chunks/{chunk-QQFQDEUE.js → chunk-LLS6JYPN.js} +2 -2
  120. package/dist/cli/chunks/{chunk-UOI6ULCH.js → chunk-LPCFIFZF.js} +2 -2
  121. package/dist/cli/chunks/{chunk-6RD44SCE.js → chunk-M5EKZA7Q.js} +1 -1
  122. package/dist/cli/chunks/chunk-MEYSIVMP.js +2 -0
  123. package/dist/cli/chunks/{chunk-YMW57PEL.js → chunk-MFGLRMO4.js} +1 -1
  124. package/dist/cli/chunks/{chunk-BE4KALTE.js → chunk-MM57SD2F.js} +1 -1
  125. package/dist/cli/chunks/{chunk-FW4DJ4FJ.js → chunk-MO3QXLF2.js} +1 -1
  126. package/dist/cli/chunks/{chunk-QFETNCNN.js → chunk-MRIZY6HB.js} +2 -2
  127. package/dist/cli/chunks/{chunk-RT6O2HW2.js → chunk-N2MDNEF7.js} +2 -2
  128. package/dist/cli/chunks/{chunk-UA7TDVL7.js → chunk-N5ZHIQAV.js} +4 -4
  129. package/dist/cli/chunks/{chunk-Q6NTEICT.js → chunk-NZ556KZN.js} +2 -2
  130. package/dist/cli/chunks/{chunk-CVOQ6ESD.js → chunk-O5AUOBGU.js} +2 -2
  131. package/dist/cli/chunks/{chunk-5D7ZFWDS.js → chunk-OBSX3I4Y.js} +2 -2
  132. package/dist/cli/chunks/{chunk-NOHWJOBS.js → chunk-OLD2CIDI.js} +1 -1
  133. package/dist/cli/chunks/{chunk-5U6N4V5M.js → chunk-OTJ22IO2.js} +4 -4
  134. package/dist/cli/chunks/{chunk-5GFKTJ65.js → chunk-OYVDTD3A.js} +2 -2
  135. package/dist/cli/chunks/{chunk-LY7MFGBD.js → chunk-P2PPJUGD.js} +147 -150
  136. package/dist/cli/chunks/{chunk-OZGIOKEA.js → chunk-P4FRYNHL.js} +1 -1
  137. package/dist/cli/chunks/{chunk-X7ADKL7T.js → chunk-P4WE6VRR.js} +2 -2
  138. package/dist/cli/chunks/{chunk-ZUB5YOCM.js → chunk-P725KXHX.js} +2 -2
  139. package/dist/cli/chunks/{chunk-74IOEOMH.js → chunk-P7MNF2SK.js} +2 -2
  140. package/dist/cli/chunks/{chunk-TXSPBLBT.js → chunk-PJU5HVWV.js} +2 -2
  141. package/dist/cli/chunks/{chunk-MT7UNBZ7.js → chunk-PN3FYSQ6.js} +2 -2
  142. package/dist/cli/chunks/{chunk-F2OPFVQH.js → chunk-PPFW3H7E.js} +1 -1
  143. package/dist/cli/chunks/{chunk-IEJ7ZV3M.js → chunk-Q4RCUCHD.js} +1 -1
  144. package/dist/cli/chunks/{chunk-IAENZ2DR.js → chunk-QRALXNNX.js} +2 -2
  145. package/dist/cli/chunks/{chunk-AJUBT4NP.js → chunk-QVX22EIM.js} +3 -3
  146. package/dist/cli/chunks/chunk-R6CZCMKD.js +2 -0
  147. package/dist/cli/chunks/chunk-ROK5YQ5P.js +3 -0
  148. package/dist/cli/chunks/{chunk-ON2UTP2U.js → chunk-S2GNFAOC.js} +2 -2
  149. package/dist/cli/chunks/{chunk-HXXHMLJ5.js → chunk-S644OORE.js} +1 -1
  150. package/dist/cli/chunks/{chunk-XYLQZWF6.js → chunk-S7CROKX4.js} +2 -2
  151. package/dist/cli/chunks/{chunk-T77GZF4B.js → chunk-S7QUHLXV.js} +1 -1
  152. package/dist/cli/chunks/{chunk-RDGPXENG.js → chunk-UGYXUPGN.js} +2 -2
  153. package/dist/cli/chunks/{chunk-QVH5Y7AP.js → chunk-URRPJ3M7.js} +1 -1
  154. package/dist/cli/chunks/{chunk-AEUEMVJK.js → chunk-URUOTHPO.js} +2 -2
  155. package/dist/cli/chunks/{chunk-VXKWNRGA.js → chunk-VCYOFWMG.js} +2 -2
  156. package/dist/cli/chunks/{chunk-6EGS77BB.js → chunk-VQVFGFYK.js} +1 -1
  157. package/dist/cli/chunks/{chunk-NHUGHAY6.js → chunk-VT5SMBEM.js} +1 -1
  158. package/dist/cli/chunks/{chunk-ROVZSZCS.js → chunk-VTGRGYY4.js} +3 -3
  159. package/dist/cli/chunks/{chunk-QPLSYEWJ.js → chunk-VWCFXCSV.js} +2 -2
  160. package/dist/cli/chunks/{chunk-ENK44A6Q.js → chunk-VY4557VF.js} +2 -2
  161. package/dist/cli/chunks/{chunk-5FSLMYAC.js → chunk-VYERAOQL.js} +2 -2
  162. package/dist/cli/chunks/{chunk-EIGRV3J6.js → chunk-W6H2SOIK.js} +2 -2
  163. package/dist/cli/chunks/{chunk-CBONQM5D.js → chunk-WBR4VRQE.js} +2 -2
  164. package/dist/cli/chunks/{chunk-JZT7BU44.js → chunk-WDV6CBED.js} +2 -2
  165. package/dist/cli/chunks/{chunk-G367W7XR.js → chunk-WO7NPGUD.js} +19 -19
  166. package/dist/cli/chunks/{chunk-4INST4ZL.js → chunk-WPOYFV4X.js} +1 -1
  167. package/dist/cli/chunks/{chunk-3M7J4U74.js → chunk-WPSGMTI4.js} +4 -4
  168. package/dist/cli/chunks/{chunk-RKUAWQOF.js → chunk-WQMXQO3O.js} +2 -2
  169. package/dist/cli/chunks/{chunk-Q3NSU24F.js → chunk-WR54SKKL.js} +2 -2
  170. package/dist/cli/chunks/{chunk-UYUJT6QO.js → chunk-X4OESN7M.js} +2 -2
  171. package/dist/cli/chunks/{chunk-ZUOVNFXK.js → chunk-X5RELRY7.js} +2 -2
  172. package/dist/cli/chunks/{chunk-BLG7SH4A.js → chunk-X7JEBPEW.js} +1 -1
  173. package/dist/cli/chunks/{chunk-FSSR6WBE.js → chunk-XEABMIUH.js} +2 -2
  174. package/dist/cli/chunks/{chunk-ONR2NXXD.js → chunk-XELFJC77.js} +3 -3
  175. package/dist/cli/chunks/{chunk-MM56VPNE.js → chunk-XPUY3ZKD.js} +3 -3
  176. package/dist/cli/chunks/{chunk-QUORH2MG.js → chunk-XZDPR6I2.js} +8 -8
  177. package/dist/cli/chunks/{chunk-MZMG6CUJ.js → chunk-Y63DADOR.js} +2 -2
  178. package/dist/cli/chunks/{chunk-CQNMGK6Y.js → chunk-YFRZVNE4.js} +2 -2
  179. package/dist/cli/chunks/{chunk-3QJU4Q4R.js → chunk-YIDZ3TEN.js} +2 -2
  180. package/dist/cli/chunks/{chunk-4EKV7PHB.js → chunk-Z6CRROLU.js} +2 -2
  181. package/dist/cli/chunks/{chunk-IWFFO6VT.js → chunk-ZPH2YT3J.js} +2 -2
  182. package/dist/cli/chunks/{chunk-PYKY22GC.js → chunk-ZV7LJPSI.js} +5 -5
  183. package/dist/cli/chunks/chunk-ZXIIB3QE.js +2 -0
  184. package/dist/cli/chunks/ci-63JINRNB.js +82 -0
  185. package/dist/cli/chunks/{ci-output-RLS32FUY.js → ci-output-CRFWLUAA.js} +2 -2
  186. package/dist/cli/chunks/{circuit-breaker-MRCC7WCM.js → circuit-breaker-PJLG3WYL.js} +2 -2
  187. package/dist/cli/chunks/{claude-flow-setup-LIZCEKDF.js → claude-flow-setup-UKHSQMJU.js} +2 -2
  188. package/dist/cli/chunks/client-A4FTITK3.js +2 -0
  189. package/dist/cli/chunks/{cline-installer-T7H6R2RC.js → cline-installer-PYQ27AS3.js} +2 -2
  190. package/dist/cli/chunks/{code-XMBLI7OF.js → code-K7VGLZ3W.js} +3 -3
  191. package/dist/cli/chunks/{code-index-extractor-QS7BYLEX.js → code-index-extractor-NNWAVWSL.js} +2 -2
  192. package/dist/cli/chunks/{codex-installer-6PGT5FM6.js → codex-installer-U4VJIKRN.js} +2 -2
  193. package/dist/cli/chunks/{completions-2A3WRXY2.js → completions-DOCI3P4W.js} +2 -2
  194. package/dist/cli/chunks/{complexity-analyzer-23HOOGJ7.js → complexity-analyzer-RFW2QRFR.js} +2 -2
  195. package/dist/cli/chunks/{continuedev-installer-4FSF7B3N.js → continuedev-installer-S5WXXOBU.js} +2 -2
  196. package/dist/cli/chunks/{copilot-installer-A5GRQQUU.js → copilot-installer-AAQ6YLVJ.js} +2 -2
  197. package/dist/cli/chunks/core-handlers-FO3QTNWI.js +2 -0
  198. package/dist/cli/chunks/{cost-tracker-Z4STQ5VB.js → cost-tracker-R4VOHTWQ.js} +2 -2
  199. package/dist/cli/chunks/{coverage-NUPP6KZZ.js → coverage-P54HPCLV.js} +3 -3
  200. package/dist/cli/chunks/cross-domain-router-LIV6SRWF.js +2 -0
  201. package/dist/cli/chunks/{cursor-installer-FVJ7ROPJ.js → cursor-installer-VHBWZE5A.js} +2 -2
  202. package/dist/cli/chunks/{daemon-D662EX5N.js → daemon-BTRSWNB4.js} +4 -4
  203. package/dist/cli/chunks/{daemon-7ZZA2MMN.js → daemon-JLH5TTWZ.js} +4 -4
  204. package/dist/cli/chunks/{dag-attention-scheduler-IB4TQ2KA.js → dag-attention-scheduler-5Z6DCRFK.js} +2 -2
  205. package/dist/cli/chunks/{detect-LGLBZN4I.js → detect-NWGASRJJ.js} +2 -2
  206. package/dist/cli/chunks/{dist-node-Z3OL42YE.js → dist-node-XMNNSEFJ.js} +2 -2
  207. package/dist/cli/chunks/{domain-handler-L3CLNL7U.js → domain-handler-BWVBZTNR.js} +2 -2
  208. package/dist/cli/chunks/{domain-plugins-GQ3V5X6L.js → domain-plugins-YAD4USA4.js} +2 -2
  209. package/dist/cli/chunks/domain-transfer-Z3MRPZEZ.js +2 -0
  210. package/dist/cli/chunks/dream-DNLGHYXY.js +2 -0
  211. package/dist/cli/chunks/{embed-and-insert-pattern-UGD6USYH.js → embed-and-insert-pattern-5CCO45WC.js} +2 -2
  212. package/dist/cli/chunks/{eval-3B7UIYGY.js → eval-JEMLTGY4.js} +2 -2
  213. package/dist/cli/chunks/{experience-capture-middleware-3RQ4NYY3.js → experience-capture-middleware-FKVYBBAN.js} +4 -4
  214. package/dist/cli/chunks/{fast-paths-QOSAEPYD.js → fast-paths-TFL32H3C.js} +2 -2
  215. package/dist/cli/chunks/{feature-flags-3S5TH6P4.js → feature-flags-CNGAUUMT.js} +2 -2
  216. package/dist/cli/chunks/{feature-flags-TLF4NKOH.js → feature-flags-OHGD2NCW.js} +2 -2
  217. package/dist/cli/chunks/{file-discovery-AEVMJRNB.js → file-discovery-IHGDYW34.js} +2 -2
  218. package/dist/cli/chunks/{fleet-E6WTXWFL.js → fleet-OGTSDGJ2.js} +4 -4
  219. package/dist/cli/chunks/{gnn-wrapper-MCKH3AUU.js → gnn-wrapper-QYTTKNCE.js} +2 -2
  220. package/dist/cli/chunks/{heartbeat-handler-U7XENHRR.js → heartbeat-handler-R5OD2SKN.js} +4 -4
  221. package/dist/cli/chunks/heartbeat-scheduler-DL4LXXJF.js +2 -0
  222. package/dist/cli/chunks/hnsw-adapter-Y64M43J4.js +2 -0
  223. package/dist/cli/chunks/hnsw-index-5V6DDMTA.js +2 -0
  224. package/dist/cli/chunks/{hnsw-legacy-bridge-5GW4SAEI.js → hnsw-legacy-bridge-ULJWYXBQ.js} +2 -2
  225. package/dist/cli/chunks/{hnswlib-node-7BLZBK5T.js → hnswlib-node-SYKJXGE2.js} +2 -2
  226. package/dist/cli/chunks/{hooks-F3O2SB6H.js → hooks-XAJXPXTU.js} +10 -10
  227. package/dist/cli/chunks/hybrid-backend-JWT2V4FQ.js +2 -0
  228. package/dist/cli/chunks/{hypergraph-engine-PV4EKXHB.js → hypergraph-engine-GIBPGW4N.js} +2 -2
  229. package/dist/cli/chunks/{hypergraph-handler-VOWO5ZTW.js → hypergraph-handler-ENFK6IDN.js} +3 -3
  230. package/dist/cli/chunks/impact-analyzer-XUZQSZZC.js +2 -0
  231. package/dist/cli/chunks/{init-handler-ENJ5ONJX.js → init-handler-CSA62LGT.js} +6 -6
  232. package/dist/cli/chunks/init-wizard-KDJKHEPN.js +2 -0
  233. package/dist/cli/chunks/kernel-MUDYPGFR.js +2 -0
  234. package/dist/cli/chunks/{kilocode-installer-HNNJOOPE.js → kilocode-installer-YXFIRTSA.js} +2 -2
  235. package/dist/cli/chunks/{kiro-installer-UZBIQ3IC.js → kiro-installer-JW3BG2MQ.js} +2 -2
  236. package/dist/cli/chunks/knowledge-graph-GR52N7PU.js +2 -0
  237. package/dist/cli/chunks/{learning-YMLCVFUT.js → learning-BDBZ7ZVG.js} +4 -4
  238. package/dist/cli/chunks/{llm-router-YWTARCCT.js → llm-router-CCX2DYTC.js} +4 -4
  239. package/dist/cli/chunks/llm-router-service-QL6LVKZ4.js +2 -0
  240. package/dist/cli/chunks/{load-DKE3F3IP.js → load-UJTTEOOK.js} +2 -2
  241. package/dist/cli/chunks/load-test-76V75WZ5.js +2 -0
  242. package/dist/cli/chunks/{mcp-5PSGIUCW.js → mcp-2NAJYREC.js} +2 -2
  243. package/dist/cli/chunks/{memory-3L3O6JMM.js → memory-C3UQSN5F.js} +5 -5
  244. package/dist/cli/chunks/memory-backend-SMQRS5QN.js +2 -0
  245. package/dist/cli/chunks/memory-handlers-ESFIJENU.js +2 -0
  246. package/dist/cli/chunks/{multi-model-executor-AEEO7IA4.js → multi-model-executor-SIHSHAD7.js} +2 -2
  247. package/dist/cli/chunks/{opencode-installer-ABBO355U.js → opencode-installer-KDYHUGPG.js} +2 -2
  248. package/dist/cli/chunks/{orchestrator-E36Q7MKE.js → orchestrator-MJHIQEHD.js} +6 -6
  249. package/dist/cli/chunks/pattern-null-store-MWAJMOYU.js +2 -0
  250. package/dist/cli/chunks/{pattern-usage-recorder-H4XKSID4.js → pattern-usage-recorder-OLBE4UIF.js} +2 -2
  251. package/dist/cli/chunks/{pipeline-BGFEHXIN.js → pipeline-IOK2CV3U.js} +2 -2
  252. package/dist/cli/chunks/{platform-GK7ZVDJI.js → platform-53JQ7JXN.js} +2 -2
  253. package/dist/cli/chunks/{plugin-CAH2CKI6.js → plugin-L5SDIWDI.js} +2 -2
  254. package/dist/cli/chunks/{prime-radiant-advanced-wasm-M5EYRONA.js → prime-radiant-advanced-wasm-2DS67JFS.js} +2 -2
  255. package/dist/cli/chunks/{project-root-BSNZC243.js → project-root-LQMOFO2Z.js} +2 -2
  256. package/dist/cli/chunks/protocol-executor-32X3GAJT.js +2 -0
  257. package/dist/cli/chunks/{protocol-handler-JDSSC2SF.js → protocol-handler-NXG2M43B.js} +2 -2
  258. package/dist/cli/chunks/{prove-ANPTOZJE.js → prove-7K7PFSSX.js} +2 -2
  259. package/dist/cli/chunks/qe-reasoning-bank-KAFV3TGI.js +2 -0
  260. package/dist/cli/chunks/{quality-SXWGYRQR.js → quality-ATILUGMJ.js} +2 -2
  261. package/dist/cli/chunks/quality-gate-MPZMDPIZ.js +7 -0
  262. package/dist/cli/chunks/queen-coordinator-L3SODGRX.js +2 -0
  263. package/dist/cli/chunks/{real-embeddings-WSRYAOZM.js → real-embeddings-VZN3KIAI.js} +2 -2
  264. package/dist/cli/chunks/{ref-validation-AZ3LRWEK.js → ref-validation-EUATPVXX.js} +2 -2
  265. package/dist/cli/chunks/{roocode-installer-2QKGFIEU.js → roocode-installer-7M2GOUNZ.js} +2 -2
  266. package/dist/cli/chunks/router-DDCSSXYQ.js +2 -0
  267. package/dist/cli/chunks/routing-feedback-RFASKYCD.js +2 -0
  268. package/dist/cli/chunks/{routing-handler-UYDC5MMD.js → routing-handler-VWANE652.js} +2 -2
  269. package/dist/cli/chunks/{ruvector-commands-QXADPVEY.js → ruvector-commands-B2YIPGOV.js} +2 -2
  270. package/dist/cli/chunks/rvf-dual-writer-HCIF2G56.js +2 -0
  271. package/dist/cli/chunks/rvf-migration-adapter-UVAHQ7SV.js +2 -0
  272. package/dist/cli/chunks/{rvf-migration-coordinator-GD4NBFKT.js → rvf-migration-coordinator-RQXOQJ5T.js} +2 -2
  273. package/dist/cli/chunks/rvf-native-adapter-F2I5FFHK.js +2 -0
  274. package/dist/cli/chunks/{rvf-store-integrity-7SXG66IL.js → rvf-store-integrity-7P5YDXRH.js} +2 -2
  275. package/dist/cli/chunks/safe-db-6ZAA4S23.js +2 -0
  276. package/dist/cli/chunks/schedule-SM5Q6UVP.js +2 -0
  277. package/dist/cli/chunks/scheduler-4EYP4EZ6.js +2 -0
  278. package/dist/cli/chunks/{security-YKB622PK.js → security-VJ7TVSQF.js} +3 -3
  279. package/dist/cli/chunks/{shared-rvf-adapter-KMLAV7JK.js → shared-rvf-adapter-63NXQFBX.js} +2 -2
  280. package/dist/cli/chunks/{shared-rvf-dual-writer-OYY27DFV.js → shared-rvf-dual-writer-JQRP7P5A.js} +2 -2
  281. package/dist/cli/chunks/sqlite-persistence-KLN2K266.js +2 -0
  282. package/dist/cli/chunks/{standalone-memory-2DOABVLC.js → standalone-memory-WJ72PH5P.js} +2 -2
  283. package/dist/cli/chunks/{status-handler-EXRKETV7.js → status-handler-G72ZSLAX.js} +2 -2
  284. package/dist/cli/chunks/{structural-health-2SKK6DU6.js → structural-health-HYBGP4BD.js} +2 -2
  285. package/dist/cli/chunks/{sync-DQ2YUNI6.js → sync-5YMZZIF4.js} +2 -2
  286. package/dist/cli/chunks/{sync-UW7SX7GO.js → sync-O5FQAHT7.js} +2 -2
  287. package/dist/cli/chunks/{task-handler-LYQ6WYUY.js → task-handler-E6IFNHZG.js} +2 -2
  288. package/dist/cli/chunks/{task-handlers-DIJO232S.js → task-handlers-P3GC2L5L.js} +3 -3
  289. package/dist/cli/chunks/{test-WRHZMUCW.js → test-OU6ERW67.js} +6 -6
  290. package/dist/cli/chunks/{test-scheduling-HI23RXFK.js → test-scheduling-3HY4I3HY.js} +7 -7
  291. package/dist/cli/chunks/{token-bootstrap-23SA6SWZ.js → token-bootstrap-A5QA4CWK.js} +2 -2
  292. package/dist/cli/chunks/{token-usage-M7RRDPXO.js → token-usage-MUNQVPFT.js} +2 -2
  293. package/dist/cli/chunks/{transformers-4TC35KKS.js → transformers-IEO25W5V.js} +2 -2
  294. package/dist/cli/chunks/{tree-sitter-wasm-parser-F4LTKAWD.js → tree-sitter-wasm-parser-T2EQHEAY.js} +2 -2
  295. package/dist/cli/chunks/{types-NBXV6LXQ.js → types-ODCPGCID.js} +2 -2
  296. package/dist/cli/chunks/unified-memory-B5IA2KKQ.js +2 -0
  297. package/dist/cli/chunks/unified-memory-hnsw-YF74LL3Z.js +2 -0
  298. package/dist/cli/chunks/unified-persistence-VZMGNGWY.js +2 -0
  299. package/dist/cli/chunks/{upgrade-4BGOU5RM.js → upgrade-4DN6EIW2.js} +2 -2
  300. package/dist/cli/chunks/{validate-EDWAR63H.js → validate-TBNAPDE3.js} +2 -2
  301. package/dist/cli/chunks/{validate-swarm-VI72CPR7.js → validate-swarm-ZN7XXUY4.js} +2 -2
  302. package/dist/cli/chunks/visual-security-ZV3BLLSH.js +2 -0
  303. package/dist/cli/chunks/{web-tree-sitter-Y5XBRQXF.js → web-tree-sitter-DWAWVD2X.js} +2 -2
  304. package/dist/cli/chunks/{windsurf-installer-VEX23WAF.js → windsurf-installer-U6EROS5S.js} +2 -2
  305. package/dist/cli/chunks/{witness-chain-3YNL6YGY.js → witness-chain-EQEJS2P4.js} +2 -2
  306. package/dist/cli/chunks/witness-chain-OA24MQWX.js +2 -0
  307. package/dist/cli/chunks/{witness-chain-repair-MJZGZRWT.js → witness-chain-repair-KBXDRXS3.js} +2 -2
  308. package/dist/cli/chunks/{witness-chain-verifier-TTJYXTBE.js → witness-chain-verifier-HSQGZ4R4.js} +2 -2
  309. package/dist/cli/chunks/{witness-key-manager-EM6YXYOY.js → witness-key-manager-RAODG73T.js} +2 -2
  310. package/dist/cli/chunks/{workflow-2RBDOM7V.js → workflow-KNFJNNKG.js} +4 -4
  311. package/dist/cli/chunks/workflow-orchestrator-IMX2LSVE.js +2 -0
  312. package/dist/cli/chunks/{wrappers-5OTAVVOV.js → wrappers-NIJBA22T.js} +2 -2
  313. package/dist/cli/commands/ci.js +17 -6
  314. package/dist/cli/commands/quality-gate.js +6 -1
  315. package/dist/cli/index.js +7 -2
  316. package/dist/cli/process-store-cleanup.d.ts +7 -0
  317. package/dist/cli/process-store-cleanup.js +27 -0
  318. package/dist/cli/utils/ci-config.d.ts +3 -3
  319. package/dist/cli/utils/ci-config.js +202 -68
  320. package/dist/cli/utils/workflow-parser.js +73 -57
  321. package/dist/domains/code-intelligence/services/metric-collector/test-counter.d.ts +1 -1
  322. package/dist/domains/code-intelligence/services/metric-collector/test-counter.js +17 -15
  323. package/dist/domains/quality-assessment/quality-evidence.d.ts +3 -1
  324. package/dist/domains/quality-assessment/quality-evidence.js +7 -2
  325. package/dist/domains/test-execution/services/retry-handler.js +38 -16
  326. package/dist/domains/test-execution/services/test-executor.d.ts +3 -3
  327. package/dist/domains/test-execution/services/test-executor.js +66 -22
  328. package/dist/governance/ab-benchmarking.d.ts +5 -1
  329. package/dist/governance/ab-benchmarking.js +64 -29
  330. package/dist/init/fleet-integration.js +3 -2
  331. package/dist/init/init-wizard-steps.js +3 -2
  332. package/dist/init/phases/06-code-intelligence.js +6 -4
  333. package/dist/integrations/ruvector/sona-persistence.d.ts +1 -0
  334. package/dist/integrations/ruvector/sona-persistence.js +74 -20
  335. package/dist/integrations/ruvector/sona-wrapper.d.ts +2 -0
  336. package/dist/integrations/ruvector/sona-wrapper.js +13 -0
  337. package/dist/kernel/memory-backend.js +5 -4
  338. package/dist/kernel/unified-memory.js +3 -2
  339. package/dist/learning/aqe-learning-engine.js +3 -2
  340. package/dist/mcp/bundle.js +474 -471
  341. package/dist/mcp/connection-pool.d.ts +2 -0
  342. package/dist/mcp/connection-pool.js +13 -2
  343. package/dist/mcp/handlers/memory-handlers.d.ts +1 -0
  344. package/dist/mcp/handlers/memory-handlers.js +16 -6
  345. package/dist/mcp/protocol-server.js +29 -8
  346. package/dist/mcp/security/rate-limiter.d.ts +1 -0
  347. package/dist/mcp/security/rate-limiter.js +22 -5
  348. package/dist/mcp/services/session-store.js +17 -17
  349. package/dist/mcp/tools/planning/goap-status.d.ts +2 -0
  350. package/dist/mcp/tools/planning/goap-status.js +8 -2
  351. package/dist/mcp/types.d.ts +2 -0
  352. package/dist/optimization/session-cache.js +13 -11
  353. package/dist/planning/goap-planner.d.ts +3 -0
  354. package/dist/planning/goap-planner.js +80 -37
  355. package/dist/plugins/cache.js +10 -3
  356. package/dist/shared/embeddings/embedding-cache.js +5 -5
  357. package/dist/shared/embeddings/nomic-embedder.js +17 -7
  358. package/dist/shared/embeddings/ollama-client.js +5 -3
  359. package/dist/shared/git/git-analyzer.js +31 -30
  360. package/dist/shared/http/http-client.js +20 -13
  361. package/dist/shared/io/file-reader.js +11 -8
  362. package/dist/shared/llm/cache.d.ts +8 -29
  363. package/dist/shared/llm/cache.js +12 -11
  364. package/dist/shared/llm/cost-tracker.js +2 -1
  365. package/dist/shared/llm/provider-manager.js +4 -22
  366. package/dist/shared/llm/providers/gemini.d.ts +1 -0
  367. package/dist/shared/llm/providers/gemini.js +14 -5
  368. package/dist/shared/llm/providers/openrouter.js +6 -3
  369. package/dist/shared/metrics/code-metrics.js +1 -1
  370. package/dist/shared/metrics/system-metrics.js +8 -2
  371. package/dist/shared/retry-engine.js +6 -12
  372. package/dist/shared/test-runner-process.d.ts +10 -0
  373. package/dist/shared/test-runner-process.js +210 -0
  374. package/dist/test-scheduling/executors/vitest-executor.js +26 -17
  375. package/dist/validation/quality-verdict.js +3 -2
  376. package/dist/workers/quality-daemon/priority-queue.js +4 -1
  377. package/package.json +6 -4
  378. package/dist/cli/chunks/adapter-TVQKH65T.js +0 -2
  379. package/dist/cli/chunks/aqe-learning-engine-ULGTVVWE.js +0 -2
  380. package/dist/cli/chunks/base-W42BURDL.js +0 -2
  381. package/dist/cli/chunks/browser-workflow-HKGHFFFT.js +0 -2
  382. package/dist/cli/chunks/chunk-2IMSJ7IO.js +0 -2
  383. package/dist/cli/chunks/chunk-FBZC4IGB.js +0 -2
  384. package/dist/cli/chunks/chunk-LXZMP3VX.js +0 -736
  385. package/dist/cli/chunks/chunk-MNQN7UZX.js +0 -4
  386. package/dist/cli/chunks/chunk-OXHF3L2T.js +0 -2
  387. package/dist/cli/chunks/chunk-PELENDDQ.js +0 -2
  388. package/dist/cli/chunks/chunk-TW3SR4TS.js +0 -2
  389. package/dist/cli/chunks/chunk-V6RE4YRQ.js +0 -2
  390. package/dist/cli/chunks/chunk-ZQZD55MN.js +0 -3
  391. package/dist/cli/chunks/ci-J3TDK5RA.js +0 -81
  392. package/dist/cli/chunks/client-3BD2DI4N.js +0 -2
  393. package/dist/cli/chunks/core-handlers-C3H2ZCS2.js +0 -2
  394. package/dist/cli/chunks/cross-domain-router-JCQ7SWDP.js +0 -2
  395. package/dist/cli/chunks/domain-transfer-MFCI76IY.js +0 -2
  396. package/dist/cli/chunks/dream-FTP33IJB.js +0 -2
  397. package/dist/cli/chunks/heartbeat-scheduler-HXBJVJL2.js +0 -2
  398. package/dist/cli/chunks/hnsw-adapter-TU6WG2ME.js +0 -2
  399. package/dist/cli/chunks/hnsw-index-MS5KODD7.js +0 -2
  400. package/dist/cli/chunks/hybrid-backend-HT45LBHC.js +0 -2
  401. package/dist/cli/chunks/impact-analyzer-AP4AGTG5.js +0 -2
  402. package/dist/cli/chunks/init-wizard-I5DFZUQL.js +0 -2
  403. package/dist/cli/chunks/kernel-MISPSPPA.js +0 -2
  404. package/dist/cli/chunks/knowledge-graph-L26JESGE.js +0 -2
  405. package/dist/cli/chunks/llm-router-service-MWGC43ZA.js +0 -2
  406. package/dist/cli/chunks/load-test-H5ISNNM5.js +0 -2
  407. package/dist/cli/chunks/memory-backend-HWDNOBKW.js +0 -2
  408. package/dist/cli/chunks/memory-handlers-ZFDVQZM5.js +0 -2
  409. package/dist/cli/chunks/pattern-null-store-GQP6ICWK.js +0 -2
  410. package/dist/cli/chunks/protocol-executor-AD5A4DAI.js +0 -2
  411. package/dist/cli/chunks/qe-reasoning-bank-W3Z2PKTR.js +0 -2
  412. package/dist/cli/chunks/quality-gate-GYNCA4ZY.js +0 -7
  413. package/dist/cli/chunks/queen-coordinator-HQRHLIJX.js +0 -2
  414. package/dist/cli/chunks/router-MTP5LH4H.js +0 -2
  415. package/dist/cli/chunks/routing-feedback-GWETVB4L.js +0 -2
  416. package/dist/cli/chunks/rvf-dual-writer-4UE5S7WP.js +0 -2
  417. package/dist/cli/chunks/rvf-migration-adapter-PHH3HF4Q.js +0 -2
  418. package/dist/cli/chunks/rvf-native-adapter-KTLZBUWV.js +0 -2
  419. package/dist/cli/chunks/safe-db-FWWGAPVE.js +0 -2
  420. package/dist/cli/chunks/schedule-TPA4V4D5.js +0 -2
  421. package/dist/cli/chunks/scheduler-5ZTEPNDD.js +0 -2
  422. package/dist/cli/chunks/sqlite-persistence-HPTT624C.js +0 -2
  423. package/dist/cli/chunks/unified-memory-OVFEPRPS.js +0 -2
  424. package/dist/cli/chunks/unified-memory-hnsw-KKRSCZHR.js +0 -2
  425. package/dist/cli/chunks/unified-persistence-7GLR4RI3.js +0 -2
  426. package/dist/cli/chunks/visual-security-2FUM5GLI.js +0 -2
  427. package/dist/cli/chunks/witness-chain-MH6GA5L6.js +0 -2
  428. package/dist/cli/chunks/workflow-orchestrator-H6G65YKU.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.14.7");process.exit(0)}
2
- import{a as q}from"./chunk-V5AK56DA.js";import{c as V,d as W}from"./chunk-UA7TDVL7.js";import{c as x}from"./chunk-VXKWNRGA.js";import{b as E,d as $}from"./chunk-OIDWDGLG.js";import{a as G}from"./chunk-TW3SR4TS.js";import{e as R}from"./chunk-5GFKTJ65.js";import{a as C,e as H}from"./chunk-ZUOVNFXK.js";import{i as v}from"./chunk-FW4DJ4FJ.js";import{a as M,b as U,d as ee}from"./chunk-RDGPXENG.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.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(`
3
3
  INSERT INTO concept_nodes
4
4
  (id, concept_type, content, embedding, activation_level, last_activated, pattern_id, metadata)
5
5
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
@@ -63,7 +63,7 @@ import{a as q}from"./chunk-V5AK56DA.js";import{c as V,d as W}from"./chunk-UA7TDV
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-3S5TH6P4.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-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
67
67
  FROM qe_pattern_nulls n
68
68
  JOIN qe_patterns p ON p.id = n.pattern_id
69
69
  ORDER BY n.updated_at DESC
@@ -89,7 +89,7 @@ import{a as q}from"./chunk-V5AK56DA.js";import{c as V,d as W}from"./chunk-UA7TDV
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-W42BURDL.js"),{createQEReasoningBank:i}=await import("./qe-reasoning-bank-W3Z2PKTR.js"),r=await n(),a=i(r);await a.initialize();try{let{getSharedRvfDualWriter:d}=await import("./shared-rvf-dual-writer-OYY27DFV.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-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(`
93
93
  UPDATE dream_insights
94
94
  SET applied = 1, pattern_id = ?
95
95
  WHERE id = ?
@@ -117,4 +117,4 @@ import{a as q}from"./chunk-V5AK56DA.js";import{c as V,d as W}from"./chunk-UA7TDV
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-3S5TH6P4.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-KMLAV7JK.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var ce=N;G();var Y="learning:loop-health";async function J(p,e,t){try{let n=new Date().toISOString(),i=await p.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await p.set(Y,i)}catch{}}var u=R.create("DreamScheduler"),Z={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},K="dream-scheduler:hook-state",L=class p{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Z,...t},this.metaLearningEngine=new W}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,u.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),u.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),u.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,u.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(u.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{u.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,u.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&u.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){u.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),u.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&u.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){u.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-KMLAV7JK.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-OYY27DFV.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&u.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){u.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new q,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>p.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){u.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)u.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>p.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:v(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{u.debug("Failed to publish meta-learning insight event")}}}else u.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),u.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){u.info("Quality gate failed but cannot start dream yet");return}u.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){u.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){u.info("Milestone reached but cannot start dream yet");return}u.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:v(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){u.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(K),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(K,t)}catch(e){u.warn("Dream hook-state reconcile failed (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){u.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],u.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){u.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function de(p,e){return new L(p,e)}var pe=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],z=class{constructor(e,t){this.db=e;this.branchManager=new b(e,t??A)}db;branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,l)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(l.validation)>d?l:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,P as b,T as c,te as d,B as e,O as f,F as g,j as h,w as i,Q as j,_ as k,A as l,b as m,X as n,N as o,oe as p,ce as q,pe as r,z as s,Z as t,L as u,de as v};
120
+ `).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:E(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function se(p){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[p]||"test-template"}function oe(p){let e=new N(p);return import("./feature-flags-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};
@@ -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.0");process.exit(0)}
2
+ var c="quality-assessment";var o=["coverage","testsPassing","criticalBugs","codeSmells","securityVulnerabilities","technicalDebt","duplications"],u={coverage:{direction:"min",value:80,severity:"high"},testsPassing:{direction:"min",value:95,severity:"critical"},criticalBugs:{direction:"max",value:0,severity:"critical"},codeSmells:{direction:"max",value:20,severity:"medium"},securityVulnerabilities:{direction:"max",value:0,severity:"critical"},technicalDebt:{direction:"max",value:5,severity:"medium"},duplications:{direction:"max",value:5,severity:"low"}};function l(t){return`quality-evidence:${t}:latest`}function d(t,r,a){if(typeof t!="string")throw new Error("Measured quality evidence is malformed: measuredAt is required.");let e=Date.parse(t);if(!Number.isFinite(e))throw new Error("Measured quality evidence is malformed: measuredAt is invalid.");if(e>r+6e4)throw new Error("Measured quality evidence is malformed: measuredAt is in the future.");if(r-e>a)throw new Error("Measured quality evidence is stale. Run the relevant quality analyzers again.");return e}function m(t,r,a,e){if(!t||typeof t!="object")throw new Error(`No measured quality evidence found for ${r}.`);let i=t;if(i.schemaVersion!==1||i.metric!==r||!Number.isFinite(i.value)||i.value<0||typeof i.source!="string"||i.source.trim().length===0)throw new Error(`Measured quality evidence for ${r} is malformed or incomplete.`);d(i.measuredAt,a,e)}async function v(t,r,a){let e=Date.now();if(d(a.measuredAt,e,Number.POSITIVE_INFINITY),a.source.trim().length===0)throw new Error("Quality evidence source is required.");for(let i of o){let n=r[i];if(n===void 0)continue;if(!Number.isFinite(n)||n<0)throw new Error(`Quality evidence value for ${i} must be a non-negative finite number.`);let s={schemaVersion:1,metric:i,value:n,measuredAt:a.measuredAt,source:a.source};await t.set(l(i),s,{namespace:c,persist:!0})}}async function y(t,r={}){let a=r.now??Date.now(),e=r.maxAgeMs??864e5,i={};for(let n of o){let s=await t.get(l(n),{namespace:c});m(s,n,a,e),i[n]=s.value}return i}function f(t,r={}){if(r.coverage!==void 0&&(!Number.isFinite(r.coverage)||r.coverage<0||r.coverage>100))throw new Error("Coverage quality threshold must be a finite number between 0 and 100.");let a=o.map(e=>{let i=e==="coverage"&&r.coverage!==void 0?{...u[e],value:r.coverage}:u[e],n=t[e];return{name:e,value:n,threshold:i.value,direction:i.direction,severity:i.severity,passed:i.direction==="min"?n>=i.value:n<=i.value}});return{passed:a.every(e=>e.passed),checks:a,recommendations:a.filter(e=>!e.passed).map(e=>`${e.name} failed its measured ${e.direction} threshold.`)}}export{u as a,v as b,y as c,f as d};
@@ -0,0 +1,82 @@
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
4
+
5
+ `;r+=`**Status:** ${n.overallStatus==="passed"?"PASSED":n.overallStatus==="warning"?"WARNING":"FAILED"}
6
+ `,r+=`**Duration:** ${(n.duration/1e3).toFixed(1)}s
7
+ `,r+=`**Quality Gate:** ${X(n)}
8
+
9
+ `,r+=`## Phases
10
+
11
+ `,r+=`| Phase | Type | Status | Duration | Summary |
12
+ `,r+=`|-------|------|--------|----------|---------|
13
+ `;for(let s of n.phases){let u=s.status==="passed"?"PASS":s.status==="failed"?"FAIL":s.status==="warning"?"WARN":"SKIP";r+=`| ${s.phase} | ${s.type} | ${u} | ${(s.duration/1e3).toFixed(1)}s | ${s.summary} |
14
+ `}r+=`
15
+ ## Artifacts
16
+
17
+ `;for(let s of n.phases)if(s.artifacts.length>0){r+=`### ${s.phase}
18
+ `;for(let u of s.artifacts)r+=`- \`${w.basename(u)}\`
19
+ `;r+=`
20
+ `}return r}function X(n){return`${n.qualityGateStatus==="not-run"?"Not run":n.qualityGatePassed?"Passed":"Failed"} (${n.qualityGateEnforced?"enforced":"advisory"})`}function ge(n,r,s){let u=new se("ci").description("CI/CD pipeline orchestration");return u.command("run").description("Execute CI pipeline from .aqe-ci.yml").option("-c, --config <path>","Path to .aqe-ci.yml config file").option("--phase <phases>","Run only specific phases (comma-separated)").option("--no-quality-gate","Skip quality gate enforcement").option("-F, --format <format>","Output format (text|json|markdown)","text").option("-o, --output <path>","Write combined report to file").action(async a=>{if(await s())try{let e,i=null;if(a.config){let f=L(w.resolve(a.config));if(!f.success){console.error(d.red(`
21
+ Config errors:`));for(let v of f.errors)console.error(d.red(` - ${v}`));await r(1);return}e=f.config,i=a.config}else if(i=T(),i){let f=L(i);if(!f.success){console.error(d.red(`
22
+ Config errors:`));for(let v of f.errors)console.error(d.red(` - ${v}`));await r(1);return}e=f.config}else e=M(),i="(defaults)";let c;if(a.phase!==void 0){let f=a.phase.split(",").map(P=>P.trim().toLowerCase()),v=f.filter(P=>!P||!e.phases.some(_=>P===_.name.toLowerCase()||P===_.type));v.length>0&&(c=`Unknown or empty CI phase selector: ${v.map(P=>P||"(empty)").join(", ")}. Available phases: ${e.phases.map(P=>`${P.name} (${P.type})`).join(", ")}`),e.phases=e.phases.filter(P=>f.includes(P.name.toLowerCase())||f.includes(P.type))}a.qualityGate===!1&&(e.qualityGate.enforced=!1);let m=a.format,b=new Date;m==="text"&&(console.log(d.blue(`
23
+ AQE CI Pipeline
24
+ `)),console.log(d.gray(` Config: ${i}`)),console.log(d.gray(` Phases: ${e.phases.length}`)),console.log(d.gray(` Quality Gate: ${e.qualityGate.enforced?"enforced":"advisory"}
25
+ `)));let l=w.resolve(e.output.directory);S.mkdirSync(l,{recursive:!0});let t=w.join(l,"quality-gate.json");S.writeFileSync(t,k({passed:!1,status:"not-run",evidenceStatus:"not-run",enforced:e.qualityGate.enforced,phases:[]}),"utf-8"),c&&console.error(d.red(c));let o=[];for(let f of c?[]:e.phases){if(m==="text"){let P=` [${o.length+1}/${e.phases.length}] ${f.name}...`;process.stdout.write(d.cyan(P))}let v=await oe(f,n,l,o.length,e.qualityGate.thresholds.coverage);if(o.push(v),m==="text"){let P=v.status==="passed"?d.green:v.status==="failed"?d.red:v.status==="warning"?d.yellow:d.gray,_=v.status.toUpperCase(),B=`${(v.duration/1e3).toFixed(1)}s`;process.stdout.write(`\r [${o.length}/${e.phases.length}] ${f.name} ${P(_)} (${B})
26
+ `),v.summary&&console.log(d.gray(` ${v.summary}`))}if(v.status==="failed"&&(v.type!=="quality-gate"||e.qualityGate.enforced)&&!f.continueOnFailure){m==="text"&&console.log(d.red(`
27
+ Pipeline stopped: "${f.name}" failed (continue_on_failure: false)
28
+ `));break}}let g=c!==void 0||o.some(f=>f.status==="failed"&&f.type!=="quality-gate"),p=o.some(f=>f.status==="warning"||f.type==="quality-gate"&&f.status==="failed"&&!e.qualityGate.enforced),q=o.filter(f=>f.type==="quality-gate"),$=e.phases.filter(f=>f.type==="quality-gate").length,C=q.length>0&&q.length===$&&q.every(f=>f.status==="passed"),y=C?"passed":q.some(f=>f.status==="failed")?"failed":"not-run",I=g||e.qualityGate.enforced&&!C?"failed":p?"warning":"passed",x=new Date,G=x.getTime()-b.getTime(),A={config:i||"(defaults)",startedAt:b,completedAt:x,duration:G,phases:o,qualityGatePassed:C,qualityGateStatus:y,qualityGateEnforced:e.qualityGate.enforced,overallStatus:I,exitCode:I==="failed"?1:0,...c?{configurationError:c}:{}};if(S.writeFileSync(t,k({...q.length===1?q[0].details:{},passed:C,status:y,enforced:e.qualityGate.enforced,...y==="not-run"?{evidenceStatus:"not-run"}:{},phases:q}),"utf-8"),e.output.combinedReport){let f=w.join(l,"ci-report.md");S.writeFileSync(f,z(A),"utf-8");let v=w.join(l,"ci-report.json");S.writeFileSync(v,k(A),"utf-8")}if(m==="json")O(k(A),a.output);else if(m==="markdown")O(z(A),a.output);else{console.log("");let f=I==="passed"?d.green:I==="failed"?d.red:d.yellow;console.log(` ${f(`Pipeline: ${I.toUpperCase()}`)} (${(G/1e3).toFixed(1)}s)`),console.log(` Quality Gate: ${X(A)}`),console.log(d.gray(` Artifacts: ${l}/`)),console.log("")}await r(A.exitCode)}catch(e){console.error(d.red(`
29
+ CI pipeline failed:`),e),await r(1)}}),u.command("init").description("Create a .aqe-ci.yml config file").option("--force","Overwrite existing config").action(async a=>{let e=T();if(e&&!a.force){console.log(d.yellow(`
30
+ Config already exists: ${e}`)),console.log(d.gray(` Use --force to overwrite
31
+ `)),await r(0);return}let i=`# AQE CI/CD Pipeline Configuration
32
+ # Documentation: https://github.com/proffesor-for-testing/agentic-qe
33
+
34
+ version: '1'
35
+ name: ${w.basename(process.cwd())}
36
+
37
+ phases:
38
+ - name: Test Generation
39
+ type: test
40
+ config:
41
+ target: .
42
+ framework: vitest
43
+ type: unit
44
+ timeout: 300
45
+
46
+ - name: Coverage Analysis
47
+ type: coverage
48
+ continue_on_failure: true
49
+ config:
50
+ target: .
51
+ threshold: 80
52
+ timeout: 300
53
+
54
+ - name: Security Scan
55
+ type: security
56
+ continue_on_failure: true
57
+ config:
58
+ sast: true
59
+ timeout: 300
60
+
61
+ - name: Quality Gate
62
+ type: quality-gate
63
+ timeout: 60
64
+
65
+ output:
66
+ format: json
67
+ directory: .aqe-ci-output
68
+ combined_report: true
69
+
70
+ quality_gate:
71
+ enforced: true
72
+ thresholds:
73
+ coverage: 80
74
+ security: medium
75
+ quality: 70
76
+ `,c=w.join(process.cwd(),".aqe-ci.yml");S.writeFileSync(c,i,"utf-8"),console.log(d.green(`
77
+ Created: ${c}`)),console.log(d.gray(" Edit the file to customize your CI pipeline")),console.log(d.gray(` Run: aqe ci run
78
+ `)),await r(0)}),u.command("validate").description("Validate .aqe-ci.yml config").option("-c, --config <path>","Path to config file").action(async a=>{let e=a.config?w.resolve(a.config):T();if(!e){console.log(d.red(`
79
+ No .aqe-ci.yml found`)),console.log(d.gray(` Run: aqe ci init
80
+ `)),await r(1);return}let i=L(e);if(i.success){console.log(d.green(`
81
+ Config valid: ${e}`)),console.log(d.gray(` Phases: ${i.config.phases.length}`));for(let c of i.config.phases){let m=c.enabled?d.green("*"):d.gray("o");console.log(` ${m} ${c.name} (${c.type})`)}console.log(d.gray(` Quality Gate: ${i.config.qualityGate.enforced?"enforced":"advisory"}`)),console.log(""),await r(0)}else{console.log(d.red(`
82
+ Config invalid: ${e}`));for(let c of i.errors)console.log(d.red(` - ${c}`));console.log(""),await r(1)}}),u}export{ge as createCICommand};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.7");process.exit(0)}
2
- import{a,b,c,d,e,f,g,h,i,j,k}from"./chunk-2G63VIJE.js";import"./chunk-YO4ESCB4.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.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,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.7");process.exit(0)}
2
- import{a,b}from"./chunk-T77GZF4B.js";import"./chunk-YO4ESCB4.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.0");process.exit(0)}
2
+ import{a,b}from"./chunk-S7QUHLXV.js";import"./chunk-GX5RFGW2.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.14.7");process.exit(0)}
2
- import{a as g}from"./chunk-N5XOXPHZ.js";import{b as p}from"./chunk-MT7UNBZ7.js";import{b as f,d as h}from"./chunk-OIDWDGLG.js";import{a as d,e as v}from"./chunk-ZUOVNFXK.js";import{a as b}from"./chunk-YO4ESCB4.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.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};
@@ -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.0");process.exit(0)}
2
+ import{c as a,d as b,e as c}from"./chunk-MRIZY6HB.js";import"./chunk-S7CROKX4.js";import"./chunk-X5RELRY7.js";import"./chunk-GX5RFGW2.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.14.7");process.exit(0)}
2
- import{b as f}from"./chunk-OEPNNLR4.js";import{a as m,e as v}from"./chunk-ZUOVNFXK.js";import"./chunk-YO4ESCB4.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.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)+`
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.14.7");process.exit(0)}
2
- import{a as T,b as I}from"./chunk-6RD44SCE.js";import{d as $,e as C}from"./chunk-2G63VIJE.js";import"./chunk-YO4ESCB4.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.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",`
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-AZ3LRWEK.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-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(`
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.14.7");process.exit(0)}
2
- import"./chunk-YO4ESCB4.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.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(`
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.14.7");process.exit(0)}
2
- import{a as N}from"./chunk-KUHLTVWC.js";import{a as P}from"./chunk-N5XOXPHZ.js";import{a as j}from"./chunk-NOHWJOBS.js";import{b as I}from"./chunk-OEPNNLR4.js";import"./chunk-OIDWDGLG.js";import{a as b,e as B}from"./chunk-ZUOVNFXK.js";import"./chunk-YO4ESCB4.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.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
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.14.7");process.exit(0)}
2
- import"./chunk-YO4ESCB4.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.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
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.14.7");process.exit(0)}
2
- import{a,b,c,d,e,f,g,h,i}from"./chunk-QQFQDEUE.js";import"./chunk-JOZ47MV6.js";import"./chunk-MZMG6CUJ.js";import"./chunk-TFK2AYIN.js";import"./chunk-YO4ESCB4.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.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,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.7");process.exit(0)}
2
- import{b as m}from"./chunk-OEPNNLR4.js";import{a as u,e as h}from"./chunk-ZUOVNFXK.js";import"./chunk-YO4ESCB4.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.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
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.14.7");process.exit(0)}
2
- import{b as g}from"./chunk-OEPNNLR4.js";import{a as p,e as v}from"./chunk-ZUOVNFXK.js";import"./chunk-YO4ESCB4.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.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)+`
3
3
  `}catch{return r}}};function R(c){return new a(c)}export{a as CopilotInstaller,R as createCopilotInstaller};
@@ -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.0");process.exit(0)}
2
+ import{c as a,d as b,e as c,f as d,g as e,h as f,i as g,j as h,k as i,l as j,m as k,n as l}from"./chunk-7JC3LHA6.js";import"./chunk-DXA7RLYU.js";import"./chunk-4FOKHGP5.js";import"./chunk-JSYNSJDQ.js";import"./chunk-AV3RX2L5.js";import"./chunk-4EEY23JS.js";import"./chunk-6GTIJNRO.js";import"./chunk-DGRE6ZAA.js";import"./chunk-W6H2SOIK.js";import"./chunk-C6M27NQE.js";import"./chunk-LPCFIFZF.js";import"./chunk-JO2YLIZH.js";import"./chunk-P4WE6VRR.js";import"./chunk-VY4557VF.js";import"./chunk-P4FRYNHL.js";import"./chunk-MM57SD2F.js";import"./chunk-P7MNF2SK.js";import"./chunk-LLS6JYPN.js";import"./chunk-Y63DADOR.js";import"./chunk-P725KXHX.js";import"./chunk-5PNRUMRV.js";import"./chunk-P2PPJUGD.js";import"./chunk-A37YYHUD.js";import"./chunk-DSGRXW6K.js";import"./chunk-AQZSF32Y.js";import"./chunk-ZXIIB3QE.js";import"./chunk-ZPH2YT3J.js";import"./chunk-IRHBR56R.js";import"./chunk-EBK6CUBD.js";import"./chunk-ISAMM7QA.js";import"./chunk-2ORTL5WG.js";import"./chunk-PPFW3H7E.js";import"./chunk-G35KP72N.js";import"./chunk-EZPWSS3B.js";import"./chunk-OTJ22IO2.js";import"./chunk-F76SYOBT.js";import"./chunk-FFE4XAQA.js";import"./chunk-O5AUOBGU.js";import"./chunk-62IEVKN3.js";import"./chunk-7D6NVIGP.js";import"./chunk-VQVFGFYK.js";import"./chunk-FTFIA4I5.js";import"./chunk-CZWWC7GC.js";import"./chunk-VTGRGYY4.js";import"./chunk-5KN4QL3G.js";import"./chunk-3Y24VTZ3.js";import"./chunk-HBIV7PQH.js";import"./chunk-X4OESN7M.js";import"./chunk-EQ4SDE4L.js";import"./chunk-PJU5HVWV.js";import"./chunk-MRIZY6HB.js";import"./chunk-S7CROKX4.js";import"./chunk-ZV7LJPSI.js";import"./chunk-ISGFAMHZ.js";import"./chunk-DZHIE5UW.js";import"./chunk-WR54SKKL.js";import"./chunk-N5ZHIQAV.js";import"./chunk-YIDZ3TEN.js";import"./chunk-5DJGP4TA.js";import"./chunk-MEYSIVMP.js";import"./chunk-4YPL3OXS.js";import"./chunk-FTS6NGBP.js";import"./chunk-2ZEV3O24.js";import"./chunk-S2GNFAOC.js";import"./chunk-JLPNYHJJ.js";import"./chunk-VWCFXCSV.js";import"./chunk-XELFJC77.js";import"./chunk-KEZ4PXVF.js";import"./chunk-KUTMQBV4.js";import"./chunk-GCHDMO5V.js";import"./chunk-MFGLRMO4.js";import"./chunk-I3BH3KIF.js";import"./chunk-BAPMEDWC.js";import"./chunk-7JABIXP3.js";import"./chunk-4DCDIKBX.js";import"./chunk-WPOYFV4X.js";import"./chunk-PN3FYSQ6.js";import"./chunk-WQMXQO3O.js";import"./chunk-R6CZCMKD.js";import"./chunk-N2MDNEF7.js";import"./chunk-EPEKEUCF.js";import"./chunk-WO7NPGUD.js";import"./chunk-Z6CRROLU.js";import"./chunk-XEABMIUH.js";import"./chunk-JIWMFLHV.js";import"./chunk-AAQNRZKT.js";import"./chunk-F7JVDLOI.js";import"./chunk-H77AUJNW.js";import"./chunk-VCYOFWMG.js";import"./chunk-KU4WLKDK.js";import"./chunk-URRPJ3M7.js";import"./chunk-QVX22EIM.js";import"./chunk-XZDPR6I2.js";import"./chunk-ILKMNDUM.js";import"./chunk-ATXAMGVE.js";import"./chunk-JJ7WAU4I.js";import"./chunk-7WUHVGGT.js";import"./chunk-UGYXUPGN.js";import"./chunk-HOPXHZA3.js";import"./chunk-B6QTNTCU.js";import"./chunk-WBR4VRQE.js";import"./chunk-4OQSAUKR.js";import"./chunk-WPSGMTI4.js";import"./chunk-GV7P5JYF.js";import"./chunk-MO3QXLF2.js";import"./chunk-VYERAOQL.js";import"./chunk-BH2SQQ2N.js";import"./chunk-5LN7FQZI.js";import"./chunk-AIE6OKCD.js";import"./chunk-OYVDTD3A.js";import"./chunk-OBSX3I4Y.js";import"./chunk-X5RELRY7.js";import"./chunk-URUOTHPO.js";import"./chunk-NZ556KZN.js";import"./chunk-QRALXNNX.js";import"./chunk-X7JEBPEW.js";import"./chunk-CMYZWIXS.js";import"./chunk-AGYPPPXR.js";import"./chunk-WDV6CBED.js";import"./chunk-GX5RFGW2.js";export{c as adoptExternalFleet,e as assignAgentLevel,k as disposeFleet,f as getAgentLevel,g as getAllAgentLevels,a as getFleetState,d as getFleetTopology,l as handleAQEHealth,j as handleFleetHealth,h as handleFleetInit,i as handleFleetStatus,b as isFleetInitialized};