agentic-qe 3.9.1 → 3.9.3

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 (294) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +44 -0
  3. package/dist/cli/bundle.js +8 -8
  4. package/dist/cli/chunks/adapter-WKI55MLS.js +2 -0
  5. package/dist/cli/chunks/{agent-booster-wasm-UH2J6BNA.js → agent-booster-wasm-W6GGSB43.js} +2 -2
  6. package/dist/cli/chunks/{agent-handler-ZCBWQE3X.js → agent-handler-3IRN5WBS.js} +2 -2
  7. package/dist/cli/chunks/{agent-memory-branch-2BAVI7UW.js → agent-memory-branch-SO63CIPJ.js} +2 -2
  8. package/dist/cli/chunks/aqe-learning-engine-QQHHH3ZL.js +2 -0
  9. package/dist/cli/chunks/{audit-G5UIJBSQ.js → audit-TONGHW5H.js} +2 -2
  10. package/dist/cli/chunks/base-3ENVJTIL.js +2 -0
  11. package/dist/cli/chunks/{better-sqlite3-YHIAPPVT.js → better-sqlite3-OK5DP5FC.js} +2 -2
  12. package/dist/cli/chunks/{brain-handler-5EE3J5PR.js → brain-handler-MC2S3UHL.js} +3 -3
  13. package/dist/cli/chunks/{branch-enumerator-OV54PID5.js → branch-enumerator-PRKJKPAE.js} +2 -2
  14. package/dist/cli/chunks/{browser-7RZGKOEO.js → browser-WTMMBSU3.js} +2 -2
  15. package/dist/cli/chunks/browser-workflow-QVT343YP.js +2 -0
  16. package/dist/cli/chunks/{chunk-WLXEDOG4.js → chunk-2CPNZVGL.js} +2 -2
  17. package/dist/cli/chunks/{chunk-VO3OVD5D.js → chunk-2GZ4EG3L.js} +1 -1
  18. package/dist/cli/chunks/{chunk-UMGWGX7C.js → chunk-2IU6WK32.js} +2 -2
  19. package/dist/cli/chunks/{chunk-4LWXZCSD.js → chunk-3GMN3PNP.js} +2 -2
  20. package/dist/cli/chunks/{chunk-XTLA4F5Z.js → chunk-3Q5FG6M3.js} +2 -2
  21. package/dist/cli/chunks/{chunk-O6QQ4HLS.js → chunk-53YFAERL.js} +2 -2
  22. package/dist/cli/chunks/{chunk-TPXYS3WG.js → chunk-5B2KXDWF.js} +1 -1
  23. package/dist/cli/chunks/{chunk-XSITQBYB.js → chunk-5OL6UOBM.js} +3 -3
  24. package/dist/cli/chunks/{chunk-I7TA453K.js → chunk-5UMSMRJC.js} +2 -2
  25. package/dist/cli/chunks/{chunk-ZSRQHJEW.js → chunk-5YUNMBIH.js} +1 -1
  26. package/dist/cli/chunks/{chunk-FRNB4CH2.js → chunk-66RCUQCI.js} +2 -2
  27. package/dist/cli/chunks/{chunk-DMGLX76J.js → chunk-6B4CTO5D.js} +2 -2
  28. package/dist/cli/chunks/{chunk-A57BEPL7.js → chunk-6N26CWST.js} +2 -2
  29. package/dist/cli/chunks/{chunk-UZZCWWIG.js → chunk-7ASGPJWU.js} +1 -1
  30. package/dist/cli/chunks/{chunk-HTXSUTWL.js → chunk-7HTSXZ77.js} +2 -2
  31. package/dist/cli/chunks/{chunk-NB47YT6A.js → chunk-7JBIDAXT.js} +2 -2
  32. package/dist/cli/chunks/{chunk-XPB6ZVQY.js → chunk-AS5WPUDR.js} +1 -1
  33. package/dist/cli/chunks/{chunk-VCCMCFDU.js → chunk-AWSYGQEB.js} +2 -2
  34. package/dist/cli/chunks/{chunk-E33KQBMW.js → chunk-BK445WWE.js} +2 -2
  35. package/dist/cli/chunks/{chunk-RU6Q5HOC.js → chunk-BRCCPQXN.js} +1 -1
  36. package/dist/cli/chunks/{chunk-OTSJU5LH.js → chunk-CF4T4YSL.js} +2 -2
  37. package/dist/cli/chunks/{chunk-O636JKJR.js → chunk-COIFERYS.js} +2 -2
  38. package/dist/cli/chunks/{chunk-JSOBRKMA.js → chunk-CU36MONI.js} +2 -2
  39. package/dist/cli/chunks/{chunk-EQFZQPFN.js → chunk-D5AQDGTS.js} +1 -1
  40. package/dist/cli/chunks/{chunk-3VAKR43Z.js → chunk-D5GIV6O7.js} +1 -1
  41. package/dist/cli/chunks/{chunk-GFNUESMU.js → chunk-DBEU5ISS.js} +2 -2
  42. package/dist/cli/chunks/{chunk-VEWIT6VN.js → chunk-DBSVEWWL.js} +1 -1
  43. package/dist/cli/chunks/{chunk-XP6XKBNW.js → chunk-DGRO6LSI.js} +2 -2
  44. package/dist/cli/chunks/{chunk-5KBQQP3X.js → chunk-DKOOKULB.js} +5 -5
  45. package/dist/cli/chunks/{chunk-GJW6V35N.js → chunk-DTNXHRUF.js} +1 -1
  46. package/dist/cli/chunks/{chunk-7ZNINH6J.js → chunk-ELU576GE.js} +3 -3
  47. package/dist/cli/chunks/{chunk-XE2YAYU5.js → chunk-ERWNQ6NC.js} +3 -3
  48. package/dist/cli/chunks/{chunk-UB7RGVKO.js → chunk-EVIXQR4O.js} +1 -1
  49. package/dist/cli/chunks/{chunk-US7INRP2.js → chunk-EXTVDKH7.js} +3 -3
  50. package/dist/cli/chunks/{chunk-QAYTL6KC.js → chunk-F6O5XLIE.js} +1 -1
  51. package/dist/cli/chunks/{chunk-5GPTM2RV.js → chunk-FIQ62VOQ.js} +1 -1
  52. package/dist/cli/chunks/chunk-FONTSK2O.js +2 -0
  53. package/dist/cli/chunks/{chunk-FPRL6UDF.js → chunk-FR26EINS.js} +2 -2
  54. package/dist/cli/chunks/{chunk-IF6GW6IY.js → chunk-FSUS5TV6.js} +2 -2
  55. package/dist/cli/chunks/{chunk-36X2O3BL.js → chunk-GBLX5XOH.js} +2 -2
  56. package/dist/cli/chunks/{chunk-L4H54Z27.js → chunk-GGEVILIS.js} +2 -2
  57. package/dist/cli/chunks/{chunk-OFNIQCGX.js → chunk-GGKV5IQR.js} +2 -2
  58. package/dist/cli/chunks/{chunk-3JESHZQM.js → chunk-GGQCAQM4.js} +2 -2
  59. package/dist/cli/chunks/{chunk-UBKK7KCR.js → chunk-HJEWQD2B.js} +1 -1
  60. package/dist/cli/chunks/{chunk-QMFP5OKH.js → chunk-HVOOYPW6.js} +2 -2
  61. package/dist/cli/chunks/{chunk-RAJO7VML.js → chunk-IOW7QTYT.js} +2 -2
  62. package/dist/cli/chunks/{chunk-HAUXLXKZ.js → chunk-ITFNPXZL.js} +2 -2
  63. package/dist/cli/chunks/{chunk-YUQIXT3G.js → chunk-J7QGH6PG.js} +2 -2
  64. package/dist/cli/chunks/{chunk-YQWB4QUP.js → chunk-JF6AXXAL.js} +4 -4
  65. package/dist/cli/chunks/{chunk-RXVYOXDB.js → chunk-JI5MNJSU.js} +1 -1
  66. package/dist/cli/chunks/{chunk-C24ZDUCM.js → chunk-JTIWAUWW.js} +1 -1
  67. package/dist/cli/chunks/{chunk-XRVUSKQV.js → chunk-JXE2DFXM.js} +1 -1
  68. package/dist/cli/chunks/{chunk-IHWSNYL2.js → chunk-JZXSKPQB.js} +2 -2
  69. package/dist/cli/chunks/{chunk-SVNX4UWR.js → chunk-K2DDNM4V.js} +8 -8
  70. package/dist/cli/chunks/{chunk-DC3HPOOJ.js → chunk-KV32LAKU.js} +1 -1
  71. package/dist/cli/chunks/{chunk-6BSJNG2S.js → chunk-LDLLHLKE.js} +2 -2
  72. package/dist/cli/chunks/{chunk-NG4TE3OW.js → chunk-LHDR6E6F.js} +2 -2
  73. package/dist/cli/chunks/{chunk-WXXAAXNS.js → chunk-LMN72H3V.js} +1 -1
  74. package/dist/cli/chunks/{chunk-24E47G3D.js → chunk-LQDAH47F.js} +2 -2
  75. package/dist/cli/chunks/chunk-LRE4A464.js +2 -0
  76. package/dist/cli/chunks/{chunk-V4U3CTS2.js → chunk-M3EFT3XR.js} +3 -3
  77. package/dist/cli/chunks/chunk-M7PGW5Z5.js +2 -0
  78. package/dist/cli/chunks/{chunk-43M6Y6VF.js → chunk-MNZ2HHKI.js} +2 -2
  79. package/dist/cli/chunks/{chunk-VY74OMGQ.js → chunk-MSKVWOND.js} +3 -3
  80. package/dist/cli/chunks/{chunk-RWXI7XAR.js → chunk-NZLJWXXM.js} +2 -2
  81. package/dist/cli/chunks/{chunk-FWDKVTK4.js → chunk-O2O5RO4H.js} +2 -2
  82. package/dist/cli/chunks/{chunk-7YUOUVN7.js → chunk-OBOCKH47.js} +2 -2
  83. package/dist/cli/chunks/{chunk-MZ54VM6A.js → chunk-OJKGRB6D.js} +2 -2
  84. package/dist/cli/chunks/{chunk-NG3BKE7V.js → chunk-OV6H3TRU.js} +2 -2
  85. package/dist/cli/chunks/{chunk-UN4PA4M2.js → chunk-OXR2FPHK.js} +2 -2
  86. package/dist/cli/chunks/{chunk-GNUUBTSX.js → chunk-OZNJZMQL.js} +2 -2
  87. package/dist/cli/chunks/{chunk-POLFT2PQ.js → chunk-P4RYVWIR.js} +2 -2
  88. package/dist/cli/chunks/{chunk-RKIGOARX.js → chunk-P6OZKWNK.js} +2 -2
  89. package/dist/cli/chunks/{chunk-WDV6TN7E.js → chunk-PD5YPC2A.js} +6 -6
  90. package/dist/cli/chunks/{chunk-JCEY7RLP.js → chunk-PKIBG7OJ.js} +2 -2
  91. package/dist/cli/chunks/{chunk-KIGRLIU4.js → chunk-PRIWFNVU.js} +2 -2
  92. package/dist/cli/chunks/{chunk-RV6SGDET.js → chunk-PS6KLLLQ.js} +2 -2
  93. package/dist/cli/chunks/{chunk-7ATLJCSG.js → chunk-QAXJOCTW.js} +1 -1
  94. package/dist/cli/chunks/{chunk-VNYGVG4Y.js → chunk-QB2LOM5O.js} +2 -2
  95. package/dist/cli/chunks/{chunk-AFPMCMVX.js → chunk-RRELDHZY.js} +2 -2
  96. package/dist/cli/chunks/{chunk-GLIFZWV2.js → chunk-S23UV7FV.js} +1 -1
  97. package/dist/cli/chunks/{chunk-AREIP4FX.js → chunk-SDHZLA45.js} +2 -2
  98. package/dist/cli/chunks/{chunk-X4MZYBOU.js → chunk-SFFI3MDN.js} +2 -2
  99. package/dist/cli/chunks/{chunk-TL7ABIMP.js → chunk-SJLDTV5B.js} +2 -2
  100. package/dist/cli/chunks/{chunk-6YC24TPL.js → chunk-SVXIAQRW.js} +2 -2
  101. package/dist/cli/chunks/{chunk-YYYB2JN5.js → chunk-T4GTFSB2.js} +2 -2
  102. package/dist/cli/chunks/{chunk-4BHOAQJH.js → chunk-T4RR4YMH.js} +1 -1
  103. package/dist/cli/chunks/{chunk-Y2ZEDXTV.js → chunk-T5MWENBA.js} +2 -2
  104. package/dist/cli/chunks/{chunk-5LDBKZ6P.js → chunk-TA454OEB.js} +1 -1
  105. package/dist/cli/chunks/{chunk-SGRN6JFB.js → chunk-TPFE3BAI.js} +2 -2
  106. package/dist/cli/chunks/{chunk-IJKYJGJL.js → chunk-TSS6LXJ6.js} +1 -1
  107. package/dist/cli/chunks/{chunk-4XBY5JDT.js → chunk-TTEXJW2U.js} +2 -2
  108. package/dist/cli/chunks/{chunk-B2I7BJLL.js → chunk-TUHIFT65.js} +2 -2
  109. package/dist/cli/chunks/{chunk-BEHP3DEF.js → chunk-U6QQS5Z3.js} +2 -2
  110. package/dist/cli/chunks/{chunk-35H73OPP.js → chunk-UC3RA5LW.js} +2 -2
  111. package/dist/cli/chunks/{chunk-V4HM4QAO.js → chunk-UVWKIP3U.js} +3 -3
  112. package/dist/cli/chunks/{chunk-XU6L2VJY.js → chunk-VNSRA5PY.js} +2 -2
  113. package/dist/cli/chunks/{chunk-WDJBGXC2.js → chunk-WAWCNUIJ.js} +1 -1
  114. package/dist/cli/chunks/{chunk-LCOEBFAB.js → chunk-WDTFG5AG.js} +1 -1
  115. package/dist/cli/chunks/{chunk-UWDBFPHQ.js → chunk-WIY3V5VQ.js} +14 -14
  116. package/dist/cli/chunks/{chunk-IQPXANCE.js → chunk-WLK5UVRJ.js} +1 -1
  117. package/dist/cli/chunks/{chunk-XUFHYPZK.js → chunk-WSVWVIVR.js} +2 -2
  118. package/dist/cli/chunks/{chunk-3WQNW6CH.js → chunk-X5C73DW5.js} +2 -2
  119. package/dist/cli/chunks/{chunk-4TNXEANY.js → chunk-XJII5WMD.js} +1 -1
  120. package/dist/cli/chunks/{chunk-I5WZ2NM2.js → chunk-YTBE2MEW.js} +4 -4
  121. package/dist/cli/chunks/{chunk-TOLYWONQ.js → chunk-Z4V3XV7E.js} +2 -2
  122. package/dist/cli/chunks/{chunk-ZEUVPLGX.js → chunk-ZMUVSL5Q.js} +2 -2
  123. package/dist/cli/chunks/{chunk-7JQTHPCD.js → chunk-ZQCU62JJ.js} +2 -2
  124. package/dist/cli/chunks/{chunk-D4PSFWND.js → chunk-ZTIPMKUS.js} +1 -1
  125. package/dist/cli/chunks/{chunk-D55PSO5D.js → chunk-ZVMAE5JD.js} +1 -1
  126. package/dist/cli/chunks/{ci-N4NTYAAI.js → ci-XQEZTRJN.js} +2 -2
  127. package/dist/cli/chunks/{ci-output-XYR2PSYH.js → ci-output-ZWGXOIUD.js} +2 -2
  128. package/dist/cli/chunks/{claude-flow-setup-FX7PRBJV.js → claude-flow-setup-PFJFHZSD.js} +2 -2
  129. package/dist/cli/chunks/client-VUKA3X4R.js +2 -0
  130. package/dist/cli/chunks/{cline-installer-GTHQOK7U.js → cline-installer-L3WC4KUM.js} +2 -2
  131. package/dist/cli/chunks/{code-4G6ZHVNI.js → code-QMDXXY6C.js} +2 -2
  132. package/dist/cli/chunks/{code-index-extractor-MKJTP5AK.js → code-index-extractor-YTPMAZPU.js} +2 -2
  133. package/dist/cli/chunks/{codex-installer-UGS773DT.js → codex-installer-KO5G7LHQ.js} +2 -2
  134. package/dist/cli/chunks/{completions-B3BXNXAU.js → completions-KVDPIXMY.js} +2 -2
  135. package/dist/cli/chunks/{complexity-analyzer-PMN77CUP.js → complexity-analyzer-KNIBPEC3.js} +2 -2
  136. package/dist/cli/chunks/{continuedev-installer-3DYKSIP3.js → continuedev-installer-N2GWI5PC.js} +2 -2
  137. package/dist/cli/chunks/{copilot-installer-IUC5HDHD.js → copilot-installer-EX3UTDQN.js} +2 -2
  138. package/dist/cli/chunks/{cost-tracker-GSGQ7O5T.js → cost-tracker-XX6OMP37.js} +2 -2
  139. package/dist/cli/chunks/{coverage-PO72QC3P.js → coverage-FHDDNCPO.js} +3 -3
  140. package/dist/cli/chunks/cross-domain-router-5SUV5AP6.js +2 -0
  141. package/dist/cli/chunks/{cursor-installer-FK53S3ZL.js → cursor-installer-M47YCQU7.js} +2 -2
  142. package/dist/cli/chunks/{daemon-4UIQTQ73.js → daemon-EV3RXWAG.js} +3 -3
  143. package/dist/cli/chunks/{dag-attention-scheduler-ZGIMLECE.js → dag-attention-scheduler-J7JDWG5J.js} +2 -2
  144. package/dist/cli/chunks/{detect-XXHLTLL7.js → detect-4P5RKV5J.js} +2 -2
  145. package/dist/cli/chunks/{domain-handler-PPGFP7P4.js → domain-handler-Q35TYDGA.js} +2 -2
  146. package/dist/cli/chunks/{domain-transfer-Q5UAE65W.js → domain-transfer-XC34MV5U.js} +2 -2
  147. package/dist/cli/chunks/dream-2UNEPNI2.js +2 -0
  148. package/dist/cli/chunks/esm-node-TPR2KU6L.js +2 -0
  149. package/dist/cli/chunks/{eval-JVJKHSTQ.js → eval-QZGRW7XD.js} +2 -2
  150. package/dist/cli/chunks/{fast-paths-3KX4ZV66.js → fast-paths-O42GG56B.js} +2 -2
  151. package/dist/cli/chunks/{feature-flags-GKHHG2I2.js → feature-flags-G6SJTDVO.js} +2 -2
  152. package/dist/cli/chunks/{feature-flags-2NOVE7DL.js → feature-flags-GIGWUPEX.js} +2 -2
  153. package/dist/cli/chunks/{file-discovery-XFSGQNM3.js → file-discovery-D4NXB3JP.js} +2 -2
  154. package/dist/cli/chunks/{fleet-FOIDAXLR.js → fleet-ZXZ5AAPW.js} +3 -3
  155. package/dist/cli/chunks/{gnn-wrapper-HPCQREKP.js → gnn-wrapper-YK6NAPJV.js} +2 -2
  156. package/dist/cli/chunks/{heartbeat-handler-HTR3EFFV.js → heartbeat-handler-DD4T6U36.js} +4 -4
  157. package/dist/cli/chunks/{heartbeat-scheduler-NZQWN7CH.js → heartbeat-scheduler-CBPO5KUB.js} +2 -2
  158. package/dist/cli/chunks/hnsw-adapter-BLMGBVDE.js +2 -0
  159. package/dist/cli/chunks/hnsw-index-UWMXU7RN.js +2 -0
  160. package/dist/cli/chunks/{hnsw-legacy-bridge-H6OA3AA3.js → hnsw-legacy-bridge-REKPPJ75.js} +2 -2
  161. package/dist/cli/chunks/{hnswlib-node-FF27BDMD.js → hnswlib-node-PMWK24KT.js} +2 -2
  162. package/dist/cli/chunks/{hooks-63NZQ7NH.js → hooks-UDKFTCJ7.js} +6 -6
  163. package/dist/cli/chunks/{hypergraph-engine-XMSLA4XH.js → hypergraph-engine-FIAZJD7K.js} +2 -2
  164. package/dist/cli/chunks/{hypergraph-handler-ID6J6GS2.js → hypergraph-handler-NN2EBNBW.js} +3 -3
  165. package/dist/cli/chunks/impact-analyzer-RK2VPRRL.js +2 -0
  166. package/dist/cli/chunks/{init-handler-CIKZGGAY.js → init-handler-RK256F2M.js} +6 -6
  167. package/dist/cli/chunks/init-wizard-HA2VADPV.js +2 -0
  168. package/dist/cli/chunks/kernel-QMZBPOWP.js +2 -0
  169. package/dist/cli/chunks/{kilocode-installer-N7NLISYY.js → kilocode-installer-6XPW7IAO.js} +2 -2
  170. package/dist/cli/chunks/{kiro-installer-U6XIPAT3.js → kiro-installer-DOHZGTBZ.js} +2 -2
  171. package/dist/cli/chunks/knowledge-graph-INYQCVMS.js +2 -0
  172. package/dist/cli/chunks/{learning-NKOF7KDJ.js → learning-GRSMZRPZ.js} +3 -3
  173. package/dist/cli/chunks/{llm-router-34WHT3PH.js → llm-router-MTZPLM7A.js} +2 -2
  174. package/dist/cli/chunks/{load-ZW4Z3YLT.js → load-CQXXMUR7.js} +2 -2
  175. package/dist/cli/chunks/load-test-YSEU2TUL.js +2 -0
  176. package/dist/cli/chunks/mcp-IIPV4IWF.js +2 -0
  177. package/dist/cli/chunks/{memory-OUYCBU4M.js → memory-GIODHUAL.js} +5 -5
  178. package/dist/cli/chunks/memory-backend-MNSPY44E.js +2 -0
  179. package/dist/cli/chunks/memory-handlers-O6UVJSAG.js +2 -0
  180. package/dist/cli/chunks/{opencode-installer-FR75GHFU.js → opencode-installer-DDIIEIKL.js} +2 -2
  181. package/dist/cli/chunks/{orchestrator-AK7ZMVNH.js → orchestrator-PAQTJDA3.js} +18 -19
  182. package/dist/cli/chunks/{pipeline-CFOPG7EM.js → pipeline-6HFLH75G.js} +2 -2
  183. package/dist/cli/chunks/{platform-NY3ULBR7.js → platform-UKK776G2.js} +2 -2
  184. package/dist/cli/chunks/{plugin-LRANQYUR.js → plugin-ERW5YBXU.js} +2 -2
  185. package/dist/cli/chunks/{prime-radiant-advanced-wasm-6KEIU55P.js → prime-radiant-advanced-wasm-WB5A4ULB.js} +2 -2
  186. package/dist/cli/chunks/protocol-executor-CBKER6RL.js +2 -0
  187. package/dist/cli/chunks/{protocol-handler-ESSZGJ7R.js → protocol-handler-AKDFZI6G.js} +2 -2
  188. package/dist/cli/chunks/{prove-EF2PPY65.js → prove-GT5XEWVF.js} +2 -2
  189. package/dist/cli/chunks/qe-reasoning-bank-C3J4RA2M.js +2 -0
  190. package/dist/cli/chunks/{quality-AYBXB635.js → quality-VZAG6B54.js} +2 -2
  191. package/dist/cli/chunks/queen-coordinator-ZXTNAEYV.js +2 -0
  192. package/dist/cli/chunks/{real-embeddings-QPBXE7MA.js → real-embeddings-KOOT5MTA.js} +2 -2
  193. package/dist/cli/chunks/{roocode-installer-UF6MMBH6.js → roocode-installer-KHGDU6QK.js} +2 -2
  194. package/dist/cli/chunks/router-YMQF6M2D.js +2 -0
  195. package/dist/cli/chunks/routing-feedback-MM7LNDS7.js +2 -0
  196. package/dist/cli/chunks/{routing-handler-5TVKFU7V.js → routing-handler-HVCNYSJM.js} +2 -2
  197. package/dist/cli/chunks/{ruvector-commands-E33VXFIA.js → ruvector-commands-D46MOJ32.js} +2 -2
  198. package/dist/cli/chunks/{rvf-dual-writer-O3AZKD24.js → rvf-dual-writer-WASNBBMN.js} +2 -2
  199. package/dist/cli/chunks/{rvf-migration-adapter-IKEUZ2HX.js → rvf-migration-adapter-ESLGEE5X.js} +2 -2
  200. package/dist/cli/chunks/{rvf-migration-coordinator-M4H7W4RN.js → rvf-migration-coordinator-S5NAMHTP.js} +2 -2
  201. package/dist/cli/chunks/rvf-native-adapter-3EEWPK4C.js +2 -0
  202. package/dist/cli/chunks/safe-db-5P6ABYNG.js +2 -0
  203. package/dist/cli/chunks/schedule-ZGESH3FK.js +2 -0
  204. package/dist/cli/chunks/scheduler-AC4AA2BD.js +2 -0
  205. package/dist/cli/chunks/{security-ZLWT7IU3.js → security-4AHBDCJJ.js} +3 -3
  206. package/dist/cli/chunks/shared-rvf-adapter-UQQUEC52.js +2 -0
  207. package/dist/cli/chunks/{shared-rvf-dual-writer-G43LQDIV.js → shared-rvf-dual-writer-ZFNW4C3N.js} +2 -2
  208. package/dist/cli/chunks/sqlite-persistence-KXDW2Q66.js +2 -0
  209. package/dist/cli/chunks/{status-handler-7P23CXUI.js → status-handler-ZVC4HX5J.js} +2 -2
  210. package/dist/cli/chunks/{structural-health-SCNBNL7K.js → structural-health-DPFQ4GEF.js} +2 -2
  211. package/dist/cli/chunks/{sync-BYZBBH65.js → sync-7A5JMQNB.js} +2 -2
  212. package/dist/cli/chunks/{task-handler-DWJQXZ2K.js → task-handler-OFZ5YMXH.js} +2 -2
  213. package/dist/cli/chunks/task-handlers-IRSHSFQW.js +2 -0
  214. package/dist/cli/chunks/{test-2JSS4XW7.js → test-F6XPB2DN.js} +4 -4
  215. package/dist/cli/chunks/{test-scheduling-TWJ5I7N3.js → test-scheduling-CPHQ7DBP.js} +3 -3
  216. package/dist/cli/chunks/token-bootstrap-5YD6K4LL.js +2 -0
  217. package/dist/cli/chunks/{token-usage-EQ4HM4EZ.js → token-usage-KQYGQAEK.js} +2 -2
  218. package/dist/cli/chunks/{transformers-PBIR5U5S.js → transformers-P7TT2MJB.js} +2 -2
  219. package/dist/cli/chunks/{tree-sitter-wasm-parser-X3L2GXUX.js → tree-sitter-wasm-parser-SUSDXGOP.js} +2 -2
  220. package/dist/cli/chunks/{types-OD43K2NP.js → types-OEGMO7AH.js} +2 -2
  221. package/dist/cli/chunks/unified-memory-MNW25PVU.js +2 -0
  222. package/dist/cli/chunks/unified-memory-hnsw-4RZRP37O.js +2 -0
  223. package/dist/cli/chunks/unified-persistence-6UBNXF25.js +2 -0
  224. package/dist/cli/chunks/{validate-POMLT2KU.js → validate-XI4GTLQR.js} +2 -2
  225. package/dist/cli/chunks/{validate-swarm-UOC4JGZT.js → validate-swarm-UZQR6AWZ.js} +2 -2
  226. package/dist/cli/chunks/{vibium-5JF6LAXI.js → vibium-VPJH2KD5.js} +2 -2
  227. package/dist/cli/chunks/visual-security-7742DBSK.js +2 -0
  228. package/dist/cli/chunks/{web-tree-sitter-R7WR7J7B.js → web-tree-sitter-LUNFY67E.js} +2 -2
  229. package/dist/cli/chunks/{windsurf-installer-ZSPEUBKR.js → windsurf-installer-LTJCP7AT.js} +2 -2
  230. package/dist/cli/chunks/witness-chain-QVPNOHDC.js +2 -0
  231. package/dist/cli/chunks/{witness-chain-CFSPCXHG.js → witness-chain-YWBIN5MQ.js} +2 -2
  232. package/dist/cli/chunks/{workflow-YNQT3OW2.js → workflow-UGXLNO36.js} +4 -4
  233. package/dist/cli/chunks/workflow-orchestrator-K3Q2GOEG.js +2 -0
  234. package/dist/cli/chunks/{wrappers-BP4FODVH.js → wrappers-LUJRP2YI.js} +2 -2
  235. package/dist/cli/commands/mcp.js +27 -17
  236. package/dist/cli/index.js +10 -15
  237. package/dist/init/phases/06-code-intelligence.d.ts +33 -1
  238. package/dist/init/phases/06-code-intelligence.js +125 -10
  239. package/dist/init/phases/10-workers.d.ts +0 -14
  240. package/dist/init/phases/10-workers.js +19 -164
  241. package/dist/kernel/hnsw-adapter.d.ts +14 -0
  242. package/dist/kernel/hnsw-adapter.js +25 -1
  243. package/dist/kernel/hnsw-index-provider.d.ts +16 -0
  244. package/dist/kernel/native-hnsw-backend.d.ts +11 -0
  245. package/dist/kernel/native-hnsw-backend.js +20 -0
  246. package/dist/kernel/progressive-hnsw-backend.d.ts +9 -0
  247. package/dist/kernel/progressive-hnsw-backend.js +41 -12
  248. package/dist/kernel/unified-memory.js +10 -0
  249. package/dist/learning/pattern-store.js +25 -3
  250. package/dist/learning/rvf-pattern-store.d.ts +3 -0
  251. package/dist/learning/rvf-pattern-store.js +4 -2
  252. package/dist/mcp/bundle.js +272 -272
  253. package/dist/optimization/token-optimizer-service.d.ts +31 -2
  254. package/dist/optimization/token-optimizer-service.js +85 -23
  255. package/package.json +1 -1
  256. package/dist/cli/chunks/adapter-NTM4ZH3P.js +0 -2
  257. package/dist/cli/chunks/aqe-learning-engine-RVX6MPYK.js +0 -2
  258. package/dist/cli/chunks/base-7HKNQ6UP.js +0 -2
  259. package/dist/cli/chunks/browser-workflow-UOFSQK7X.js +0 -2
  260. package/dist/cli/chunks/chunk-4XREPCBZ.js +0 -2
  261. package/dist/cli/chunks/chunk-U5JQGRHZ.js +0 -2
  262. package/dist/cli/chunks/client-CRRENRK4.js +0 -2
  263. package/dist/cli/chunks/cross-domain-router-FSCGJG3B.js +0 -2
  264. package/dist/cli/chunks/dream-PONKQULG.js +0 -2
  265. package/dist/cli/chunks/esm-node-XLWDJRBX.js +0 -2
  266. package/dist/cli/chunks/hnsw-adapter-BNA5WUAB.js +0 -2
  267. package/dist/cli/chunks/hnsw-index-RQIIAE7S.js +0 -2
  268. package/dist/cli/chunks/impact-analyzer-FS2UNVP4.js +0 -2
  269. package/dist/cli/chunks/init-wizard-TUU5PPY6.js +0 -2
  270. package/dist/cli/chunks/kernel-XFG42WAG.js +0 -2
  271. package/dist/cli/chunks/knowledge-graph-XV7FPU2T.js +0 -2
  272. package/dist/cli/chunks/load-test-F4L7RTXJ.js +0 -2
  273. package/dist/cli/chunks/mcp-6R7SVGKO.js +0 -2
  274. package/dist/cli/chunks/memory-backend-DTJD2DWF.js +0 -2
  275. package/dist/cli/chunks/memory-handlers-WNXKZRNM.js +0 -2
  276. package/dist/cli/chunks/protocol-executor-6W4PS2D4.js +0 -2
  277. package/dist/cli/chunks/qe-reasoning-bank-7G3TZLEA.js +0 -2
  278. package/dist/cli/chunks/queen-coordinator-NFPKGMQN.js +0 -2
  279. package/dist/cli/chunks/router-F4B7Q66G.js +0 -2
  280. package/dist/cli/chunks/routing-feedback-5CIDDW7P.js +0 -2
  281. package/dist/cli/chunks/rvf-native-adapter-UX3WAPIP.js +0 -2
  282. package/dist/cli/chunks/safe-db-QBBNXEVK.js +0 -2
  283. package/dist/cli/chunks/schedule-GFT4NN6Z.js +0 -2
  284. package/dist/cli/chunks/scheduler-CQ56T7DB.js +0 -2
  285. package/dist/cli/chunks/shared-rvf-adapter-EXACQ2PT.js +0 -2
  286. package/dist/cli/chunks/sqlite-persistence-JHSUZPAW.js +0 -2
  287. package/dist/cli/chunks/task-handlers-35JIXVRW.js +0 -2
  288. package/dist/cli/chunks/token-bootstrap-LLLNJT5V.js +0 -2
  289. package/dist/cli/chunks/unified-memory-YPHONR2T.js +0 -2
  290. package/dist/cli/chunks/unified-memory-hnsw-HJS4OXWM.js +0 -2
  291. package/dist/cli/chunks/unified-persistence-EFZRO6AW.js +0 -2
  292. package/dist/cli/chunks/visual-security-7KWFLYNB.js +0 -2
  293. package/dist/cli/chunks/witness-chain-RWU6WT37.js +0 -2
  294. package/dist/cli/chunks/workflow-orchestrator-Z6TAVMQP.js +0 -2
@@ -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.9.1");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
2
  import{readFileSync as O,existsSync as x,readdirSync as A}from"fs";import{join as y,basename as v}from"path";function m(r){let e=[];if(!r||typeof r!="object")return e.push("Overlay must be a non-null object"),e;let t=r;if((!t.agent||typeof t.agent!="string")&&e.push('Overlay must have a string "agent" field'),t.replace!==void 0)if(typeof t.replace!="object"||t.replace===null)e.push('"replace" must be an object');else{let n=t.replace;n.description!==void 0&&typeof n.description!="string"&&e.push('"replace.description" must be a string'),n.domains!==void 0&&!Array.isArray(n.domains)&&e.push('"replace.domains" must be an array'),n.complexity!==void 0&&typeof n.complexity!="string"&&e.push('"replace.complexity" must be a string')}if(t.append!==void 0)if(typeof t.append!="object"||t.append===null)e.push('"append" must be an object');else{let n=t.append;n.instructions!==void 0&&typeof n.instructions!="string"&&e.push('"append.instructions" must be a string'),n.capabilities!==void 0&&!Array.isArray(n.capabilities)&&e.push('"append.capabilities" must be an array'),n.tags!==void 0&&!Array.isArray(n.tags)&&e.push('"append.tags" must be an array')}if(t.config!==void 0)if(typeof t.config!="object"||t.config===null)e.push('"config" must be an object');else{let n=t.config;n.minimumFindings!==void 0&&typeof n.minimumFindings!="number"&&e.push('"config.minimumFindings" must be a number'),n.maxParallelAgents!==void 0&&typeof n.maxParallelAgents!="number"&&e.push('"config.maxParallelAgents" must be a number'),n.preferredFrameworks!==void 0&&!Array.isArray(n.preferredFrameworks)&&e.push('"config.preferredFrameworks" must be an array'),n.needsContext!==void 0&&typeof n.needsContext!="boolean"&&e.push('"config.needsContext" must be a boolean')}return e}var w=".claude/agent-overrides";function $(r){let e={},t=r.split(`
3
3
  `),n=null,i=null,s=null,a=null;for(let o of t){let l=o.replace(/\r$/,"");if(l.trim().startsWith("#")||l.trim()==="")continue;let u=l.length-l.trimStart().length,g=l.trim();if(g.startsWith("- ")){let c=g.slice(2).trim().replace(/^["']|["']$/g,"");s&&s.push(c);continue}if(s&&a){if(i&&n){let c=e[n]||{};c[a]=s,e[n]=c}else if(n){let c=e[n]||{};c[a]=s,e[n]=c}s=null,a=null}let f=g.match(/^(\w[\w.-]*)\s*:\s*(.*)$/);if(!f)continue;let[,p,b]=f,d=b.trim().replace(/^["']|["']$/g,"");if(u===0)d===""||d===void 0?(n=p,i=null,e[p]||(e[p]={})):(e[p]=h(d),n=null,i=null);else if(u<=4&&n)if(d===""||d===void 0)i=p,s=[],a=p;else{let c=e[n]||{};c[p]=h(d),e[n]=c}}if(s&&a&&n){let o=e[n]||{};o[a]=s,e[n]=o}return e}function h(r){if(r==="true")return!0;if(r==="false")return!1;if(r==="null")return null;let e=Number(r);return!isNaN(e)&&r!==""?e:r}function N(r){let e=y(r,w),t={overlays:[],warnings:[],errors:[]};if(!x(e))return t;let n;try{n=A(e).filter(i=>(i.endsWith(".yaml")||i.endsWith(".yml"))&&!i.startsWith("_"))}catch(i){return t.errors.push(`Failed to read overrides directory: ${i.message}`),t}for(let i of n){let s=y(e,i);try{let a=O(s,"utf-8"),o=$(a);if(!o.agent){let u=v(i).replace(/\.(override|customize)\.(yaml|yml)$/,"");o.agent=u}let l=m(o);if(l.length>0){t.warnings.push(`Overlay ${i} has validation issues: ${l.join("; ")}. Loading without overlay.`);continue}t.overlays.push(o)}catch(a){t.warnings.push(`Failed to parse overlay ${i}: ${a.message}. Agent loads without overlay.`)}}return t}function E(r,e){let t=r,n={agentName:e.agent,overlayFile:`${e.agent}.override.yaml`,replacedFields:[],appendedFields:[],configOverrides:[]};if(e.replace){if(e.replace.description){let i=/^(description:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.description}`),n.replacedFields.push("description"))}if(e.replace.domains){let i=/^(domain:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.domains.join(", ")}`),n.replacedFields.push("domains"))}if(e.replace.complexity){let i=/^(complexity:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.complexity}`),n.replacedFields.push("complexity"))}}if(e.append){if(e.append.instructions&&(t+=`
4
4
 
@@ -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.9.1");process.exit(0)}
2
- import{c as t}from"./chunk-UZZCWWIG.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
+ import{c as t}from"./chunk-7ASGPJWU.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r as d};
@@ -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.9.1");process.exit(0)}
2
- import{S as f,b as p}from"./chunk-MZ54VM6A.js";f();var y={predictionWindowSize:10,compressionThreshold:.3,maxConcurrentStreams:8,oscillationFrequencyMs:100};function d(s){try{return JSON.stringify(s).length}catch{return 0}}function w(s,t){let e={},n=!1;for(let r of Object.keys(t))JSON.stringify(s[r])!==JSON.stringify(t[r])&&(e[r]=t[r],n=!0);for(let r of Object.keys(s))r in t||(e[r]=void 0,n=!0);return n?e:null}function v(s,t){let e={...s};for(let[n,r]of Object.entries(t))r===void 0?delete e[n]:e[n]=r;return e}var l=class{windowSize;windows=new Map;constructor(t){this.windowSize=Math.max(1,t)}predict(t){let e=this.windows.get(t);if(!e||e.length===0)return null;let n=e[e.length-1];return typeof n!="object"||n===null||Array.isArray(n)?null:{...n}}record(t,e){let n=this.windows.get(t);n||(n=[],this.windows.set(t,n)),n.push(e),n.length>this.windowSize&&n.shift()}removeStream(t){this.windows.delete(t)}},h=class{maxStreams;cycleMs;streamIds=[];currentIndex=0;constructor(t,e){this.maxStreams=Math.max(1,t),this.cycleMs=Math.max(1,e)}addStream(t){return this.streamIds.includes(t)||this.streamIds.length>=this.maxStreams?!1:(this.streamIds.push(t),!0)}removeStream(t){let e=this.streamIds.indexOf(t);return e===-1?!1:(this.streamIds.splice(e,1),this.currentIndex>=this.streamIds.length&&(this.currentIndex=0),!0)}nextStream(){if(this.streamIds.length===0)return null;let t=this.streamIds[this.currentIndex];return this.currentIndex=(this.currentIndex+1)%this.streamIds.length,t}getActiveStreams(){return[...this.streamIds]}get activeCount(){return this.streamIds.length}},g=class{config;predictor;router;lastPayloads=new Map;totalMessages=0;compressedMessages=0;totalOriginalBytes=0;totalCompressedBytes=0;constructor(t){this.config={...y,...t},this.predictor=new l(this.config.predictionWindowSize),this.router=new h(this.config.maxConcurrentStreams,this.config.oscillationFrequencyMs)}send(t,e,n,r){this.totalMessages++;let i=d(r);this.totalOriginalBytes+=i;let c=!1,o=r,a=i;if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let m=this.predictor.predict(t);if(m){let u=w(m,r);u?1-d(u)/Math.max(i,1)>=this.config.compressionThreshold&&(o={__delta:!0,__changes:u},a=d(o),c=!0,this.compressedMessages++):(o={__delta:!0,__changes:{}},a=d(o),c=!0,this.compressedMessages++)}}return this.totalCompressedBytes+=a,this.predictor.record(t,r),this.lastPayloads.set(t,r),{streamId:t,senderId:e,receiverId:n,payload:o,compressed:c,originalSize:i,compressedSize:a,timestamp:Date.now()}}receive(t){if(!t.compressed||typeof t.payload!="object"||t.payload===null)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let e=t.payload;if(!e.__delta)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let n=this.predictor.predict(t.streamId),r=e.__changes??{};if(!n)return r;let i=v(n,r);return this.predictor.record(t.streamId,i),this.lastPayloads.set(t.streamId,i),i}getStats(){let t=this.totalOriginalBytes-this.totalCompressedBytes;return{totalMessages:this.totalMessages,compressedMessages:this.compressedMessages,bandwidthSavedBytes:Math.max(0,t),bandwidthReductionPercent:this.totalOriginalBytes>0?Math.max(0,t)/this.totalOriginalBytes*100:0,activeStreams:this.router.activeCount}}addStream(t){this.router.addStream(t)}removeStream(t){this.router.removeStream(t),this.predictor.removeStream(t),this.lastPayloads.delete(t)}};function M(s){return S()?new g(s):null}function S(){return p().useCognitiveRouting}export{M as a,S as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
+ import{S as f,b as p}from"./chunk-OJKGRB6D.js";f();var y={predictionWindowSize:10,compressionThreshold:.3,maxConcurrentStreams:8,oscillationFrequencyMs:100};function d(s){try{return JSON.stringify(s).length}catch{return 0}}function w(s,t){let e={},n=!1;for(let r of Object.keys(t))JSON.stringify(s[r])!==JSON.stringify(t[r])&&(e[r]=t[r],n=!0);for(let r of Object.keys(s))r in t||(e[r]=void 0,n=!0);return n?e:null}function v(s,t){let e={...s};for(let[n,r]of Object.entries(t))r===void 0?delete e[n]:e[n]=r;return e}var l=class{windowSize;windows=new Map;constructor(t){this.windowSize=Math.max(1,t)}predict(t){let e=this.windows.get(t);if(!e||e.length===0)return null;let n=e[e.length-1];return typeof n!="object"||n===null||Array.isArray(n)?null:{...n}}record(t,e){let n=this.windows.get(t);n||(n=[],this.windows.set(t,n)),n.push(e),n.length>this.windowSize&&n.shift()}removeStream(t){this.windows.delete(t)}},h=class{maxStreams;cycleMs;streamIds=[];currentIndex=0;constructor(t,e){this.maxStreams=Math.max(1,t),this.cycleMs=Math.max(1,e)}addStream(t){return this.streamIds.includes(t)||this.streamIds.length>=this.maxStreams?!1:(this.streamIds.push(t),!0)}removeStream(t){let e=this.streamIds.indexOf(t);return e===-1?!1:(this.streamIds.splice(e,1),this.currentIndex>=this.streamIds.length&&(this.currentIndex=0),!0)}nextStream(){if(this.streamIds.length===0)return null;let t=this.streamIds[this.currentIndex];return this.currentIndex=(this.currentIndex+1)%this.streamIds.length,t}getActiveStreams(){return[...this.streamIds]}get activeCount(){return this.streamIds.length}},g=class{config;predictor;router;lastPayloads=new Map;totalMessages=0;compressedMessages=0;totalOriginalBytes=0;totalCompressedBytes=0;constructor(t){this.config={...y,...t},this.predictor=new l(this.config.predictionWindowSize),this.router=new h(this.config.maxConcurrentStreams,this.config.oscillationFrequencyMs)}send(t,e,n,r){this.totalMessages++;let i=d(r);this.totalOriginalBytes+=i;let c=!1,o=r,a=i;if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let m=this.predictor.predict(t);if(m){let u=w(m,r);u?1-d(u)/Math.max(i,1)>=this.config.compressionThreshold&&(o={__delta:!0,__changes:u},a=d(o),c=!0,this.compressedMessages++):(o={__delta:!0,__changes:{}},a=d(o),c=!0,this.compressedMessages++)}}return this.totalCompressedBytes+=a,this.predictor.record(t,r),this.lastPayloads.set(t,r),{streamId:t,senderId:e,receiverId:n,payload:o,compressed:c,originalSize:i,compressedSize:a,timestamp:Date.now()}}receive(t){if(!t.compressed||typeof t.payload!="object"||t.payload===null)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let e=t.payload;if(!e.__delta)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let n=this.predictor.predict(t.streamId),r=e.__changes??{};if(!n)return r;let i=v(n,r);return this.predictor.record(t.streamId,i),this.lastPayloads.set(t.streamId,i),i}getStats(){let t=this.totalOriginalBytes-this.totalCompressedBytes;return{totalMessages:this.totalMessages,compressedMessages:this.compressedMessages,bandwidthSavedBytes:Math.max(0,t),bandwidthReductionPercent:this.totalOriginalBytes>0?Math.max(0,t)/this.totalOriginalBytes*100:0,activeStreams:this.router.activeCount}}addStream(t){this.router.addStream(t)}removeStream(t){this.router.removeStream(t),this.predictor.removeStream(t),this.lastPayloads.delete(t)}};function M(s){return S()?new g(s):null}function S(){return p().useCognitiveRouting}export{M as a,S as b};
@@ -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.9.1");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
2
  function M(u){let e=u|0;return()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}var A=2,y=10,x=200,p=1e-8,b=class{epsilon;seed;constructor(e){if(this.epsilon=e?.epsilon??.3,this.seed=e?.seed,this.epsilon<=0||this.epsilon>=1)throw new Error("SparsifierConfig.epsilon must be in (0, 1)")}sparsify(e){if(e.nodeCount<=0||e.edges.length===0)return{nodeCount:e.nodeCount,edges:[]};let n=this.seed!==void 0?M(this.seed):Math.random,t=this.approximateEffectiveResistances(e),i=e.nodeCount,r=e.edges.length,o=Math.max(1,Math.log(i)),m=this.epsilon*this.epsilon,l=Math.min(r,Math.max(i-1,A*(i-1)*(1-this.epsilon))),s=new Float64Array(r),c=0;for(let a=0;a<r;a++){let d=e.edges[a][2];s[a]=d*t[a],c+=s[a]}if(c<=0)return{nodeCount:e.nodeCount,edges:[]};let f=[];for(let a=0;a<r;a++){let[d,C,E]=e.edges[a],g=Math.min(1,s[a]/c*l);if(n()<g){let w=E/g;f.push([d,C,w])}}return{nodeCount:e.nodeCount,edges:f}}validateSpectral(e,n){let t=Math.min(y,Math.max(1,e.nodeCount-1)),i=this.computeLaplacian(e),r=this.computeLaplacian(n),o=this.computeTopEigenvalues(i,t),m=this.computeTopEigenvalues(r,t),l=[],s=!0,c=this.epsilon;for(let f=0;f<o.length;f++){if(o[f]<1e-10)continue;let a=m[f]/o[f];l.push(a),(a<1-c||a>1+c)&&(s=!1)}return{isValid:s,eigenvalueRatios:l,originalEdgeCount:e.edges.length,sparsifiedEdgeCount:n.edges.length,compressionRatio:e.edges.length>0?n.edges.length/e.edges.length:0}}computeLaplacian(e){let n=e.nodeCount,t=Array.from({length:n},()=>new Array(n).fill(0));for(let[i,r,o]of e.edges)i<0||i>=n||r<0||r>=n||(t[i][i]+=o,t[r][r]+=o,t[i][r]-=o,t[r][i]-=o);return t}computeTopEigenvalues(e,n){let t=e.length;if(t===0)return[];let i=[],r=[],o=e.map(m=>[...m]);for(let m=0;m<Math.min(n,t);m++){let l=this.powerIteration(o,t,r);if(l===null)break;i.push(l.eigenvalue),r.push(l.eigenvector),V(o,l.eigenvalue,l.eigenvector)}return i}approximateEffectiveResistances(e){let n=e.nodeCount,t=new Float64Array(n);for(let[r,o,m]of e.edges)r>=0&&r<n&&(t[r]+=m),o>=0&&o<n&&(t[o]+=m);let i=new Array(e.edges.length);for(let r=0;r<e.edges.length;r++){let[o,m]=e.edges[r],l=t[o]||1,s=t[m]||1;i[r]=1/l+1/s}return i}powerIteration(e,n,t){let i=0;for(let s=0;s<n;s++)for(let c=0;c<n;c++)i+=e[s][c]*e[s][c];if(i<p*p)return null;let r=t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]=Math.sin((s+1)*(r+1)*1.618033988749895)+.1*(s-n/2);for(let s of t)h(o,s);if(R(o)<p)return null;let l=0;for(let s=0;s<x;s++){let c=L(e,o);for(let d of t)h(c,d);let f=S(c,o),a=v(c);if(a<p)return{eigenvalue:0,eigenvector:o};for(let d=0;d<n;d++)o[d]=c[d]/a;if(Math.abs(f-l)<p){l=f;break}l=f}return{eigenvalue:Math.abs(l),eigenvector:o}}};function L(u,e){let n=u.length,t=new Array(n).fill(0);for(let i=0;i<n;i++){let r=0;for(let o=0;o<n;o++)r+=u[i][o]*e[o];t[i]=r}return t}function v(u){let e=0;for(let n=0;n<u.length;n++)e+=u[n]*u[n];return Math.sqrt(e)}function R(u){let e=v(u);if(e>0)for(let n=0;n<u.length;n++)u[n]/=e;return e}function S(u,e){let n=0;for(let t=0;t<u.length;t++)n+=u[t]*e[t];return n}function h(u,e){let n=S(u,e);for(let t=0;t<u.length;t++)u[t]-=n*e[t]}function V(u,e,n){let t=n.length;for(let i=0;i<t;i++)for(let r=0;r<t;r++)u[i][r]-=e*n[i]*n[r]}export{b as a};
@@ -1,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.9.1");process.exit(0)}
2
- import{a as W}from"./chunk-YUQIXT3G.js";import{c as V,d as q}from"./chunk-V4HM4QAO.js";import{c as M}from"./chunk-FRNB4CH2.js";import{a as $}from"./chunk-U5JQGRHZ.js";import{c as N}from"./chunk-A57BEPL7.js";import{b as D,d as H}from"./chunk-JSOBRKMA.js";import{a as E,c as k}from"./chunk-UN4PA4M2.js";import{f as y}from"./chunk-UB7RGVKO.js";import{a as R,b as U,d as J}from"./chunk-XUFHYPZK.js";var P={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};H();k();var A=class{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=M(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.prepareStatements(),this.initialized=!0,this.config.debug){let e=await this.getStats();console.log(`[ConceptGraph] Initialized: ${this.persistence.getDbPath()}`,e)}}catch(e){throw new Error(`Failed to initialize ConceptGraph: ${E(e)}`)}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertNode",this.db.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
+ import{a as W}from"./chunk-J7QGH6PG.js";import{c as V,d as q}from"./chunk-UVWKIP3U.js";import{c as M}from"./chunk-66RCUQCI.js";import{a as $}from"./chunk-FONTSK2O.js";import{c as N}from"./chunk-6N26CWST.js";import{b as D,d as H}from"./chunk-CU36MONI.js";import{a as E,c as k}from"./chunk-OXR2FPHK.js";import{f as y}from"./chunk-EVIXQR4O.js";import{a as R,b as U,d as J}from"./chunk-WSVWVIVR.js";var P={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};H();k();var A=class{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=M(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.prepareStatements(),this.initialized=!0,this.config.debug){let e=await this.getStats();console.log(`[ConceptGraph] Initialized: ${this.persistence.getDbPath()}`,e)}}catch(e){throw new Error(`Failed to initialize ConceptGraph: ${E(e)}`)}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertNode",this.db.prepare(`
3
3
  INSERT INTO concept_nodes
4
4
  (id, concept_type, content, embedding, activation_level, last_activated, pattern_id, metadata)
5
5
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
@@ -59,7 +59,7 @@ import{a as W}from"./chunk-YUQIXT3G.js";import{c as V,d as q}from"./chunk-V4HM4Q
59
59
  ORDER BY weight DESC
60
60
  LIMIT -1 OFFSET ?
61
61
  )
62
- `).run(s,e);a+=c.changes}return a})(),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,a=t.get().count,r={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)r[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:a,byType:r,avgEdgesPerNode:i>0?a/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?D(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function K(h){return new A(h)}J();function Z(h,e){if(e<0||e>=h.length)return h[0]??0;let t=0,n=h.length-1;for(;t<n;){let i=t+n>>1;if(h[i]<h[t]){let s=h[t];h[t]=h[i],h[i]=s}if(h[n]<h[t]){let s=h[t];h[t]=h[n],h[n]=s}if(h[i]<h[n]){let s=h[i];h[i]=h[n],h[n]=s}let a=h[n],r=t;for(let s=t;s<n;s++)if(h[s]<=a){let c=h[r];h[r]=h[s],h[s]=c,r++}let o=h[r];if(h[r]=h[n],h[n]=o,r===e)return h[r];r<e?t=r+1:n=r-1}return h[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},S=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...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 a=0,r=t,o=0,s=0;for(;a<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),l=this.graph.getActiveNodes(this.config.threshold);for(let u of l)u.activationLevel>r&&(r=u.activationLevel);if(l.length===o&&d===0){if(s++,s>=3)break}else s=0;o=l.length,a++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,l)=>l.activation-d.activation),p=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:a,nodesActivated:c.length,peakActivation:r,activatedNodes:c,novelAssociations:p.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,a=0,r=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),l=o[d];if(l){let u=this.config.noiseLevel+R()*this.config.noiseLevel*2,m=l.activationLevel,v=Math.min(1,m+u+.3);this.graph.setActivation(l.id,v);let f=await this.spread([l.id],v,s);i+=f.iterations,f.peakActivation>a&&(a=f.peakActivation);for(let b of f.activatedNodes)r.add(b.nodeId);for(let b of f.novelAssociations)n.push(b)}if(Date.now()>=s)break;await this.sleep(50+R()*50)}let c=this.deduplicateAssociations(n),p=Array.from(r).map(d=>{let l=this.graph.getConcept(d);return{nodeId:d,activation:l?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,l)=>l.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:p.length,peakActivation:a,activatedNodes:p,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((r,o)=>o.activationLevel-r.activationLevel).slice(0,i));let a=[];for(let r=0;r<n.length;r++)for(let o=r+1;o<n.length;o++){let s=n[r],c=n[o],p=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),l=this.graph.getEdge(c.id,s.id),u=d!==void 0||l!==void 0,m=d?.weight??l?.weight??0,v=!u||m<.3;p>.3&&(a.push({source:s,target:c,coActivation:p,isNovel:v}),this.trackCoActivation(s.id,c.id))}return a.sort((r,o)=>r.isNovel!==o.isNovel?r.isNovel?-1:1:o.coActivation-r.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=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=Z(n,t-1),a=[];for(let[r,o]of this.coActivationCounts){if(a.length>=t)break;o<=i&&a.push(r)}for(let r of a)this.coActivationCounts.delete(r)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let a=this.graph.getEdges(i.id);for(let r of a){let o=this.graph.getConcept(r.target);if(!o)continue;let s=i.activationLevel*r.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,p=Math.min(1,c+s);n.push({nodeId:r.target,newActivation:p})}}}for(let i of n){let a=this.graph.getConcept(i.nodeId);a&&i.newActivation>a.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(R()-.5)*2*this.config.noiseLevel,i=Math.max(0,Math.min(1,t.activationLevel+n));this.graph.setActivation(t.id,i)}}recordActivation(e,t){let n=this.activationHistory.get(e)||[];n.push(t),n.length>50&&n.shift(),this.activationHistory.set(e,n)}trackCoActivation(e,t){let n=[e,t].sort().join(":"),i=this.coActivationCounts.get(n)||0;this.coActivationCounts.set(n,i+1)}deduplicateAssociations(e){let t=new Map;for(let n of e){let i=[n.source,n.target].sort().join(":"),a=t.get(i);(!a||n.strength>a.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 ee}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},I=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let a=await this.detectPatternMerges(i);for(let c of a)c.cycleId=e,n.push(c);let r=await this.detectNovelAssociations(t.novelAssociations);for(let c of r)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let 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,p)=>p.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let a=i+1;a<n.length;a++){let r=n[i],o=n[a],s=this.graph.getEdge(r.id,o.id),c=this.graph.getEdge(o.id,r.id),p=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(r.content,o.content),l=Math.sqrt(r.activationLevel*o.activationLevel),u=p*.4+d*.3+l*.3;if(u>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[r.id,o.id]}),v=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[r.id,o.id],edgeWeight:p,contentSimilarity:d,coActivation:l});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[r.id,o.id],description:this.generatePatternMergeDescription(r,o,u),noveltyScore:m,confidenceScore:v,actionable:v>=this.config.minConfidence,applied:!1,suggestedAction:v>=this.config.minConfidence?`Merge "${this.truncate(r.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),a=this.graph.getConcept(n.target);if(!i||!a)continue;let r=this.graph.getEdge(n.source,n.target);if(r&&r.weight>.5)continue;let o=i.conceptType!==a.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,a,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(a.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??{},a=i.successRate,r=i.executionCount,o=i.confidence,s=a!==void 0&&a<.7,c=r!==void 0&&r>10,p=o!==void 0&&o<.6;if(s||c&&p){let d=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),l=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,a,r),noveltyScore:d,confidenceScore:l,actionable:l>=this.config.minConfidence,applied:!1,suggestedAction:l>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let a=i.conceptType??"pattern";n[a]||(n[a]=[]),n[a].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(a=>a.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ee().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),a=new Set(n),r=new Set(i),o=n.filter(c=>r.has(c)),s=a.size+r.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 a=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 ${a}% 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();k();$();import{existsSync as te,unlinkSync as ne}from"fs";var T={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},C=class{constructor(e,t=T){this.db=e;this.thresholds=t}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-2NOVE7DL.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 a=`/tmp/dream-branch-${t}.rvf`,r=this.rvfAdapter.derive(a),o=i;o._rvfBranchPath=a,o._rvfChildAdapter=r}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),a=i.patternCount-n.patternCount,r=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-a/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(r<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-r).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,l=new Float32Array(d);for(let m=0;m<d;m++)l[m]=Math.sin(m*.1);let u=this.rvfAdapter.search?.(l,10)??[];u.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${u.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let p=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:p,patternCountDelta:a,avgConfidenceDelta:r,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&te(n)&&ne(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var x=N.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...T}},z=class{constructor(e){this.graph=e}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 a=(await this.graph.getNeighbors(n.id)).map(r=>r.edge);this.edgeCache.set(n.id,a)}}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 r of e)t[r.conceptType]=(t[r.conceptType]??0)+1,n+=this.activationLevels.get(r.id)??r.activationLevel;let i=0,a=Array.from(this.edgeCache.values());for(let r of a)i+=r.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},_=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=M(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.migrateSchema(),this.graph=new A,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new C(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${E(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),a=new Set(i.map(s=>s.name)),r=a.has("insight_type"),o=a.has("source_concepts");if(!r)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),x.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),x.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){x.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:y(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let a=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(a),this.emitBranchEvent("dream:branch_created",i)}try{let a=await this.graph.getActiveNodes(0);if(a.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${a.length} < ${this.config.minConceptsRequired}`);let r=new z(this.graph);await r.loadIntoMemory(30);let s=await new S(r,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 r.persistActivations();let p=await new I(r,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=p.length;for(let l of p)await this.saveInsight(l);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let l=this.branchManager.validateBranch(i);if(l.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,l);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,l);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:l.reason},"dream-engine")}catch{}x.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:l.reason})}i=null}let d={cycle:{...this.currentCycle},insights:p,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(a){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=E(a),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,a}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async ensureConceptsLoaded(){if(this.ensureInitialized(),(await this.graph.getActiveNodes(0)).length>=this.config.minConceptsRequired)return 0;let t=this.db.prepare(`SELECT id, name, description, qe_domain as domain, pattern_type as patternType,
62
+ `).run(s,e);a+=c.changes}return a})(),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,a=t.get().count,r={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)r[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:a,byType:r,avgEdgesPerNode:i>0?a/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?D(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function K(h){return new A(h)}J();function Z(h,e){if(e<0||e>=h.length)return h[0]??0;let t=0,n=h.length-1;for(;t<n;){let i=t+n>>1;if(h[i]<h[t]){let s=h[t];h[t]=h[i],h[i]=s}if(h[n]<h[t]){let s=h[t];h[t]=h[n],h[n]=s}if(h[i]<h[n]){let s=h[i];h[i]=h[n],h[n]=s}let a=h[n],r=t;for(let s=t;s<n;s++)if(h[s]<=a){let c=h[r];h[r]=h[s],h[s]=c,r++}let o=h[r];if(h[r]=h[n],h[n]=o,r===e)return h[r];r<e?t=r+1:n=r-1}return h[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},S=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...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 a=0,r=t,o=0,s=0;for(;a<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),l=this.graph.getActiveNodes(this.config.threshold);for(let u of l)u.activationLevel>r&&(r=u.activationLevel);if(l.length===o&&d===0){if(s++,s>=3)break}else s=0;o=l.length,a++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,l)=>l.activation-d.activation),p=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:a,nodesActivated:c.length,peakActivation:r,activatedNodes:c,novelAssociations:p.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,a=0,r=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),l=o[d];if(l){let u=this.config.noiseLevel+R()*this.config.noiseLevel*2,m=l.activationLevel,v=Math.min(1,m+u+.3);this.graph.setActivation(l.id,v);let f=await this.spread([l.id],v,s);i+=f.iterations,f.peakActivation>a&&(a=f.peakActivation);for(let b of f.activatedNodes)r.add(b.nodeId);for(let b of f.novelAssociations)n.push(b)}if(Date.now()>=s)break;await this.sleep(50+R()*50)}let c=this.deduplicateAssociations(n),p=Array.from(r).map(d=>{let l=this.graph.getConcept(d);return{nodeId:d,activation:l?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,l)=>l.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:p.length,peakActivation:a,activatedNodes:p,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((r,o)=>o.activationLevel-r.activationLevel).slice(0,i));let a=[];for(let r=0;r<n.length;r++)for(let o=r+1;o<n.length;o++){let s=n[r],c=n[o],p=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),l=this.graph.getEdge(c.id,s.id),u=d!==void 0||l!==void 0,m=d?.weight??l?.weight??0,v=!u||m<.3;p>.3&&(a.push({source:s,target:c,coActivation:p,isNovel:v}),this.trackCoActivation(s.id,c.id))}return a.sort((r,o)=>r.isNovel!==o.isNovel?r.isNovel?-1:1:o.coActivation-r.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=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=Z(n,t-1),a=[];for(let[r,o]of this.coActivationCounts){if(a.length>=t)break;o<=i&&a.push(r)}for(let r of a)this.coActivationCounts.delete(r)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let a=this.graph.getEdges(i.id);for(let r of a){let o=this.graph.getConcept(r.target);if(!o)continue;let s=i.activationLevel*r.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,p=Math.min(1,c+s);n.push({nodeId:r.target,newActivation:p})}}}for(let i of n){let a=this.graph.getConcept(i.nodeId);a&&i.newActivation>a.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(R()-.5)*2*this.config.noiseLevel,i=Math.max(0,Math.min(1,t.activationLevel+n));this.graph.setActivation(t.id,i)}}recordActivation(e,t){let n=this.activationHistory.get(e)||[];n.push(t),n.length>50&&n.shift(),this.activationHistory.set(e,n)}trackCoActivation(e,t){let n=[e,t].sort().join(":"),i=this.coActivationCounts.get(n)||0;this.coActivationCounts.set(n,i+1)}deduplicateAssociations(e){let t=new Map;for(let n of e){let i=[n.source,n.target].sort().join(":"),a=t.get(i);(!a||n.strength>a.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 ee}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},I=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let a=await this.detectPatternMerges(i);for(let c of a)c.cycleId=e,n.push(c);let r=await this.detectNovelAssociations(t.novelAssociations);for(let c of r)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let 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,p)=>p.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let a=i+1;a<n.length;a++){let r=n[i],o=n[a],s=this.graph.getEdge(r.id,o.id),c=this.graph.getEdge(o.id,r.id),p=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(r.content,o.content),l=Math.sqrt(r.activationLevel*o.activationLevel),u=p*.4+d*.3+l*.3;if(u>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[r.id,o.id]}),v=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[r.id,o.id],edgeWeight:p,contentSimilarity:d,coActivation:l});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[r.id,o.id],description:this.generatePatternMergeDescription(r,o,u),noveltyScore:m,confidenceScore:v,actionable:v>=this.config.minConfidence,applied:!1,suggestedAction:v>=this.config.minConfidence?`Merge "${this.truncate(r.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),a=this.graph.getConcept(n.target);if(!i||!a)continue;let r=this.graph.getEdge(n.source,n.target);if(r&&r.weight>.5)continue;let o=i.conceptType!==a.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,a,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(a.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??{},a=i.successRate,r=i.executionCount,o=i.confidence,s=a!==void 0&&a<.7,c=r!==void 0&&r>10,p=o!==void 0&&o<.6;if(s||c&&p){let d=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),l=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,a,r),noveltyScore:d,confidenceScore:l,actionable:l>=this.config.minConfidence,applied:!1,suggestedAction:l>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let a=i.conceptType??"pattern";n[a]||(n[a]=[]),n[a].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(a=>a.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ee().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),a=new Set(n),r=new Set(i),o=n.filter(c=>r.has(c)),s=a.size+r.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 a=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 ${a}% 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();k();$();import{existsSync as te,unlinkSync as ne}from"fs";var T={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},C=class{constructor(e,t=T){this.db=e;this.thresholds=t}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-GIGWUPEX.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 a=`/tmp/dream-branch-${t}.rvf`,r=this.rvfAdapter.derive(a),o=i;o._rvfBranchPath=a,o._rvfChildAdapter=r}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),a=i.patternCount-n.patternCount,r=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-a/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(r<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-r).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,l=new Float32Array(d);for(let m=0;m<d;m++)l[m]=Math.sin(m*.1);let u=this.rvfAdapter.search?.(l,10)??[];u.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${u.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let p=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:p,patternCountDelta:a,avgConfidenceDelta:r,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&te(n)&&ne(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var x=N.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...T}},z=class{constructor(e){this.graph=e}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 a=(await this.graph.getNeighbors(n.id)).map(r=>r.edge);this.edgeCache.set(n.id,a)}}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 r of e)t[r.conceptType]=(t[r.conceptType]??0)+1,n+=this.activationLevels.get(r.id)??r.activationLevel;let i=0,a=Array.from(this.edgeCache.values());for(let r of a)i+=r.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},_=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=M(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.migrateSchema(),this.graph=new A,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new C(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${E(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),a=new Set(i.map(s=>s.name)),r=a.has("insight_type"),o=a.has("source_concepts");if(!r)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),x.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),x.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){x.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:y(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let a=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(a),this.emitBranchEvent("dream:branch_created",i)}try{let a=await this.graph.getActiveNodes(0);if(a.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${a.length} < ${this.config.minConceptsRequired}`);let r=new z(this.graph);await r.loadIntoMemory(30);let s=await new S(r,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 r.persistActivations();let p=await new I(r,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=p.length;for(let l of p)await this.saveInsight(l);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let l=this.branchManager.validateBranch(i);if(l.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,l);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,l);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:l.reason},"dream-engine")}catch{}x.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:l.reason})}i=null}let d={cycle:{...this.currentCycle},insights:p,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(a){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=E(a),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,a}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async ensureConceptsLoaded(){if(this.ensureInitialized(),(await this.graph.getActiveNodes(0)).length>=this.config.minConceptsRequired)return 0;let t=this.db.prepare(`SELECT id, name, description, qe_domain as domain, pattern_type as patternType,
63
63
  confidence, success_rate as successRate
64
64
  FROM qe_patterns
65
65
  WHERE confidence >= 0.3
@@ -92,4 +92,4 @@ import{a as W}from"./chunk-YUQIXT3G.js";import{c as V,d as q}from"./chunk-V4HM4Q
92
92
  (id, cycle_id, insight_type, source_concepts, description, novelty_score,
93
93
  confidence_score, actionable, applied, suggested_action, pattern_id)
94
94
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
95
- `).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:D(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function ie(h){let e=new _(h);return import("./feature-flags-2NOVE7DL.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-EXACQ2PT.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var re=_;$();var g=N.create("DreamScheduler"),Y={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},L=class h{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={...Y,...t},this.metaLearningEngine=new q}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,g.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),g.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),g.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,g.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(g.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{g.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,g.info("Starting dream cycle",{durationMs:e});try{let t=await this.dreamEngine.ensureConceptsLoaded();t>0&&g.info("Auto-loaded concepts for dream",{loaded:t});let n=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=n,this.totalDreamsCompleted++,this.clearExperienceBuffer(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(n),await this.publishDreamCompletedEvent(n),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(i){g.warn("Post-dream meta-learning failed (non-critical)",{error:i instanceof Error?i.message:String(i)})}return this.running&&this.scheduleNextDream(),g.info("Dream completed",{insightsGenerated:n.insights.length}),n}finally{this.dreaming=!1}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&g.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){g.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async 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>h.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){g.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)g.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>h.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:y(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{g.debug("Failed to publish meta-learning insight event")}}}else g.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),g.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){g.info("Quality gate failed but cannot start dream yet");return}g.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){g.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){g.info("Milestone reached but cannot start dream yet");return}g.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:y(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){g.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){g.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],g.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){g.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function ae(h,e){return new L(h,e)}var se=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],G=class{constructor(e,t){this.db=e;this.branchManager=new C(e,t??T)}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(),a=[];for(let s of e){let c=await this.executeStrategy(s,i,t);a.push(c)}let r=a.filter(s=>s.validation.passed),o=null;if(r.length>0){o=r.reduce((c,p)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(p.validation)>d?p: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:a,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,a=this.branchManager.createBranch(i),r=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(a,t);return this.branchManager.discardBranch(a),{strategy:e,branch:a,validation:o,selected:!1,durationMs:Date.now()-r}}catch{return this.branchManager.discardBranch(a),{strategy:e,branch:a,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-r}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{P as a,A as b,K as c,B as d,O as e,F as f,j as g,S as h,Q as i,I as j,T as k,C as l,X as m,_ as n,ie as o,re as p,Y as q,L as r,ae as s,se as t,G as u};
95
+ `).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:D(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function ie(h){let e=new _(h);return import("./feature-flags-GIGWUPEX.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-UQQUEC52.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var re=_;$();var g=N.create("DreamScheduler"),Y={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},L=class h{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={...Y,...t},this.metaLearningEngine=new q}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,g.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),g.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),g.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,g.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(g.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{g.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,g.info("Starting dream cycle",{durationMs:e});try{let t=await this.dreamEngine.ensureConceptsLoaded();t>0&&g.info("Auto-loaded concepts for dream",{loaded:t});let n=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=n,this.totalDreamsCompleted++,this.clearExperienceBuffer(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(n),await this.publishDreamCompletedEvent(n),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(i){g.warn("Post-dream meta-learning failed (non-critical)",{error:i instanceof Error?i.message:String(i)})}return this.running&&this.scheduleNextDream(),g.info("Dream completed",{insightsGenerated:n.insights.length}),n}finally{this.dreaming=!1}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&g.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){g.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async 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>h.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){g.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)g.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>h.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:y(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{g.debug("Failed to publish meta-learning insight event")}}}else g.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),g.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){g.info("Quality gate failed but cannot start dream yet");return}g.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){g.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){g.info("Milestone reached but cannot start dream yet");return}g.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:y(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){g.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){g.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],g.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){g.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function ae(h,e){return new L(h,e)}var se=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],G=class{constructor(e,t){this.db=e;this.branchManager=new C(e,t??T)}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(),a=[];for(let s of e){let c=await this.executeStrategy(s,i,t);a.push(c)}let r=a.filter(s=>s.validation.passed),o=null;if(r.length>0){o=r.reduce((c,p)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(p.validation)>d?p: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:a,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,a=this.branchManager.createBranch(i),r=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(a,t);return this.branchManager.discardBranch(a),{strategy:e,branch:a,validation:o,selected:!1,durationMs:Date.now()-r}}catch{return this.branchManager.discardBranch(a),{strategy:e,branch:a,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-r}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{P as a,A as b,K as c,B as d,O as e,F as f,j as g,S as h,Q as i,I as j,T as k,C as l,X as m,_ as n,ie as o,re as p,Y as q,L as r,ae as s,se as t,G as u};
@@ -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.9.1");process.exit(0)}
2
- import{a as n}from"./chunk-43M6Y6VF.js";import{a as o}from"./chunk-QMFP5OKH.js";import{a,e as c}from"./chunk-SGRN6JFB.js";c();var M=a.CLEANUP_INTERVAL_MS,y=".agentic-qe/memory.db";async function d(r,t=!0){let e;switch(r.type){case"memory":e=new o;break;case"sqlite":e=new n({sqlite:r.sqlite,enableFallback:!0});break;case"agentdb":e=new n({sqlite:{path:r.agentdb?.path??y},enableFallback:!0});break;case"hybrid":e=new n(r.hybrid);break;default:throw new Error(`Unknown memory backend type: ${r.type}`)}return t&&await e.initialize(),{backend:e,type:r.type,initialized:t}}async function u(r=!0){let t=process.env.AQE_MEMORY_BACKEND??"memory",e=process.env.AQE_MEMORY_PATH??".agentic-qe",i={type:t,sqlite:{path:`${e}/memory.db`,walMode:!0},agentdb:{path:`${e}/memory.db`},hybrid:{enableFallback:!0,sqlite:{path:`${e}/memory.db`}}};return d(i,r)}export{d as a,u as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
+ import{a as n}from"./chunk-MNZ2HHKI.js";import{a as o}from"./chunk-HVOOYPW6.js";import{a,e as c}from"./chunk-TPFE3BAI.js";c();var M=a.CLEANUP_INTERVAL_MS,y=".agentic-qe/memory.db";async function d(r,t=!0){let e;switch(r.type){case"memory":e=new o;break;case"sqlite":e=new n({sqlite:r.sqlite,enableFallback:!0});break;case"agentdb":e=new n({sqlite:{path:r.agentdb?.path??y},enableFallback:!0});break;case"hybrid":e=new n(r.hybrid);break;default:throw new Error(`Unknown memory backend type: ${r.type}`)}return t&&await e.initialize(),{backend:e,type:r.type,initialized:t}}async function u(r=!0){let t=process.env.AQE_MEMORY_BACKEND??"memory",e=process.env.AQE_MEMORY_PATH??".agentic-qe",i={type:t,sqlite:{path:`${e}/memory.db`,walMode:!0},agentdb:{path:`${e}/memory.db`},hybrid:{enableFallback:!0,sqlite:{path:`${e}/memory.db`}}};return d(i,r)}export{d as a,u as b};
@@ -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.9.1");process.exit(0)}
2
- import{a as N,d as P}from"./chunk-XUFHYPZK.js";import{b,e as k}from"./chunk-SGRN6JFB.js";import{a as p,d as F}from"./chunk-NG3BKE7V.js";import{a as T,c as E}from"./chunk-4XREPCBZ.js";import{a as H,b as O}from"./chunk-35H73OPP.js";import{c as z,g as S}from"./chunk-UZZCWWIG.js";function x(l){let e=0;for(let t=0;t<l.length;t++)e+=l[t]*l[t];return Math.sqrt(e)}function C(l,e,t,s){let n=t*s;if(n===0)return 0;let o=0;for(let r=0;r<l.length;r++)o+=l[r]*e[r];return o/n}function U(l={}){let{name:e="default",...t}=l;return new M(e,t)}var f,w,v,I,A,M,D=z(()=>{F();P();k();E();f=null,w=null;try{let l=(O(),S(H));f=l.differentiableSearch,w=l.init}catch{}v=class{data=[];compareFn;constructor(e){this.compareFn=e}push(e){this.data.push(e),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;let e=this.data[0],t=this.data.pop();return this.data.length>0&&(this.data[0]=t,this.sinkDown(0)),e}peek(){return this.data[0]}size(){return this.data.length}bubbleUp(e){for(;e>0;){let t=e-1>>1;if(this.compareFn(this.data[e],this.data[t])<0)[this.data[e],this.data[t]]=[this.data[t],this.data[e]],e=t;else break}}sinkDown(e){let t=this.data.length;for(;;){let s=e,n=2*e+1,o=2*e+2;if(n<t&&this.compareFn(this.data[n],this.data[s])<0&&(s=n),o<t&&this.compareFn(this.data[o],this.data[s])<0&&(s=o),s!==e)[this.data[e],this.data[s]]=[this.data[s],this.data[e]],e=s;else break}}},I=class{nodes=new Map;M=b.M_CONNECTIONS;Mmax0=b.M_CONNECTIONS*2;efConstruction=b.EF_CONSTRUCTION;efSearch=b.EF_SEARCH;mL=1/Math.log(b.M_CONNECTIONS);maxLevel=16;entryPoint=null;currentMaxLevel=-1;randomLevel(){return Math.min(Math.floor(-Math.log(N())*this.mL),this.maxLevel)}similarity(e,t){let s=this.nodes.get(t);return s?p(e,s.embedding):-1}searchLayer(e,t,s){let n=t,o=this.similarity(e,n),r=!0;for(;r;){r=!1;let a=this.nodes.get(n);if(!a)break;let h=a.neighbors.get(s)??[];for(let d of h){if(!this.nodes.has(d))continue;let i=this.similarity(e,d);i>o&&(n=d,o=i,r=!0)}}return n}searchLayerBeam(e,t,s,n){let o=new Set(t),r=t.filter(i=>this.nodes.has(i)).map(i=>({id:i,score:this.similarity(e,i)})),a=new v((i,c)=>c.score-i.score),h=new v((i,c)=>i.score-c.score);for(let i of r)a.push(i),h.push(i);for(;a.size()>0;){let i=a.pop();if(h.size()>=n&&i.score<h.peek().score)break;let c=this.nodes.get(i.id);if(!c)continue;let u=c.neighbors.get(s)??[];for(let m of u){if(o.has(m)||(o.add(m),!this.nodes.has(m)))continue;let g=this.similarity(e,m),y=h.size()>=n?h.peek().score:-1/0;if(h.size()<n||g>y){let L={id:m,score:g};a.push(L),h.push(L),h.size()>n&&h.pop()}}}let d=[];for(;h.size()>0;)d.push(h.pop());return d.reverse(),d}selectNeighbors(e,t,s){return t.sort((n,o)=>o.score-n.score).slice(0,s).map(n=>n.id)}getMaxConnections(e){return e===0?this.Mmax0:this.M}add(e,t){this.nodes.has(e)&&this.remove(e);let s=this.randomLevel(),n={id:e,embedding:t,neighbors:new Map};for(let r=0;r<=s;r++)n.neighbors.set(r,[]);if(this.nodes.set(e,n),this.entryPoint===null){this.entryPoint=e,this.currentMaxLevel=s;return}let o=this.entryPoint;for(let r=this.currentMaxLevel;r>s;r--)o=this.searchLayer(t,o,r);for(let r=Math.min(s,this.currentMaxLevel);r>=0;r--){let a=this.getMaxConnections(r),h=this.searchLayerBeam(t,[o],r,this.efConstruction),d=this.selectNeighbors(t,h,a);n.neighbors.set(r,[...d]);for(let i of d){let c=this.nodes.get(i);if(!c)continue;let u=c.neighbors.get(r)??[];if(u.push(e),u.length>a){let m=u.filter(g=>this.nodes.has(g)).map(g=>({id:g,score:p(c.embedding,this.nodes.get(g).embedding)}));m.sort((g,y)=>y.score-g.score),c.neighbors.set(r,m.slice(0,a).map(g=>g.id))}else c.neighbors.set(r,u)}h.length>0&&(o=h[0].id)}s>this.currentMaxLevel&&(this.entryPoint=e,this.currentMaxLevel=s)}remove(e){let t=this.nodes.get(e);if(!t)return!1;for(let[s,n]of t.neighbors.entries())for(let o of n){let r=this.nodes.get(o);if(!r)continue;let a=r.neighbors.get(s);if(!a)continue;let h=a.indexOf(e);h!==-1&&a.splice(h,1);let d=this.getMaxConnections(s);if(a.length<d){for(let i of n)if(i!==o&&i!==e&&this.nodes.has(i)&&!a.includes(i)){a.push(i);let c=this.nodes.get(i);if(c){let u=c.neighbors.get(s)??[];!u.includes(o)&&u.length<d&&(u.push(o),c.neighbors.set(s,u))}if(a.length>=d)break}}r.neighbors.set(s,a)}if(this.nodes.delete(e),this.entryPoint===e)if(this.nodes.size===0)this.entryPoint=null,this.currentMaxLevel=-1;else{let s=null,n=-1;for(let[o,r]of this.nodes.entries()){let a=-1;for(let h of r.neighbors.keys())h>a&&(a=h);a>n&&(n=a,s=o)}this.entryPoint=s,this.currentMaxLevel=n}return!0}search(e,t){if(this.nodes.size===0||this.entryPoint===null)return[];if(this.nodes.size===1){let r=this.nodes.get(this.entryPoint);return[{id:r.id,score:p(e,r.embedding)}]}let s=this.entryPoint;for(let r=this.currentMaxLevel;r>0;r--)s=this.searchLayer(e,s,r);let n=Math.max(this.efSearch,t);return this.searchLayerBeam(e,[s],0,n).slice(0,t)}size(){return this.nodes.size}clear(){this.nodes.clear(),this.entryPoint=null,this.currentMaxLevel=-1}};A=class{ids=[];vectors=[];norms=[];idToIndex=new Map;initialized=!1;constructor(){if(w&&!this.initialized)try{w(),this.initialized=!0}catch{this.initialized=f!==null}}add(e,t){let s=new Float32Array(t),n=x(s);if(this.idToIndex.has(e)){let r=this.idToIndex.get(e);this.vectors[r]=s,this.norms[r]=n;return}let o=this.ids.length;this.ids.push(e),this.vectors.push(s),this.norms.push(n),this.idToIndex.set(e,o)}search(e,t){if(this.ids.length===0)return[];let s=Math.min(t,this.ids.length),n=this.vectors.length>0?this.vectors[0].length:0,o=e.length,r=n===o;if(f&&this.vectors.length>0&&r){let i=new Float32Array(e),c=x(i);return f(i,this.vectors,s,1).indices.map(m=>({id:this.ids[m],score:C(i,this.vectors[m],c,this.norms[m])}))}let a=new Float32Array(e),h=x(a),d=[];for(let i=0;i<this.ids.length;i++){let c=this.vectors[i];if(c.length!==a.length){i===0&&console.warn(`[RuvectorFlatIndex] Dimension mismatch: query=${a.length}, stored=${c.length}. Skipping ${this.ids.length} mismatched vectors. Re-index with correct dimensions.`);continue}else d.push({id:this.ids[i],score:C(a,c,h,this.norms[i])})}return d.sort((i,c)=>c.score-i.score),d.slice(0,s)}remove(e){let t=this.idToIndex.get(e);if(t===void 0)return!1;let s=this.ids.length-1;if(t!==s){let n=this.ids[s];this.ids[t]=n,this.vectors[t]=this.vectors[s],this.norms[t]=this.norms[s],this.idToIndex.set(n,t)}return this.ids.pop(),this.vectors.pop(),this.norms.pop(),this.idToIndex.delete(e),!0}clear(){this.ids=[],this.vectors=[],this.norms=[],this.idToIndex.clear()}size(){return this.ids.length}},M=class{adapter;constructor(e,t){this.adapter=T.create(e,t)}add(e,t){this.adapter.addByStringId(e,t)}search(e,t){return this.adapter.searchByArray(e,t)}remove(e){return this.adapter.removeByStringId(e)}clear(){this.adapter.clear()}size(){return this.adapter.size()}recall(){return this.adapter.recall()}getProvider(){return this.adapter}}});export{v as a,I as b,A as c,M as d,U as e,D as f};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
+ import{a as N,d as P}from"./chunk-WSVWVIVR.js";import{b,e as k}from"./chunk-TPFE3BAI.js";import{a as p,d as F}from"./chunk-OV6H3TRU.js";import{a as T,c as E}from"./chunk-M7PGW5Z5.js";import{a as H,b as O}from"./chunk-UC3RA5LW.js";import{c as z,g as S}from"./chunk-7ASGPJWU.js";function x(l){let e=0;for(let t=0;t<l.length;t++)e+=l[t]*l[t];return Math.sqrt(e)}function C(l,e,t,s){let n=t*s;if(n===0)return 0;let o=0;for(let r=0;r<l.length;r++)o+=l[r]*e[r];return o/n}function U(l={}){let{name:e="default",...t}=l;return new M(e,t)}var f,w,v,I,A,M,D=z(()=>{F();P();k();E();f=null,w=null;try{let l=(O(),S(H));f=l.differentiableSearch,w=l.init}catch{}v=class{data=[];compareFn;constructor(e){this.compareFn=e}push(e){this.data.push(e),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;let e=this.data[0],t=this.data.pop();return this.data.length>0&&(this.data[0]=t,this.sinkDown(0)),e}peek(){return this.data[0]}size(){return this.data.length}bubbleUp(e){for(;e>0;){let t=e-1>>1;if(this.compareFn(this.data[e],this.data[t])<0)[this.data[e],this.data[t]]=[this.data[t],this.data[e]],e=t;else break}}sinkDown(e){let t=this.data.length;for(;;){let s=e,n=2*e+1,o=2*e+2;if(n<t&&this.compareFn(this.data[n],this.data[s])<0&&(s=n),o<t&&this.compareFn(this.data[o],this.data[s])<0&&(s=o),s!==e)[this.data[e],this.data[s]]=[this.data[s],this.data[e]],e=s;else break}}},I=class{nodes=new Map;M=b.M_CONNECTIONS;Mmax0=b.M_CONNECTIONS*2;efConstruction=b.EF_CONSTRUCTION;efSearch=b.EF_SEARCH;mL=1/Math.log(b.M_CONNECTIONS);maxLevel=16;entryPoint=null;currentMaxLevel=-1;randomLevel(){return Math.min(Math.floor(-Math.log(N())*this.mL),this.maxLevel)}similarity(e,t){let s=this.nodes.get(t);return s?p(e,s.embedding):-1}searchLayer(e,t,s){let n=t,o=this.similarity(e,n),r=!0;for(;r;){r=!1;let a=this.nodes.get(n);if(!a)break;let h=a.neighbors.get(s)??[];for(let d of h){if(!this.nodes.has(d))continue;let i=this.similarity(e,d);i>o&&(n=d,o=i,r=!0)}}return n}searchLayerBeam(e,t,s,n){let o=new Set(t),r=t.filter(i=>this.nodes.has(i)).map(i=>({id:i,score:this.similarity(e,i)})),a=new v((i,c)=>c.score-i.score),h=new v((i,c)=>i.score-c.score);for(let i of r)a.push(i),h.push(i);for(;a.size()>0;){let i=a.pop();if(h.size()>=n&&i.score<h.peek().score)break;let c=this.nodes.get(i.id);if(!c)continue;let u=c.neighbors.get(s)??[];for(let m of u){if(o.has(m)||(o.add(m),!this.nodes.has(m)))continue;let g=this.similarity(e,m),y=h.size()>=n?h.peek().score:-1/0;if(h.size()<n||g>y){let L={id:m,score:g};a.push(L),h.push(L),h.size()>n&&h.pop()}}}let d=[];for(;h.size()>0;)d.push(h.pop());return d.reverse(),d}selectNeighbors(e,t,s){return t.sort((n,o)=>o.score-n.score).slice(0,s).map(n=>n.id)}getMaxConnections(e){return e===0?this.Mmax0:this.M}add(e,t){this.nodes.has(e)&&this.remove(e);let s=this.randomLevel(),n={id:e,embedding:t,neighbors:new Map};for(let r=0;r<=s;r++)n.neighbors.set(r,[]);if(this.nodes.set(e,n),this.entryPoint===null){this.entryPoint=e,this.currentMaxLevel=s;return}let o=this.entryPoint;for(let r=this.currentMaxLevel;r>s;r--)o=this.searchLayer(t,o,r);for(let r=Math.min(s,this.currentMaxLevel);r>=0;r--){let a=this.getMaxConnections(r),h=this.searchLayerBeam(t,[o],r,this.efConstruction),d=this.selectNeighbors(t,h,a);n.neighbors.set(r,[...d]);for(let i of d){let c=this.nodes.get(i);if(!c)continue;let u=c.neighbors.get(r)??[];if(u.push(e),u.length>a){let m=u.filter(g=>this.nodes.has(g)).map(g=>({id:g,score:p(c.embedding,this.nodes.get(g).embedding)}));m.sort((g,y)=>y.score-g.score),c.neighbors.set(r,m.slice(0,a).map(g=>g.id))}else c.neighbors.set(r,u)}h.length>0&&(o=h[0].id)}s>this.currentMaxLevel&&(this.entryPoint=e,this.currentMaxLevel=s)}remove(e){let t=this.nodes.get(e);if(!t)return!1;for(let[s,n]of t.neighbors.entries())for(let o of n){let r=this.nodes.get(o);if(!r)continue;let a=r.neighbors.get(s);if(!a)continue;let h=a.indexOf(e);h!==-1&&a.splice(h,1);let d=this.getMaxConnections(s);if(a.length<d){for(let i of n)if(i!==o&&i!==e&&this.nodes.has(i)&&!a.includes(i)){a.push(i);let c=this.nodes.get(i);if(c){let u=c.neighbors.get(s)??[];!u.includes(o)&&u.length<d&&(u.push(o),c.neighbors.set(s,u))}if(a.length>=d)break}}r.neighbors.set(s,a)}if(this.nodes.delete(e),this.entryPoint===e)if(this.nodes.size===0)this.entryPoint=null,this.currentMaxLevel=-1;else{let s=null,n=-1;for(let[o,r]of this.nodes.entries()){let a=-1;for(let h of r.neighbors.keys())h>a&&(a=h);a>n&&(n=a,s=o)}this.entryPoint=s,this.currentMaxLevel=n}return!0}search(e,t){if(this.nodes.size===0||this.entryPoint===null)return[];if(this.nodes.size===1){let r=this.nodes.get(this.entryPoint);return[{id:r.id,score:p(e,r.embedding)}]}let s=this.entryPoint;for(let r=this.currentMaxLevel;r>0;r--)s=this.searchLayer(e,s,r);let n=Math.max(this.efSearch,t);return this.searchLayerBeam(e,[s],0,n).slice(0,t)}size(){return this.nodes.size}clear(){this.nodes.clear(),this.entryPoint=null,this.currentMaxLevel=-1}};A=class{ids=[];vectors=[];norms=[];idToIndex=new Map;initialized=!1;constructor(){if(w&&!this.initialized)try{w(),this.initialized=!0}catch{this.initialized=f!==null}}add(e,t){let s=new Float32Array(t),n=x(s);if(this.idToIndex.has(e)){let r=this.idToIndex.get(e);this.vectors[r]=s,this.norms[r]=n;return}let o=this.ids.length;this.ids.push(e),this.vectors.push(s),this.norms.push(n),this.idToIndex.set(e,o)}search(e,t){if(this.ids.length===0)return[];let s=Math.min(t,this.ids.length),n=this.vectors.length>0?this.vectors[0].length:0,o=e.length,r=n===o;if(f&&this.vectors.length>0&&r){let i=new Float32Array(e),c=x(i);return f(i,this.vectors,s,1).indices.map(m=>({id:this.ids[m],score:C(i,this.vectors[m],c,this.norms[m])}))}let a=new Float32Array(e),h=x(a),d=[];for(let i=0;i<this.ids.length;i++){let c=this.vectors[i];if(c.length!==a.length){i===0&&console.warn(`[RuvectorFlatIndex] Dimension mismatch: query=${a.length}, stored=${c.length}. Skipping ${this.ids.length} mismatched vectors. Re-index with correct dimensions.`);continue}else d.push({id:this.ids[i],score:C(a,c,h,this.norms[i])})}return d.sort((i,c)=>c.score-i.score),d.slice(0,s)}remove(e){let t=this.idToIndex.get(e);if(t===void 0)return!1;let s=this.ids.length-1;if(t!==s){let n=this.ids[s];this.ids[t]=n,this.vectors[t]=this.vectors[s],this.norms[t]=this.norms[s],this.idToIndex.set(n,t)}return this.ids.pop(),this.vectors.pop(),this.norms.pop(),this.idToIndex.delete(e),!0}clear(){this.ids=[],this.vectors=[],this.norms=[],this.idToIndex.clear()}size(){return this.ids.length}},M=class{adapter;constructor(e,t){this.adapter=T.create(e,t)}add(e,t){this.adapter.addByStringId(e,t)}search(e,t){return this.adapter.searchByArray(e,t)}remove(e){return this.adapter.removeByStringId(e)}clear(){this.adapter.clear()}size(){return this.adapter.size()}recall(){return this.adapter.recall()}getProvider(){return this.adapter}}});export{v as a,I as b,A as c,M as d,U as e,D as f};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
2
- import{f as d}from"./chunk-E33KQBMW.js";import{a as u,c as g}from"./chunk-UN4PA4M2.js";g();var m=[{type:"email",pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,mask:n=>n[0]+"***@"+n.split("@")[1]},{type:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,mask:()=>"***-**-****"},{type:"credit-card",pattern:/\b(?:\d[ -]*?){13,19}\b/g,mask:n=>"****-****-****-"+n.replace(/\D/g,"").slice(-4)},{type:"phone",pattern:/\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b/g,mask:n=>n.slice(0,3)+"***"+n.slice(-2)},{type:"api-key",pattern:/(?:key|token|api_key|apikey|secret|password|passwd|auth)=([A-Za-z0-9_\-]{16,})/gi,mask:()=>"***REDACTED***"}],y=class extends d{config={name:"qe/security/url-validate",description:"Validate URL security: checks for XSS/injection patterns, unsafe protocols, and scans URL query parameters for PII exposure (emails, SSNs, credit cards, API keys).",domain:"security-compliance",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{url:{type:"string",description:"URL to validate for security threats and PII exposure"},enablePII:{type:"boolean",description:"Enable PII exposure scanning in URL and query parameters",default:!0}},required:["url"]}}async execute(s,r){try{let e=this.validateURLSecurity(s.url),t=s.enablePII!==!1?this.scanForPII(s.url):{scanned:!1,found:!1,types:[],details:[]},c=e.issues.length+(t.found?t.types.length:0)===0?`URL passed all checks (security: clean, PII: ${t.scanned?"none found":"not scanned"})`:`URL has ${e.issues.length} security issue(s)${t.found?` and ${t.types.length} PII type(s) exposed in URL`:""}`;return{success:!0,data:{url:s.url,urlSecurity:e,piiExposure:t,summary:c}}}catch(e){return{success:!1,error:u(e)}}}validateURLSecurity(s){let r=[],e="none";try{let t=new URL(s);["http:","https:"].includes(t.protocol)||(r.push({type:"unsafe-protocol",description:`Protocol ${t.protocol} is not allowed`,severity:"high"}),e="high");let o=[/<script/i,/javascript:/i,/on\w+=/i,/data:text\/html/i];for(let i of o)if(i.test(s)){r.push({type:"xss",description:"Potential XSS pattern detected in URL",severity:"critical"}),e="critical";break}let c=[/'.*or.*'/i,/union.*select/i,/drop.*table/i,/;\s*--/i];for(let i of c)if(i.test(s)){r.push({type:"sql-injection",description:"Potential SQL injection pattern detected in URL",severity:"critical"}),e="critical";break}/\.\.[/\\]/.test(s)&&(r.push({type:"path-traversal",description:"Potential path traversal pattern (../) detected",severity:"high"}),e!=="critical"&&(e="high"));let a=["redirect","url","next","return","returnUrl","goto"];for(let i of a){let l=t.searchParams.get(i);l&&/^https?:\/\//.test(l)&&(r.push({type:"open-redirect",description:`Query parameter "${i}" contains an external URL \u2014 potential open redirect`,severity:"medium"}),e==="none"&&(e="medium"))}}catch{r.push({type:"invalid-url",description:"URL could not be parsed",severity:"critical"}),e="critical"}return{valid:r.length===0,riskLevel:e,issues:r}}scanForPII(s){let r=[],e=new Set,t;try{t=decodeURIComponent(s)}catch{t=s}let o="",c="";try{let a=new URL(t);o=a.search,c=a.pathname}catch{o=t}for(let{type:a,pattern:i,mask:l}of m){i.lastIndex=0;let p;for(;(p=i.exec(t))!==null;){e.add(a);let h=o.includes(p[0])?"query-parameter":c.includes(p[0])?"path":"url";r.push({type:a,location:h,masked:l(p[0])})}}return{scanned:!0,found:e.size>0,types:Array.from(e),details:r}}};export{y as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
+ import{f as d}from"./chunk-BK445WWE.js";import{a as u,c as g}from"./chunk-OXR2FPHK.js";g();var m=[{type:"email",pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,mask:n=>n[0]+"***@"+n.split("@")[1]},{type:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,mask:()=>"***-**-****"},{type:"credit-card",pattern:/\b(?:\d[ -]*?){13,19}\b/g,mask:n=>"****-****-****-"+n.replace(/\D/g,"").slice(-4)},{type:"phone",pattern:/\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b/g,mask:n=>n.slice(0,3)+"***"+n.slice(-2)},{type:"api-key",pattern:/(?:key|token|api_key|apikey|secret|password|passwd|auth)=([A-Za-z0-9_\-]{16,})/gi,mask:()=>"***REDACTED***"}],y=class extends d{config={name:"qe/security/url-validate",description:"Validate URL security: checks for XSS/injection patterns, unsafe protocols, and scans URL query parameters for PII exposure (emails, SSNs, credit cards, API keys).",domain:"security-compliance",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{url:{type:"string",description:"URL to validate for security threats and PII exposure"},enablePII:{type:"boolean",description:"Enable PII exposure scanning in URL and query parameters",default:!0}},required:["url"]}}async execute(s,r){try{let e=this.validateURLSecurity(s.url),t=s.enablePII!==!1?this.scanForPII(s.url):{scanned:!1,found:!1,types:[],details:[]},c=e.issues.length+(t.found?t.types.length:0)===0?`URL passed all checks (security: clean, PII: ${t.scanned?"none found":"not scanned"})`:`URL has ${e.issues.length} security issue(s)${t.found?` and ${t.types.length} PII type(s) exposed in URL`:""}`;return{success:!0,data:{url:s.url,urlSecurity:e,piiExposure:t,summary:c}}}catch(e){return{success:!1,error:u(e)}}}validateURLSecurity(s){let r=[],e="none";try{let t=new URL(s);["http:","https:"].includes(t.protocol)||(r.push({type:"unsafe-protocol",description:`Protocol ${t.protocol} is not allowed`,severity:"high"}),e="high");let o=[/<script/i,/javascript:/i,/on\w+=/i,/data:text\/html/i];for(let i of o)if(i.test(s)){r.push({type:"xss",description:"Potential XSS pattern detected in URL",severity:"critical"}),e="critical";break}let c=[/'.*or.*'/i,/union.*select/i,/drop.*table/i,/;\s*--/i];for(let i of c)if(i.test(s)){r.push({type:"sql-injection",description:"Potential SQL injection pattern detected in URL",severity:"critical"}),e="critical";break}/\.\.[/\\]/.test(s)&&(r.push({type:"path-traversal",description:"Potential path traversal pattern (../) detected",severity:"high"}),e!=="critical"&&(e="high"));let a=["redirect","url","next","return","returnUrl","goto"];for(let i of a){let l=t.searchParams.get(i);l&&/^https?:\/\//.test(l)&&(r.push({type:"open-redirect",description:`Query parameter "${i}" contains an external URL \u2014 potential open redirect`,severity:"medium"}),e==="none"&&(e="medium"))}}catch{r.push({type:"invalid-url",description:"URL could not be parsed",severity:"critical"}),e="critical"}return{valid:r.length===0,riskLevel:e,issues:r}}scanForPII(s){let r=[],e=new Set,t;try{t=decodeURIComponent(s)}catch{t=s}let o="",c="";try{let a=new URL(t);o=a.search,c=a.pathname}catch{o=t}for(let{type:a,pattern:i,mask:l}of m){i.lastIndex=0;let p;for(;(p=i.exec(t))!==null;){e.add(a);let h=o.includes(p[0])?"query-parameter":c.includes(p[0])?"path":"url";r.push({type:a,location:h,masked:l(p[0])})}}return{scanned:!0,found:e.size>0,types:Array.from(e),details:r}}};export{y as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
2
  import{createRequire as t}from"module";var o=t(import.meta.url),e=o("@xenova/transformers"),n=e,{RuvectorLayer:i,TensorCompress:a,differentiableSearch:s,hierarchicalForward:c,getCompressionLevel:l,init:p,FlashAttention:m,DotProductAttention:u,MultiHeadAttention:d,HyperbolicAttention:A,LinearAttention:f,MoEAttention:h,SonaEngine:_,pipeline:v}=e||{};export{n as a,i as b,a as c,s as d,c as e,l as f,p as g,m as h,u as i,d as j,A as k,f as l,h as m,_ as n,v as o};
@@ -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.9.1");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
2
  import{writeFileSync as p,readFileSync as m}from"node:fs";import{resolve as f,dirname as c,join as d}from"node:path";import{mkdirSync as g}from"node:fs";import{fileURLToPath as h}from"node:url";function $(){try{let e=typeof __dirname<"u"?__dirname:c(h(import.meta.url));for(let t=0;t<5;t++){let n=d(e,"package.json");try{let r=JSON.parse(m(n,"utf-8"));if(r.version)return r.version}catch{}e=c(e)}}catch{}return"unknown"}var T=["-F, --format <format>","Output format (text|json|sarif|junit|markdown)","text"],x=["-o, --output <path>","Write output to file instead of stdout"];function C(e,t,n){if(t){let r=f(t);g(c(r),{recursive:!0}),p(r,e,"utf-8"),n&&console.log(n),console.log(`Output written to: ${r}`)}else console.log(e)}function R(e){return JSON.stringify(e,null,2)}var v="https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json";function w(e){let t=i=>{switch(i.toLowerCase()){case"critical":case"high":return"error";case"medium":return"warning";case"low":case"info":return"note";default:return"warning"}},n=new Map,r=[];for(let i of e.vulnerabilities){let o=i.ruleId||`AQE/${i.type.replace(/\s+/g,"-").toLowerCase()}`;n.has(o)||n.set(o,{id:o,name:i.type,shortDescription:i.type,...i.cweId?{helpUri:`https://cwe.mitre.org/data/definitions/${i.cweId.replace("CWE-","")}.html`}:{}}),r.push({ruleId:o,level:t(i.severity),message:{text:i.message},locations:[{physicalLocation:{artifactLocation:{uri:i.file,uriBaseId:"%SRCROOT%"},region:{startLine:i.line,startColumn:1}}}],...i.cweId?{taxa:[{id:i.cweId,toolComponent:{name:"CWE"}}]}:{}})}let s={$schema:v,version:"2.1.0",runs:[{tool:{driver:{name:"agentic-qe",version:$(),informationUri:"https://github.com/proffesor-for-testing/agentic-qe",rules:Array.from(n.values()).map(i=>({id:i.id,name:i.name,shortDescription:{text:i.shortDescription},...i.helpUri?{helpUri:i.helpUri}:{},defaultConfiguration:{level:"warning"}}))}},results:r,invocations:[{executionSuccessful:!0,commandLine:`aqe security --sast --format sarif -t ${e.target}`}]}]};return JSON.stringify(s,null,2)}function a(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function I(e){let t=e.tests||[],n=e.passed+e.failed+e.skipped,r=(e.duration/1e3).toFixed(3),s=`<?xml version="1.0" encoding="UTF-8"?>
3
3
  `;if(s+=`<testsuites tests="${n}" failures="${e.failed}" errors="0" time="${r}">
4
4
  `,s+=` <testsuite name="aqe-test-run" tests="${n}" failures="${e.failed}" errors="0" skipped="${e.skipped}" time="${r}" id="${a(e.runId)}">
@@ -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.9.1");process.exit(0)}
2
- import{a as D}from"./chunk-VO3OVD5D.js";import{c as x,d as $}from"./chunk-D55PSO5D.js";import{a as j}from"./chunk-AREIP4FX.js";import"./chunk-5LDBKZ6P.js";import"./chunk-UZZCWWIG.js";import{Command as U}from"commander";import o from"chalk";import*as I from"fs";import*as p from"path";import*as F from"fs";import*as R from"path";var P={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}}},Q=[".aqe-ci.yml",".aqe-ci.yaml","aqe-ci.yml","aqe-ci.yaml"];function G(s=process.cwd()){let n=R.resolve(s);for(let r=0;r<10;r++){for(let a of Q){let e=R.join(n,a);if(F.existsSync(e))return e}let l=R.dirname(n);if(l===n)break;n=l}return null}function T(s){if(!F.existsSync(s))return{success:!1,errors:[`Config file not found: ${s}`]};let n;try{n=F.readFileSync(s,"utf-8")}catch(r){return{success:!1,errors:[`Failed to read config: ${r}`]}}return N(n,s)}function N(s,n){let r=[],l;try{l=j(s)}catch(e){return{success:!1,errors:[`Invalid YAML: ${e}`]}}let a={version:l.version||P.version,name:l.name||P.name,phases:[],output:{...P.output},qualityGate:{...P.qualityGate,thresholds:{...P.qualityGate.thresholds}}};if(l.output&&typeof l.output=="object"){let e=l.output;e.format&&(a.output.format=e.format),e.directory&&(a.output.directory=e.directory),e.combined_report!==void 0&&(a.output.combinedReport=e.combined_report)}if(l.quality_gate&&typeof l.quality_gate=="object"){let e=l.quality_gate;if(e.enforced!==void 0&&(a.qualityGate.enforced=e.enforced),e.thresholds&&typeof e.thresholds=="object"){let t=e.thresholds;t.coverage!==void 0&&(a.qualityGate.thresholds.coverage=t.coverage),t.security!==void 0&&(a.qualityGate.thresholds.security=t.security),t.quality!==void 0&&(a.qualityGate.thresholds.quality=t.quality)}}if(l.phases&&Array.isArray(l.phases))for(let e=0;e<l.phases.length;e++){let t=l.phases[e];if(!t.name){r.push(`Phase ${e+1} must have a "name" field`);continue}if(!t.type){r.push(`Phase "${t.name}" must have a "type" field`);continue}let i=["test","coverage","security","quality-gate","code-intelligence","custom"];if(!i.includes(t.type)){r.push(`Phase "${t.name}" has invalid type "${t.type}". Valid: ${i.join(", ")}`);continue}let h={name:t.name,type:t.type,enabled:t.enabled!==!1,config:t.config||{},continueOnFailure:t.continue_on_failure||!1,timeout:t.timeout||300};a.phases.push(h)}else a.phases=[...P.phases];return a.phases.length===0&&r.push("Config must have at least one phase"),r.length>0?{success:!1,config:a,errors:r}:{success:!0,config:a,errors:[],configPath:n}}function E(){return{...P,phases:P.phases.map(s=>({...s,config:{...s.config}})),output:{...P.output},qualityGate:{...P.qualityGate,thresholds:{...P.qualityGate.thresholds}}}}async function W(s,n,r,l){let a=Date.now(),e=[];if(!s.enabled)return{phase:s.name,type:s.type,status:"skipped",duration:0,exitCode:0,summary:"Phase disabled",artifacts:[]};try{let t={},i="passed",h="";switch(s.type){case"test":{let f=await n.kernel.getDomainAPIAsync("test-generation");if(!f)return A(s,a,"failed",1,"Test generation domain not available",e);let C=s.config.target||".",{walkSourceFiles:m}=await import("./file-discovery-XFSGQNM3.js"),w=p.resolve(C),v=m(w,{includeTests:!1}),y=await f.generateTests({sourceFiles:v,testType:s.config.type||"unit",framework:s.config.framework||"vitest",coverageTarget:80});if(y.success&&y.value){let g=y.value;t={testsGenerated:g.tests.length,coverageEstimate:g.coverageEstimate},h=`Generated ${g.tests.length} tests (est. ${g.coverageEstimate}% coverage)`;let d=p.join(r,"test-generation.json");I.writeFileSync(d,$(g),"utf-8"),e.push(d)}else i="failed",h=y.error?.message||"Test generation failed";break}case"coverage":{let f=await n.kernel.getDomainAPIAsync("coverage-analysis");if(!f)return A(s,a,"failed",1,"Coverage analysis domain not available",e);let C=s.config.target||".",m=s.config.threshold||80,{walkSourceFiles:w}=await import("./file-discovery-XFSGQNM3.js"),v=p.resolve(C),y=w(v,{includeTests:!1}),g=D(y),d=await f.analyze({coverageData:g,threshold:m,includeFileDetails:!0});if(d.success&&d.value){let b=d.value;t={...b.summary,meetsThreshold:b.meetsThreshold,threshold:m},i=b.meetsThreshold?"passed":"warning",h=`Line: ${b.summary.line}%, Branch: ${b.summary.branch}% \u2014 ${b.meetsThreshold?"meets":"below"} ${m}% threshold`;let q=p.join(r,"coverage.json");I.writeFileSync(q,$(d.value),"utf-8"),e.push(q)}else i="failed",h=d.error?.message||"Coverage analysis failed";break}case"security":{let f=await n.kernel.getDomainAPIAsync("security-compliance");if(!f)return A(s,a,"failed",1,"Security domain not available",e);let C=s.config.target||".",{walkSourceFiles:m}=await import("./file-discovery-XFSGQNM3.js"),w=p.resolve(C),v=m(w,{includeTests:!0}),y=await f.runSASTScan(v);if(y.success&&y.value){let g=y.value,d=g.vulnerabilities||[],b=d.filter(S=>S.severity==="high"||S.severity==="critical").length;t={vulnerabilities:d.length,high:b},i=b>0?"failed":d.length>0?"warning":"passed",h=d.length===0?"No vulnerabilities found":`${d.length} vulnerabilities (${b} high/critical)`;let{toSARIF:q}=await import("./ci-output-XYR2PSYH.js"),c=p.join(r,"security.sarif");I.writeFileSync(c,q({vulnerabilities:d,target:C,scanType:"SAST"}),"utf-8"),e.push(c);let u=p.join(r,"security.json");I.writeFileSync(u,$(g),"utf-8"),e.push(u)}else i="failed",h=y.error?.message||"Security scan failed";break}case"quality-gate":{let f=await n.kernel.getDomainAPIAsync("quality-assessment");if(!f)return A(s,a,"failed",1,"Quality assessment domain not available",e);let C=await f.evaluate({runGate:!0,includeAdvice:!0});if(C.success&&C.value){let m=C.value,w=m.passed??m.meetsThreshold??!0;t={passed:w,score:m.score||m.grade,checks:m.checks},i=w?"passed":"failed",h=`Quality gate: ${w?"PASSED":"FAILED"} (score: ${m.score||m.grade||"N/A"})`;let v=p.join(r,"quality-gate.json");I.writeFileSync(v,$(m),"utf-8"),e.push(v)}else i="failed",h=C.error?.message||"Quality gate evaluation failed";break}case"code-intelligence":{let f=await n.kernel.getDomainAPIAsync("code-intelligence");if(!f)return A(s,a,"failed",1,"Code intelligence domain not available",e);let C=s.config.target||".",{walkSourceFiles:m}=await import("./file-discovery-XFSGQNM3.js"),w=p.resolve(C),v=m(w,{includeTests:!1}),y=await f.index({paths:v,incremental:!0});if(y.success&&y.value){let g=y.value;t=g,h=`Indexed ${g.filesIndexed} files, ${g.nodesCreated} nodes`;let d=p.join(r,"code-intelligence.json");I.writeFileSync(d,$(g),"utf-8"),e.push(d)}else i="warning",h=y.error?.message||"Code intelligence indexing incomplete";break}default:h=`Custom phase "${s.name}" \u2014 no built-in handler`,i="warning"}let k=Date.now()-a;return{phase:s.name,type:s.type,status:i,duration:k,exitCode:i==="failed"?1:0,summary:h,artifacts:e,details:t}}catch(t){let i=Date.now()-a;return{phase:s.name,type:s.type,status:"failed",duration:i,exitCode:1,summary:`Error: ${t instanceof Error?t.message:String(t)}`,artifacts:e}}}function A(s,n,r,l,a,e){return{phase:s.name,type:s.type,status:r,duration:Date.now()-n,exitCode:l,summary:a,artifacts:e}}function _(s){let n=`# AQE CI/CD Report
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.3");process.exit(0)}
2
+ import{a as D}from"./chunk-2GZ4EG3L.js";import{c as x,d as $}from"./chunk-ZVMAE5JD.js";import{a as j}from"./chunk-SDHZLA45.js";import"./chunk-TA454OEB.js";import"./chunk-7ASGPJWU.js";import{Command as U}from"commander";import o from"chalk";import*as I from"fs";import*as p from"path";import*as F from"fs";import*as R from"path";var P={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}}},Q=[".aqe-ci.yml",".aqe-ci.yaml","aqe-ci.yml","aqe-ci.yaml"];function G(s=process.cwd()){let n=R.resolve(s);for(let r=0;r<10;r++){for(let a of Q){let e=R.join(n,a);if(F.existsSync(e))return e}let l=R.dirname(n);if(l===n)break;n=l}return null}function T(s){if(!F.existsSync(s))return{success:!1,errors:[`Config file not found: ${s}`]};let n;try{n=F.readFileSync(s,"utf-8")}catch(r){return{success:!1,errors:[`Failed to read config: ${r}`]}}return N(n,s)}function N(s,n){let r=[],l;try{l=j(s)}catch(e){return{success:!1,errors:[`Invalid YAML: ${e}`]}}let a={version:l.version||P.version,name:l.name||P.name,phases:[],output:{...P.output},qualityGate:{...P.qualityGate,thresholds:{...P.qualityGate.thresholds}}};if(l.output&&typeof l.output=="object"){let e=l.output;e.format&&(a.output.format=e.format),e.directory&&(a.output.directory=e.directory),e.combined_report!==void 0&&(a.output.combinedReport=e.combined_report)}if(l.quality_gate&&typeof l.quality_gate=="object"){let e=l.quality_gate;if(e.enforced!==void 0&&(a.qualityGate.enforced=e.enforced),e.thresholds&&typeof e.thresholds=="object"){let t=e.thresholds;t.coverage!==void 0&&(a.qualityGate.thresholds.coverage=t.coverage),t.security!==void 0&&(a.qualityGate.thresholds.security=t.security),t.quality!==void 0&&(a.qualityGate.thresholds.quality=t.quality)}}if(l.phases&&Array.isArray(l.phases))for(let e=0;e<l.phases.length;e++){let t=l.phases[e];if(!t.name){r.push(`Phase ${e+1} must have a "name" field`);continue}if(!t.type){r.push(`Phase "${t.name}" must have a "type" field`);continue}let i=["test","coverage","security","quality-gate","code-intelligence","custom"];if(!i.includes(t.type)){r.push(`Phase "${t.name}" has invalid type "${t.type}". Valid: ${i.join(", ")}`);continue}let h={name:t.name,type:t.type,enabled:t.enabled!==!1,config:t.config||{},continueOnFailure:t.continue_on_failure||!1,timeout:t.timeout||300};a.phases.push(h)}else a.phases=[...P.phases];return a.phases.length===0&&r.push("Config must have at least one phase"),r.length>0?{success:!1,config:a,errors:r}:{success:!0,config:a,errors:[],configPath:n}}function E(){return{...P,phases:P.phases.map(s=>({...s,config:{...s.config}})),output:{...P.output},qualityGate:{...P.qualityGate,thresholds:{...P.qualityGate.thresholds}}}}async function W(s,n,r,l){let a=Date.now(),e=[];if(!s.enabled)return{phase:s.name,type:s.type,status:"skipped",duration:0,exitCode:0,summary:"Phase disabled",artifacts:[]};try{let t={},i="passed",h="";switch(s.type){case"test":{let f=await n.kernel.getDomainAPIAsync("test-generation");if(!f)return A(s,a,"failed",1,"Test generation domain not available",e);let C=s.config.target||".",{walkSourceFiles:m}=await import("./file-discovery-D4NXB3JP.js"),w=p.resolve(C),v=m(w,{includeTests:!1}),y=await f.generateTests({sourceFiles:v,testType:s.config.type||"unit",framework:s.config.framework||"vitest",coverageTarget:80});if(y.success&&y.value){let g=y.value;t={testsGenerated:g.tests.length,coverageEstimate:g.coverageEstimate},h=`Generated ${g.tests.length} tests (est. ${g.coverageEstimate}% coverage)`;let d=p.join(r,"test-generation.json");I.writeFileSync(d,$(g),"utf-8"),e.push(d)}else i="failed",h=y.error?.message||"Test generation failed";break}case"coverage":{let f=await n.kernel.getDomainAPIAsync("coverage-analysis");if(!f)return A(s,a,"failed",1,"Coverage analysis domain not available",e);let C=s.config.target||".",m=s.config.threshold||80,{walkSourceFiles:w}=await import("./file-discovery-D4NXB3JP.js"),v=p.resolve(C),y=w(v,{includeTests:!1}),g=D(y),d=await f.analyze({coverageData:g,threshold:m,includeFileDetails:!0});if(d.success&&d.value){let b=d.value;t={...b.summary,meetsThreshold:b.meetsThreshold,threshold:m},i=b.meetsThreshold?"passed":"warning",h=`Line: ${b.summary.line}%, Branch: ${b.summary.branch}% \u2014 ${b.meetsThreshold?"meets":"below"} ${m}% threshold`;let q=p.join(r,"coverage.json");I.writeFileSync(q,$(d.value),"utf-8"),e.push(q)}else i="failed",h=d.error?.message||"Coverage analysis failed";break}case"security":{let f=await n.kernel.getDomainAPIAsync("security-compliance");if(!f)return A(s,a,"failed",1,"Security domain not available",e);let C=s.config.target||".",{walkSourceFiles:m}=await import("./file-discovery-D4NXB3JP.js"),w=p.resolve(C),v=m(w,{includeTests:!0}),y=await f.runSASTScan(v);if(y.success&&y.value){let g=y.value,d=g.vulnerabilities||[],b=d.filter(S=>S.severity==="high"||S.severity==="critical").length;t={vulnerabilities:d.length,high:b},i=b>0?"failed":d.length>0?"warning":"passed",h=d.length===0?"No vulnerabilities found":`${d.length} vulnerabilities (${b} high/critical)`;let{toSARIF:q}=await import("./ci-output-ZWGXOIUD.js"),c=p.join(r,"security.sarif");I.writeFileSync(c,q({vulnerabilities:d,target:C,scanType:"SAST"}),"utf-8"),e.push(c);let u=p.join(r,"security.json");I.writeFileSync(u,$(g),"utf-8"),e.push(u)}else i="failed",h=y.error?.message||"Security scan failed";break}case"quality-gate":{let f=await n.kernel.getDomainAPIAsync("quality-assessment");if(!f)return A(s,a,"failed",1,"Quality assessment domain not available",e);let C=await f.evaluate({runGate:!0,includeAdvice:!0});if(C.success&&C.value){let m=C.value,w=m.passed??m.meetsThreshold??!0;t={passed:w,score:m.score||m.grade,checks:m.checks},i=w?"passed":"failed",h=`Quality gate: ${w?"PASSED":"FAILED"} (score: ${m.score||m.grade||"N/A"})`;let v=p.join(r,"quality-gate.json");I.writeFileSync(v,$(m),"utf-8"),e.push(v)}else i="failed",h=C.error?.message||"Quality gate evaluation failed";break}case"code-intelligence":{let f=await n.kernel.getDomainAPIAsync("code-intelligence");if(!f)return A(s,a,"failed",1,"Code intelligence domain not available",e);let C=s.config.target||".",{walkSourceFiles:m}=await import("./file-discovery-D4NXB3JP.js"),w=p.resolve(C),v=m(w,{includeTests:!1}),y=await f.index({paths:v,incremental:!0});if(y.success&&y.value){let g=y.value;t=g,h=`Indexed ${g.filesIndexed} files, ${g.nodesCreated} nodes`;let d=p.join(r,"code-intelligence.json");I.writeFileSync(d,$(g),"utf-8"),e.push(d)}else i="warning",h=y.error?.message||"Code intelligence indexing incomplete";break}default:h=`Custom phase "${s.name}" \u2014 no built-in handler`,i="warning"}let k=Date.now()-a;return{phase:s.name,type:s.type,status:i,duration:k,exitCode:i==="failed"?1:0,summary:h,artifacts:e,details:t}}catch(t){let i=Date.now()-a;return{phase:s.name,type:s.type,status:"failed",duration:i,exitCode:1,summary:`Error: ${t instanceof Error?t.message:String(t)}`,artifacts:e}}}function A(s,n,r,l,a,e){return{phase:s.name,type:s.type,status:r,duration:Date.now()-n,exitCode:l,summary:a,artifacts:e}}function _(s){let n=`# AQE CI/CD Report
3
3
 
4
4
  `;n+=`**Status:** ${s.overallStatus==="passed"?"PASSED":s.overallStatus==="warning"?"WARNING":"FAILED"}
5
5
  `,n+=`**Duration:** ${(s.duration/1e3).toFixed(1)}s
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.1");process.exit(0)}
2
- import{a,b,c,d,e,f,g,h,i,j}from"./chunk-D55PSO5D.js";import"./chunk-UZZCWWIG.js";export{a as FORMAT_OPTION,b as OUTPUT_OPTION,g as coverageToMarkdown,h as qualityGateToMarkdown,i as securityToMarkdown,j as testRunToMarkdown,d as toJSON,f as toJUnit,e as toSARIF,c 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.9.3");process.exit(0)}
2
+ import{a,b,c,d,e,f,g,h,i,j}from"./chunk-ZVMAE5JD.js";import"./chunk-7ASGPJWU.js";export{a as FORMAT_OPTION,b as OUTPUT_OPTION,g as coverageToMarkdown,h as qualityGateToMarkdown,i as securityToMarkdown,j as testRunToMarkdown,d as toJSON,f as toJUnit,e as toSARIF,c 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.9.1");process.exit(0)}
2
- import{b as p}from"./chunk-B2I7BJLL.js";import{b as f,d as h}from"./chunk-JSOBRKMA.js";import{a as c,c as b}from"./chunk-UN4PA4M2.js";import{a as v}from"./chunk-UZZCWWIG.js";h();b();import{existsSync as u,writeFileSync as g,readFileSync as m}from"node:fs";import{join as a}from"node:path";import{execSync as C}from"node:child_process";async function y(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 n={"mcp-config":"mcp","local-binary":"cli","npx-cached":"cli","npm-dependency":"npm"};return{available:!0,version:o.version,method:o.method?n[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(u(e))try{o=f(m(e,"utf-8"))}catch{}o.mcpServers||(o.mcpServers={});let n=o.mcpServers;!n.ruflo&&!n["claude-flow"]&&(n.ruflo={command:"npx",args:["ruflo@3.5.18","mcp"],env:{}}),g(e,JSON.stringify(o,null,2))}async function j(t,e){try{e&&console.log("[ClaudeFlow] Running pretrain analysis..."),C("npx --no-install ruflo hooks pretrain --depth medium",{encoding:"utf-8",timeout:12e4,cwd:t,stdio:["pipe","pipe","pipe"]}),e&&console.log("[ClaudeFlow] Pretrain analysis complete")}catch(o){e&&console.log("[ClaudeFlow] Pretrain analysis skipped:",c(o))}}async function D(t){let{projectRoot:e,force:o,checkOnly:n,debug:s}=t,r=await y(e,s);if(!r.available&&!o)return{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,workers:!1,patternSearch:!1}};let i=await F(e);if(n)return{available:r.available,version:r.version,features:i};let w=a(e,".agentic-qe"),d=a(w,"claude-flow-integration.json");try{let l=S(e,i);g(d,JSON.stringify(l,null,2)),s&&console.log(`[ClaudeFlow] Config written to: ${d}`)}catch(l){return{available:r.available,version:r.version,features:i,error:`Failed to write config: ${c(l)}`}}try{R(e)}catch(l){s&&console.log("[ClaudeFlow] MCP config update failed:",c(l))}return i.pretrain&&await j(e,s),{available:!0,version:r.version,features:i,configPath:d}}function J(t){let e=a(t,".agentic-qe","claude-flow-integration.json");return u(e)}function N(t){let e=a(t,".agentic-qe","claude-flow-integration.json");if(!u(e))return null;try{return f(m(e,"utf-8"))}catch{return null}}function I(t){let e=a(t,".agentic-qe","claude-flow-integration.json");if(u(e))try{return v("node:fs").rmSync(e),!0}catch{return!1}return!0}export{N as getClaudeFlowConfig,J as isClaudeFlowConfigured,I as removeClaudeFlowIntegration,D 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.9.3");process.exit(0)}
2
+ import{b as p}from"./chunk-TUHIFT65.js";import{b as f,d as h}from"./chunk-CU36MONI.js";import{a as c,c as b}from"./chunk-OXR2FPHK.js";import{a as v}from"./chunk-7ASGPJWU.js";h();b();import{existsSync as u,writeFileSync as g,readFileSync as m}from"node:fs";import{join as a}from"node:path";import{execSync as C}from"node:child_process";async function y(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 n={"mcp-config":"mcp","local-binary":"cli","npx-cached":"cli","npm-dependency":"npm"};return{available:!0,version:o.version,method:o.method?n[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(u(e))try{o=f(m(e,"utf-8"))}catch{}o.mcpServers||(o.mcpServers={});let n=o.mcpServers;!n.ruflo&&!n["claude-flow"]&&(n.ruflo={command:"npx",args:["ruflo@3.5.18","mcp"],env:{}}),g(e,JSON.stringify(o,null,2))}async function j(t,e){try{e&&console.log("[ClaudeFlow] Running pretrain analysis..."),C("npx --no-install ruflo hooks pretrain --depth medium",{encoding:"utf-8",timeout:12e4,cwd:t,stdio:["pipe","pipe","pipe"]}),e&&console.log("[ClaudeFlow] Pretrain analysis complete")}catch(o){e&&console.log("[ClaudeFlow] Pretrain analysis skipped:",c(o))}}async function D(t){let{projectRoot:e,force:o,checkOnly:n,debug:s}=t,r=await y(e,s);if(!r.available&&!o)return{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,workers:!1,patternSearch:!1}};let i=await F(e);if(n)return{available:r.available,version:r.version,features:i};let w=a(e,".agentic-qe"),d=a(w,"claude-flow-integration.json");try{let l=S(e,i);g(d,JSON.stringify(l,null,2)),s&&console.log(`[ClaudeFlow] Config written to: ${d}`)}catch(l){return{available:r.available,version:r.version,features:i,error:`Failed to write config: ${c(l)}`}}try{R(e)}catch(l){s&&console.log("[ClaudeFlow] MCP config update failed:",c(l))}return i.pretrain&&await j(e,s),{available:!0,version:r.version,features:i,configPath:d}}function J(t){let e=a(t,".agentic-qe","claude-flow-integration.json");return u(e)}function N(t){let e=a(t,".agentic-qe","claude-flow-integration.json");if(!u(e))return null;try{return f(m(e,"utf-8"))}catch{return null}}function I(t){let e=a(t,".agentic-qe","claude-flow-integration.json");if(u(e))try{return v("node:fs").rmSync(e),!0}catch{return!1}return!0}export{N as getClaudeFlowConfig,J as isClaudeFlowConfigured,I as removeClaudeFlowIntegration,D 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.9.3");process.exit(0)}
2
+ import{c as a,d as b,e as c}from"./chunk-ERWNQ6NC.js";import"./chunk-GGQCAQM4.js";import"./chunk-OXR2FPHK.js";import"./chunk-7ASGPJWU.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.9.1");process.exit(0)}
2
- import{b as p}from"./chunk-UBKK7KCR.js";import{a as f,c as v}from"./chunk-UN4PA4M2.js";import"./chunk-UZZCWWIG.js";v();import{existsSync as s,mkdirSync as m,readFileSync as u,writeFileSync as a}from"fs";import{join as h,dirname as d}from"path";var l=class{projectRoot;overwrite;generator;constructor(r){this.projectRoot=r.projectRoot,this.overwrite=r.overwrite??!1,this.generator=p()}async install(){let r={success:!0,mcpConfigured:!1,modeInstalled:!1,errors:[],configPath:"",modePath:""};try{let t=this.generator.generateMcpConfig("cline"),e=h(this.projectRoot,t.path);if(r.configPath=e,!s(e)||this.overwrite){let o=d(e);if(s(o)||m(o,{recursive:!0}),s(e)&&this.overwrite){let c=this.mergeExistingConfig(e,t.content);a(e,c)}else a(e,t.content);r.mcpConfigured=!0}let n=this.generator.generateBehavioralRules("cline"),i=h(this.projectRoot,n.path);if(r.modePath=i,!s(i)||this.overwrite){let o=d(i);if(s(o)||m(o,{recursive:!0}),s(i)&&this.overwrite){let c=this.mergeExistingModes(i,n.content);a(i,c)}else a(i,n.content);r.modeInstalled=!0}}catch(t){r.success=!1,r.errors.push(`Cline installation failed: ${f(t)}`)}return r}mergeExistingConfig(r,t){try{let e=JSON.parse(u(r,"utf-8")),n=JSON.parse(t);return e.mcpServers||(e.mcpServers={}),Object.assign(e.mcpServers,n.mcpServers),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.9.3");process.exit(0)}
2
+ import{b as p}from"./chunk-HJEWQD2B.js";import{a as f,c as v}from"./chunk-OXR2FPHK.js";import"./chunk-7ASGPJWU.js";v();import{existsSync as s,mkdirSync as m,readFileSync as u,writeFileSync as a}from"fs";import{join as h,dirname as d}from"path";var l=class{projectRoot;overwrite;generator;constructor(r){this.projectRoot=r.projectRoot,this.overwrite=r.overwrite??!1,this.generator=p()}async install(){let r={success:!0,mcpConfigured:!1,modeInstalled:!1,errors:[],configPath:"",modePath:""};try{let t=this.generator.generateMcpConfig("cline"),e=h(this.projectRoot,t.path);if(r.configPath=e,!s(e)||this.overwrite){let o=d(e);if(s(o)||m(o,{recursive:!0}),s(e)&&this.overwrite){let c=this.mergeExistingConfig(e,t.content);a(e,c)}else a(e,t.content);r.mcpConfigured=!0}let n=this.generator.generateBehavioralRules("cline"),i=h(this.projectRoot,n.path);if(r.modePath=i,!s(i)||this.overwrite){let o=d(i);if(s(o)||m(o,{recursive:!0}),s(i)&&this.overwrite){let c=this.mergeExistingModes(i,n.content);a(i,c)}else a(i,n.content);r.modeInstalled=!0}}catch(t){r.success=!1,r.errors.push(`Cline installation failed: ${f(t)}`)}return r}mergeExistingConfig(r,t){try{let e=JSON.parse(u(r,"utf-8")),n=JSON.parse(t);return e.mcpServers||(e.mcpServers={}),Object.assign(e.mcpServers,n.mcpServers),JSON.stringify(e,null,2)+`
3
3
  `}catch{return t}}mergeExistingModes(r,t){try{let e=JSON.parse(u(r,"utf-8")),n=JSON.parse(t);if(!Array.isArray(e))return t;let i=e.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.9.1");process.exit(0)}
2
- import{a as A,b as $}from"./chunk-GJW6V35N.js";import{c as b,d as x}from"./chunk-D55PSO5D.js";import"./chunk-UZZCWWIG.js";import{Command as z}from"commander";import e from"chalk";function j(S,w,P){return new z("code").description("Code intelligence analysis").argument("<action>","Action (index|search|impact|deps|complexity)").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("-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.9.3");process.exit(0)}
2
+ import{a as A,b as $}from"./chunk-DTNXHRUF.js";import{c as b,d as x}from"./chunk-ZVMAE5JD.js";import"./chunk-7ASGPJWU.js";import{Command as z}from"commander";import e from"chalk";function j(S,w,P){return new z("code").description("Code intelligence analysis").argument("<action>","Action (index|search|impact|deps|complexity)").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("-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)
@@ -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.9.1");process.exit(0)}
2
- import"./chunk-UZZCWWIG.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.9.3");process.exit(0)}
2
+ import"./chunk-7ASGPJWU.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.9.1");process.exit(0)}
2
- import{b as f}from"./chunk-UBKK7KCR.js";import{a as l,c as m}from"./chunk-UN4PA4M2.js";import"./chunk-UZZCWWIG.js";m();import{existsSync as o,mkdirSync as h,readFileSync as d,writeFileSync as s}from"fs";import{join as u,dirname as x}from"path";var c=class{projectRoot;overwrite;generator;constructor(t){this.projectRoot=t.projectRoot,this.overwrite=t.overwrite??!1,this.generator=f()}async install(){let t={success:!0,mcpConfigured:!1,agentsMdInstalled:!1,errors:[],configPath:"",agentsMdPath:""};try{let r=this.generator.generateMcpConfig("codex"),e=u(this.projectRoot,r.path);if(t.configPath=e,!o(e)||this.overwrite){let i=x(e);if(o(i)||h(i,{recursive:!0}),o(e)&&this.overwrite){let p=this.mergeExistingTomlConfig(e,r.content);s(e,p)}else s(e,r.content);t.mcpConfigured=!0}let a=this.generator.generateBehavioralRules("codex"),n=u(this.projectRoot,a.path);if(t.agentsMdPath=n,!o(n)||this.overwrite){if(o(n)&&this.overwrite){let i=this.mergeExistingAgentsMd(n,a.content);s(n,i)}else s(n,a.content);t.agentsMdInstalled=!0}}catch(r){t.success=!1,t.errors.push(`Codex installation failed: ${l(r)}`)}return t}mergeExistingTomlConfig(t,r){try{let e=d(t,"utf-8");return e.includes("[mcp_servers.agentic-qe]")?e:e.trimEnd()+`
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.9.3");process.exit(0)}
2
+ import{b as f}from"./chunk-HJEWQD2B.js";import{a as l,c as m}from"./chunk-OXR2FPHK.js";import"./chunk-7ASGPJWU.js";m();import{existsSync as o,mkdirSync as h,readFileSync as d,writeFileSync as s}from"fs";import{join as u,dirname as x}from"path";var c=class{projectRoot;overwrite;generator;constructor(t){this.projectRoot=t.projectRoot,this.overwrite=t.overwrite??!1,this.generator=f()}async install(){let t={success:!0,mcpConfigured:!1,agentsMdInstalled:!1,errors:[],configPath:"",agentsMdPath:""};try{let r=this.generator.generateMcpConfig("codex"),e=u(this.projectRoot,r.path);if(t.configPath=e,!o(e)||this.overwrite){let i=x(e);if(o(i)||h(i,{recursive:!0}),o(e)&&this.overwrite){let p=this.mergeExistingTomlConfig(e,r.content);s(e,p)}else s(e,r.content);t.mcpConfigured=!0}let a=this.generator.generateBehavioralRules("codex"),n=u(this.projectRoot,a.path);if(t.agentsMdPath=n,!o(n)||this.overwrite){if(o(n)&&this.overwrite){let i=this.mergeExistingAgentsMd(n,a.content);s(n,i)}else s(n,a.content);t.agentsMdInstalled=!0}}catch(r){t.success=!1,t.errors.push(`Codex installation failed: ${l(r)}`)}return t}mergeExistingTomlConfig(t,r){try{let e=d(t,"utf-8");return e.includes("[mcp_servers.agentic-qe]")?e:e.trimEnd()+`
3
3
 
4
4
  `+r}catch{return r}}mergeExistingAgentsMd(t,r){try{let e=d(t,"utf-8");return e.includes("Agentic QE")||e.includes("fleet_init")?e:e.trimEnd()+`
5
5
 
@@ -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.9.1");process.exit(0)}
2
- import"./chunk-UZZCWWIG.js";import{Command as N}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"],S=[...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.9.3");process.exit(0)}
2
+ import"./chunk-7ASGPJWU.js";import{Command as N}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"],S=[...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.9.1");process.exit(0)}
2
- import{a,b,c,d,e,f,g,h,i}from"./chunk-36X2O3BL.js";import"./chunk-3VAKR43Z.js";import"./chunk-WDJBGXC2.js";import"./chunk-UZZCWWIG.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.9.3");process.exit(0)}
2
+ import{a,b,c,d,e,f,g,h,i}from"./chunk-GBLX5XOH.js";import"./chunk-D5GIV6O7.js";import"./chunk-WAWCNUIJ.js";import"./chunk-7ASGPJWU.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.9.1");process.exit(0)}
2
- import{b as g}from"./chunk-UBKK7KCR.js";import{a as u,c as h}from"./chunk-UN4PA4M2.js";import"./chunk-UZZCWWIG.js";h();import{existsSync as o,mkdirSync as f,readFileSync as d,writeFileSync as a}from"fs";import{join as m,dirname as p}from"path";var c=class{projectRoot;overwrite;generator;constructor(t){this.projectRoot=t.projectRoot,this.overwrite=t.overwrite??!1,this.generator=g()}async install(){let t={success:!0,mcpConfigured:!1,rulesInstalled:!1,errors:[],configPath:"",rulesPath:""};try{let r=this.generator.generateMcpConfig("continuedev"),e=m(this.projectRoot,r.path);if(t.configPath=e,!o(e)||this.overwrite){let n=p(e);if(o(n)||f(n,{recursive:!0}),o(e)&&this.overwrite){let v=this.mergeExistingYamlConfig(e,r.content);a(e,v)}else a(e,r.content);t.mcpConfigured=!0}let s=this.generator.generateBehavioralRules("continuedev"),i=m(this.projectRoot,s.path);if(t.rulesPath=i,!o(i)||this.overwrite){let n=p(i);o(n)||f(n,{recursive:!0}),a(i,s.content),t.rulesInstalled=!0}}catch(r){t.success=!1,t.errors.push(`Continue.dev installation failed: ${u(r)}`)}return t}mergeExistingYamlConfig(t,r){try{let e=d(t,"utf-8");return e.includes("agentic-qe")?e:e.includes("mcpServers:")?e.trimEnd()+`
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.9.3");process.exit(0)}
2
+ import{b as g}from"./chunk-HJEWQD2B.js";import{a as u,c as h}from"./chunk-OXR2FPHK.js";import"./chunk-7ASGPJWU.js";h();import{existsSync as o,mkdirSync as f,readFileSync as d,writeFileSync as a}from"fs";import{join as m,dirname as p}from"path";var c=class{projectRoot;overwrite;generator;constructor(t){this.projectRoot=t.projectRoot,this.overwrite=t.overwrite??!1,this.generator=g()}async install(){let t={success:!0,mcpConfigured:!1,rulesInstalled:!1,errors:[],configPath:"",rulesPath:""};try{let r=this.generator.generateMcpConfig("continuedev"),e=m(this.projectRoot,r.path);if(t.configPath=e,!o(e)||this.overwrite){let n=p(e);if(o(n)||f(n,{recursive:!0}),o(e)&&this.overwrite){let v=this.mergeExistingYamlConfig(e,r.content);a(e,v)}else a(e,r.content);t.mcpConfigured=!0}let s=this.generator.generateBehavioralRules("continuedev"),i=m(this.projectRoot,s.path);if(t.rulesPath=i,!o(i)||this.overwrite){let n=p(i);o(n)||f(n,{recursive:!0}),a(i,s.content),t.rulesInstalled=!0}}catch(r){t.success=!1,t.errors.push(`Continue.dev installation failed: ${u(r)}`)}return t}mergeExistingYamlConfig(t,r){try{let e=d(t,"utf-8");return e.includes("agentic-qe")?e:e.includes("mcpServers:")?e.trimEnd()+`
3
3
  `+` - name: agentic-qe
4
4
  command: npx
5
5
  args: