agentic-qe 3.9.35 → 3.9.36

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 (299) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +56 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/cli/bundle.js +5 -5
  5. package/dist/cli/chunks/adapter-MISKG4JY.js +2 -0
  6. package/dist/cli/chunks/{agent-booster-wasm-4PJZ34PF.js → agent-booster-wasm-L6D36M77.js} +2 -2
  7. package/dist/cli/chunks/{agent-handler-OB5JATVT.js → agent-handler-3JNKP4OI.js} +2 -2
  8. package/dist/cli/chunks/{agent-memory-branch-ZEHRWZ5R.js → agent-memory-branch-QBRBX7O4.js} +2 -2
  9. package/dist/cli/chunks/aqe-learning-engine-NDLBNM6C.js +2 -0
  10. package/dist/cli/chunks/{audit-PWFRSBBW.js → audit-M4W43TXQ.js} +2 -2
  11. package/dist/cli/chunks/base-OMDJAHGF.js +2 -0
  12. package/dist/cli/chunks/{hnswlib-node-XEOLAMMR.js → better-sqlite3-SPABZYYQ.js} +2 -2
  13. package/dist/cli/chunks/{brain-handler-6SMUCFO7.js → brain-handler-WQN7C55Z.js} +3 -3
  14. package/dist/cli/chunks/{branch-enumerator-U6ROQR4O.js → branch-enumerator-BOTGLI7M.js} +2 -2
  15. package/dist/cli/chunks/{browser-BMM57TA3.js → browser-ZFZCR7LP.js} +2 -2
  16. package/dist/cli/chunks/browser-workflow-XUG5Z5CJ.js +2 -0
  17. package/dist/cli/chunks/{chunk-2UY3X3KE.js → chunk-27FNROZ2.js} +9 -9
  18. package/dist/cli/chunks/{chunk-42QMNST6.js → chunk-2AANIKDG.js} +2 -2
  19. package/dist/cli/chunks/{chunk-ICYM7H6T.js → chunk-2EWOYVH3.js} +2 -2
  20. package/dist/cli/chunks/{chunk-4HJVTKJD.js → chunk-2KMCRASK.js} +1 -1
  21. package/dist/cli/chunks/{chunk-3BDZSWCA.js → chunk-3CIQ6CQ4.js} +2 -2
  22. package/dist/cli/chunks/{chunk-NPUMPLL7.js → chunk-4R3WXD4U.js} +1 -1
  23. package/dist/cli/chunks/{chunk-KAEWFVGD.js → chunk-556GYKN5.js} +2 -2
  24. package/dist/cli/chunks/{chunk-GQCIW2ZZ.js → chunk-5ECOD4O6.js} +1 -1
  25. package/dist/cli/chunks/{chunk-WGWOCTQW.js → chunk-5M63H6RY.js} +1 -1
  26. package/dist/cli/chunks/{chunk-IXOGBA7C.js → chunk-5MSZREOD.js} +2 -2
  27. package/dist/cli/chunks/{chunk-3UGY4ZQB.js → chunk-5OAAJUGO.js} +1 -1
  28. package/dist/cli/chunks/{chunk-O3MTYRBX.js → chunk-5RPHV7Y3.js} +1 -1
  29. package/dist/cli/chunks/{chunk-ACL5JFJR.js → chunk-5SYH5QMQ.js} +2 -2
  30. package/dist/cli/chunks/{chunk-NS4P3VRA.js → chunk-5ZTY5JJX.js} +2 -2
  31. package/dist/cli/chunks/{chunk-QOAVXGAU.js → chunk-66636UWH.js} +2 -2
  32. package/dist/cli/chunks/{chunk-XMCMLPXY.js → chunk-6BHUKCLI.js} +2 -2
  33. package/dist/cli/chunks/{chunk-YYKZVBIG.js → chunk-6DACR7QY.js} +2 -2
  34. package/dist/cli/chunks/{chunk-3YIVRMQB.js → chunk-6M2POFDF.js} +1 -1
  35. package/dist/cli/chunks/{chunk-56O5V5MP.js → chunk-6M44C43I.js} +2 -2
  36. package/dist/cli/chunks/{chunk-I5XEXLBF.js → chunk-74DA4P5K.js} +1 -1
  37. package/dist/cli/chunks/{chunk-T26ENWX5.js → chunk-7TO7NTLT.js} +8 -8
  38. package/dist/cli/chunks/{chunk-S3QU54ZQ.js → chunk-7ZCDG3IM.js} +1 -1
  39. package/dist/cli/chunks/{chunk-PK3NAZQI.js → chunk-A3TOJ4KN.js} +2 -2
  40. package/dist/cli/chunks/{chunk-GR732YA3.js → chunk-AH3TKDVW.js} +2 -2
  41. package/dist/cli/chunks/{chunk-TE27EK44.js → chunk-AH3UC4IV.js} +2 -2
  42. package/dist/cli/chunks/{chunk-HKQ23RPJ.js → chunk-AJ2VFSLX.js} +2 -2
  43. package/dist/cli/chunks/{chunk-YPJ2O3TE.js → chunk-AWC7G2D3.js} +2 -2
  44. package/dist/cli/chunks/{chunk-CMKNLC3Q.js → chunk-AY2LLGZN.js} +4 -4
  45. package/dist/cli/chunks/{chunk-SMPMLODT.js → chunk-BGD65PL4.js} +1 -1
  46. package/dist/cli/chunks/{chunk-YLYKRAGZ.js → chunk-BI54GWTK.js} +2 -2
  47. package/dist/cli/chunks/{chunk-I7XQT6YM.js → chunk-BNFW4LMD.js} +2 -2
  48. package/dist/cli/chunks/{chunk-X3GKTB6R.js → chunk-BUVY7IGM.js} +1 -1
  49. package/dist/cli/chunks/{chunk-XUZ73S3Y.js → chunk-C2JK5O55.js} +2 -2
  50. package/dist/cli/chunks/{chunk-4UZ7G2KT.js → chunk-CAGRQR2U.js} +2 -2
  51. package/dist/cli/chunks/{chunk-BSM7YJBY.js → chunk-CJQT3MYN.js} +1 -1
  52. package/dist/cli/chunks/{chunk-72HXOVRN.js → chunk-CK5TGFII.js} +1 -1
  53. package/dist/cli/chunks/{chunk-4YKHVRQH.js → chunk-CLATNP57.js} +3 -3
  54. package/dist/cli/chunks/{chunk-II6DIMY6.js → chunk-CSDGFQKW.js} +2 -2
  55. package/dist/cli/chunks/{chunk-F6R2TGNS.js → chunk-D5CLABLM.js} +2 -2
  56. package/dist/cli/chunks/{chunk-BCD2IMXF.js → chunk-DCXFHBHS.js} +2 -2
  57. package/dist/cli/chunks/{chunk-6CCKOU2U.js → chunk-DKBBMZWB.js} +2 -2
  58. package/dist/cli/chunks/{chunk-SBDRHY3I.js → chunk-DTJHO3WI.js} +2 -2
  59. package/dist/cli/chunks/{chunk-5XXZQCHS.js → chunk-EAMKH35X.js} +1 -1
  60. package/dist/cli/chunks/{chunk-2FTSVPVG.js → chunk-EDG4NEET.js} +1 -1
  61. package/dist/cli/chunks/{chunk-BXBUUSJN.js → chunk-ESIE3MT5.js} +3 -3
  62. package/dist/cli/chunks/{chunk-BEJAUYFA.js → chunk-EXBJCDFM.js} +2 -2
  63. package/dist/cli/chunks/{chunk-G6BJ5I57.js → chunk-EXUT2LCP.js} +1 -1
  64. package/dist/cli/chunks/{chunk-UDKBQAAH.js → chunk-F57OUXHJ.js} +2 -2
  65. package/dist/cli/chunks/{chunk-MSEG7GKM.js → chunk-F5IVWV2P.js} +1 -1
  66. package/dist/cli/chunks/{chunk-T2QVCK56.js → chunk-FK4B2HIW.js} +1 -1
  67. package/dist/cli/chunks/{chunk-GWXP36YP.js → chunk-FSDUNGYM.js} +2 -2
  68. package/dist/cli/chunks/{chunk-7RNLOYAP.js → chunk-FYJE4QLL.js} +2 -2
  69. package/dist/cli/chunks/{chunk-PY7PJT2Y.js → chunk-FZA674BT.js} +2 -2
  70. package/dist/cli/chunks/{chunk-C7QVMFCJ.js → chunk-G6Q66YLG.js} +3 -3
  71. package/dist/cli/chunks/{chunk-D2ITP3ON.js → chunk-G7YDYXQH.js} +2 -2
  72. package/dist/cli/chunks/{chunk-YTB7DDLE.js → chunk-GAC4MD6S.js} +1 -1
  73. package/dist/cli/chunks/{chunk-OPD6AENV.js → chunk-GFMSAL5Y.js} +2 -2
  74. package/dist/cli/chunks/{chunk-J2LOP3GE.js → chunk-GLI5EN6O.js} +2 -2
  75. package/dist/cli/chunks/{chunk-WU3RGTLV.js → chunk-GW7HWFWQ.js} +1 -1
  76. package/dist/cli/chunks/{chunk-YL56FMCJ.js → chunk-GWLLNJ64.js} +1 -1
  77. package/dist/cli/chunks/{chunk-BBHTM2RF.js → chunk-HHGZ4LXC.js} +1 -1
  78. package/dist/cli/chunks/{chunk-RZDMSTAQ.js → chunk-HOZNVDFF.js} +2 -2
  79. package/dist/cli/chunks/{chunk-4NVDPO7L.js → chunk-I7BXATQ6.js} +2 -2
  80. package/dist/cli/chunks/{chunk-UJTI5MRE.js → chunk-IF4ZZ2HD.js} +2 -2
  81. package/dist/cli/chunks/{chunk-2ICMLI2T.js → chunk-IMP43AXO.js} +2 -2
  82. package/dist/cli/chunks/{chunk-RPRFDO23.js → chunk-JA7YARLP.js} +1 -1
  83. package/dist/cli/chunks/{chunk-FMV22K3J.js → chunk-JD3VV2BD.js} +2 -2
  84. package/dist/cli/chunks/{chunk-HAOGVFKR.js → chunk-JFDNNXIX.js} +2 -2
  85. package/dist/cli/chunks/{chunk-HMIRBSTI.js → chunk-KI6RXKP4.js} +2 -2
  86. package/dist/cli/chunks/{chunk-VMMPOLUV.js → chunk-L3JJ52N6.js} +2 -2
  87. package/dist/cli/chunks/{chunk-A7QP5E46.js → chunk-LIE24NRL.js} +2 -2
  88. package/dist/cli/chunks/{chunk-6TYWIS4R.js → chunk-LPVRFVSC.js} +2 -2
  89. package/dist/cli/chunks/{chunk-NWWXVXXG.js → chunk-LUFY3GGI.js} +2 -2
  90. package/dist/cli/chunks/{chunk-WFVBK7N3.js → chunk-MAHLTWGV.js} +2 -2
  91. package/dist/cli/chunks/{chunk-SI6VUQSI.js → chunk-MEQ4OPSL.js} +3 -3
  92. package/dist/cli/chunks/{chunk-RP5SDWCL.js → chunk-MFPVS2KP.js} +2 -2
  93. package/dist/cli/chunks/{chunk-5CZDHJZX.js → chunk-MJJAHA2T.js} +1 -1
  94. package/dist/cli/chunks/{chunk-E7N6CRFV.js → chunk-NKA3X6VT.js} +1 -1
  95. package/dist/cli/chunks/{chunk-ZAGCKWOC.js → chunk-NKBCAW27.js} +1 -1
  96. package/dist/cli/chunks/{chunk-TLBIFZM4.js → chunk-NMHULQAV.js} +2 -2
  97. package/dist/cli/chunks/{chunk-CTU4V32J.js → chunk-NYU4YD5V.js} +2 -2
  98. package/dist/cli/chunks/{chunk-DEJW6GYF.js → chunk-O4C3JEOR.js} +2 -2
  99. package/dist/cli/chunks/{chunk-MHUPY3YO.js → chunk-O5JNHH2D.js} +2 -2
  100. package/dist/cli/chunks/{chunk-YBGQT3OS.js → chunk-OLBYILKU.js} +2 -2
  101. package/dist/cli/chunks/{chunk-SSJV4AZ7.js → chunk-OO2JHVMS.js} +6 -6
  102. package/dist/cli/chunks/{chunk-A5LZVQQL.js → chunk-P4VQTIJE.js} +3 -3
  103. package/dist/cli/chunks/{chunk-JNK742DP.js → chunk-P7IOH7L4.js} +1 -1
  104. package/dist/cli/chunks/{chunk-AAVOYIKA.js → chunk-PGRDHDEJ.js} +1 -1
  105. package/dist/cli/chunks/{chunk-JW4N25B5.js → chunk-PUZAIRMY.js} +2 -2
  106. package/dist/cli/chunks/{chunk-BKF3E3UJ.js → chunk-PY4B37U3.js} +1 -1
  107. package/dist/cli/chunks/{chunk-FXITHMQB.js → chunk-PYCYZYIL.js} +4 -4
  108. package/dist/cli/chunks/{chunk-NFIOKKA6.js → chunk-QAGAEAKM.js} +2 -2
  109. package/dist/cli/chunks/{chunk-NAVH552F.js → chunk-QH7K2UPP.js} +2 -2
  110. package/dist/cli/chunks/{chunk-6WZNRHJJ.js → chunk-QMUTKI34.js} +1 -1
  111. package/dist/cli/chunks/{chunk-WSJN6HFR.js → chunk-QXM3PRVR.js} +2 -2
  112. package/dist/cli/chunks/{chunk-Z6NUCGQA.js → chunk-QYUWWTE3.js} +1 -1
  113. package/dist/cli/chunks/{chunk-6SN55CMC.js → chunk-RCU5L7FF.js} +2 -2
  114. package/dist/cli/chunks/{chunk-HGJGU625.js → chunk-RDXIRE2I.js} +2 -2
  115. package/dist/cli/chunks/{chunk-HSR7EHVN.js → chunk-SCBWRKPE.js} +1 -1
  116. package/dist/cli/chunks/{chunk-3R6YQEQY.js → chunk-SJ3SHZUC.js} +4 -4
  117. package/dist/cli/chunks/{chunk-M4BCSFVN.js → chunk-TCDGJYM2.js} +1 -1
  118. package/dist/cli/chunks/{chunk-NJUNYXMH.js → chunk-TG44VKO3.js} +2 -2
  119. package/dist/cli/chunks/{chunk-GWROZUWK.js → chunk-TK7TGVVQ.js} +1 -1
  120. package/dist/cli/chunks/{chunk-H7V3ZQT7.js → chunk-TOZ6WUAB.js} +2 -2
  121. package/dist/cli/chunks/{chunk-T4HZLBM4.js → chunk-TU2PSEDW.js} +2 -2
  122. package/dist/cli/chunks/{chunk-NZB2JE2D.js → chunk-TXSVZYFA.js} +2 -2
  123. package/dist/cli/chunks/{chunk-BTQA2E2Y.js → chunk-U6QAKKNB.js} +2 -2
  124. package/dist/cli/chunks/{chunk-X27VMOIH.js → chunk-U7B4WCBY.js} +1 -1
  125. package/dist/cli/chunks/{chunk-YQRABKOC.js → chunk-USLHYNYG.js} +2 -2
  126. package/dist/cli/chunks/{chunk-BTPDHALG.js → chunk-VENEJ3UI.js} +2 -2
  127. package/dist/cli/chunks/{chunk-FMZ7I4XV.js → chunk-W2DF6FNE.js} +1 -1
  128. package/dist/cli/chunks/{chunk-OJ5GBEXU.js → chunk-X6IEQVSF.js} +2 -2
  129. package/dist/cli/chunks/{chunk-CROIRPKG.js → chunk-X6UGFKHW.js} +2 -2
  130. package/dist/cli/chunks/{chunk-M7TDNJMZ.js → chunk-XNXFEMWT.js} +1 -1
  131. package/dist/cli/chunks/{chunk-FPPV7TYI.js → chunk-Y4ERDIPP.js} +2 -2
  132. package/dist/cli/chunks/{chunk-VLZ3LC6L.js → chunk-YE42UTLT.js} +2 -2
  133. package/dist/cli/chunks/{chunk-FMAUTL26.js → chunk-YKZ3ZJWT.js} +2 -2
  134. package/dist/cli/chunks/{chunk-UQ6JC3UY.js → chunk-YMB4YVFX.js} +3 -3
  135. package/dist/cli/chunks/{chunk-GHMIADYW.js → chunk-YUFUGGXY.js} +2 -2
  136. package/dist/cli/chunks/{chunk-IQ363U37.js → chunk-Z5A2ENBC.js} +2 -2
  137. package/dist/cli/chunks/{chunk-5Q7X5SDB.js → chunk-ZBY4HSHR.js} +2 -2
  138. package/dist/cli/chunks/{chunk-INCNWH3R.js → chunk-ZK6GXL5J.js} +2 -2
  139. package/dist/cli/chunks/chunk-ZYPSXPQ5.js +2 -0
  140. package/dist/cli/chunks/{ci-GXSOJB6I.js → ci-YA6SQ3PU.js} +2 -2
  141. package/dist/cli/chunks/{ci-output-GNUGZD2F.js → ci-output-KKHXCQI4.js} +2 -2
  142. package/dist/cli/chunks/{circuit-breaker-LAW2AAHF.js → circuit-breaker-RTBCXGKA.js} +2 -2
  143. package/dist/cli/chunks/{claude-flow-setup-VF5NUUJZ.js → claude-flow-setup-CRV3Y6LO.js} +2 -2
  144. package/dist/cli/chunks/client-VXJRAW3W.js +2 -0
  145. package/dist/cli/chunks/{cline-installer-H7RPYI3G.js → cline-installer-IS2VLXQS.js} +2 -2
  146. package/dist/cli/chunks/{code-COHRPYF6.js → code-3CSNTK5O.js} +2 -2
  147. package/dist/cli/chunks/{code-index-extractor-353PWY6B.js → code-index-extractor-P2YXEJGV.js} +2 -2
  148. package/dist/cli/chunks/{codex-installer-DIXHDH63.js → codex-installer-QGDV2CAQ.js} +2 -2
  149. package/dist/cli/chunks/{completions-NGPREB6E.js → completions-TYECEYHY.js} +2 -2
  150. package/dist/cli/chunks/{complexity-analyzer-BO3QCTWT.js → complexity-analyzer-GA5KSFF2.js} +2 -2
  151. package/dist/cli/chunks/{continuedev-installer-SG4HUNX6.js → continuedev-installer-NW5Y4ZMI.js} +2 -2
  152. package/dist/cli/chunks/{copilot-installer-RC6ZFHQG.js → copilot-installer-E5BIBYG6.js} +2 -2
  153. package/dist/cli/chunks/{cost-tracker-Q76KFISR.js → cost-tracker-JLSEY4ID.js} +2 -2
  154. package/dist/cli/chunks/{coverage-PT23ZOGU.js → coverage-4TH275AN.js} +3 -3
  155. package/dist/cli/chunks/cross-domain-router-AKHC7TFO.js +2 -0
  156. package/dist/cli/chunks/{cursor-installer-ZDS65WC6.js → cursor-installer-4SXSE5YT.js} +2 -2
  157. package/dist/cli/chunks/{daemon-ZRDBUK4Q.js → daemon-7T4RZQH6.js} +3 -3
  158. package/dist/cli/chunks/{daemon-M32BWOES.js → daemon-U6MP4P6S.js} +4 -4
  159. package/dist/cli/chunks/{dag-attention-scheduler-GUPZT7PR.js → dag-attention-scheduler-DT2V46XR.js} +2 -2
  160. package/dist/cli/chunks/{detect-PZNLC2CO.js → detect-WHSTB4QT.js} +2 -2
  161. package/dist/cli/chunks/{dist-node-QO5MMHVF.js → dist-node-4LC2RJXW.js} +2 -2
  162. package/dist/cli/chunks/{domain-handler-OH2YSZCT.js → domain-handler-A2LOOU7Y.js} +2 -2
  163. package/dist/cli/chunks/{domain-transfer-TVTK2YX5.js → domain-transfer-4RJTMB3Y.js} +2 -2
  164. package/dist/cli/chunks/dream-FPWIC7KF.js +2 -0
  165. package/dist/cli/chunks/{embed-and-insert-pattern-2ARE7NCX.js → embed-and-insert-pattern-PR3KTT24.js} +2 -2
  166. package/dist/cli/chunks/{eval-64RXRKM4.js → eval-2HRBMOOB.js} +2 -2
  167. package/dist/cli/chunks/{experience-capture-middleware-TH7JERGY.js → experience-capture-middleware-X46IYOSD.js} +3 -3
  168. package/dist/cli/chunks/{fast-paths-IAWNSJFU.js → fast-paths-LYYYU362.js} +2 -2
  169. package/dist/cli/chunks/{feature-flags-22FDDEFG.js → feature-flags-RNAMQPUN.js} +2 -2
  170. package/dist/cli/chunks/{feature-flags-TAKLIOWM.js → feature-flags-TKDXIHOH.js} +2 -2
  171. package/dist/cli/chunks/{file-discovery-QWEHC5VO.js → file-discovery-MKGGMDIW.js} +2 -2
  172. package/dist/cli/chunks/{fleet-5PQX4H2Q.js → fleet-OY4IBCZG.js} +3 -3
  173. package/dist/cli/chunks/{gnn-wrapper-RR5EYGCL.js → gnn-wrapper-G5OGHVAQ.js} +2 -2
  174. package/dist/cli/chunks/{heartbeat-handler-QOVPD6JV.js → heartbeat-handler-N7IUATSD.js} +4 -4
  175. package/dist/cli/chunks/heartbeat-scheduler-WHGMTRT7.js +2 -0
  176. package/dist/cli/chunks/hnsw-adapter-IA2M5KDH.js +2 -0
  177. package/dist/cli/chunks/hnsw-index-UBXTXXLQ.js +2 -0
  178. package/dist/cli/chunks/{hnsw-legacy-bridge-RRTRMCEL.js → hnsw-legacy-bridge-TMCMZDVF.js} +2 -2
  179. package/dist/cli/chunks/{better-sqlite3-XEIBI22V.js → hnswlib-node-NN6GB2YD.js} +2 -2
  180. package/dist/cli/chunks/{hooks-DTEIDS42.js → hooks-5QDXEZ25.js} +53 -53
  181. package/dist/cli/chunks/{hybrid-router-E36GZC7Q.js → hybrid-router-IY62NN7G.js} +2 -2
  182. package/dist/cli/chunks/{hypergraph-engine-7VTF3N6A.js → hypergraph-engine-QQYKS2F3.js} +2 -2
  183. package/dist/cli/chunks/{hypergraph-handler-CTUGX3DL.js → hypergraph-handler-YXFNXMRF.js} +3 -3
  184. package/dist/cli/chunks/impact-analyzer-6PVCOS33.js +2 -0
  185. package/dist/cli/chunks/{init-handler-HRSUGKSE.js → init-handler-SFFSDGEF.js} +6 -6
  186. package/dist/cli/chunks/init-wizard-XHP5C6RD.js +2 -0
  187. package/dist/cli/chunks/kernel-YM5PY5SS.js +2 -0
  188. package/dist/cli/chunks/{kilocode-installer-UGB5UY5B.js → kilocode-installer-QFRYXQYY.js} +2 -2
  189. package/dist/cli/chunks/{kiro-installer-7SAM5O2F.js → kiro-installer-7L2EYEOR.js} +2 -2
  190. package/dist/cli/chunks/knowledge-graph-LTUOUHO7.js +2 -0
  191. package/dist/cli/chunks/{learning-GBRPEBXN.js → learning-7TVVL5UH.js} +3 -3
  192. package/dist/cli/chunks/{llm-router-YP2RW2QC.js → llm-router-S3HHVPH4.js} +4 -4
  193. package/dist/cli/chunks/{load-3TRJPJBJ.js → load-Y46RO7BF.js} +2 -2
  194. package/dist/cli/chunks/load-test-CYCAQI3F.js +2 -0
  195. package/dist/cli/chunks/{mcp-U7ZYZTEU.js → mcp-PYNP2S5O.js} +2 -2
  196. package/dist/cli/chunks/{memory-CLBPDAAE.js → memory-DAVXW5OP.js} +5 -5
  197. package/dist/cli/chunks/memory-backend-RW2OPAJU.js +2 -0
  198. package/dist/cli/chunks/{memory-handlers-JEOU6AOR.js → memory-handlers-6COHVON7.js} +2 -2
  199. package/dist/cli/chunks/{multi-model-executor-MPPD63KI.js → multi-model-executor-7ECJRCM3.js} +2 -2
  200. package/dist/cli/chunks/{opencode-installer-DIMXI5PK.js → opencode-installer-H7QOONUC.js} +2 -2
  201. package/dist/cli/chunks/{orchestrator-YKOSNTFS.js → orchestrator-TSJ2F3MG.js} +5 -5
  202. package/dist/cli/chunks/{pipeline-SDCM3CNA.js → pipeline-SXR4MRY7.js} +2 -2
  203. package/dist/cli/chunks/{platform-7UH4BXN7.js → platform-7NOS56VD.js} +2 -2
  204. package/dist/cli/chunks/{plugin-KIVAXJ3P.js → plugin-VLSWBGJN.js} +2 -2
  205. package/dist/cli/chunks/{prime-radiant-advanced-wasm-PONLGWM6.js → prime-radiant-advanced-wasm-7ZHSOP7H.js} +2 -2
  206. package/dist/cli/chunks/protocol-executor-CREUYOBZ.js +2 -0
  207. package/dist/cli/chunks/{protocol-handler-6RYLLDOG.js → protocol-handler-LWNYDM4D.js} +2 -2
  208. package/dist/cli/chunks/{prove-PDFFRQQW.js → prove-JYFW3OBB.js} +2 -2
  209. package/dist/cli/chunks/{provider-manager-I6R4EQGK.js → provider-manager-VPS4W7KG.js} +2 -2
  210. package/dist/cli/chunks/qe-reasoning-bank-J4DLHRJY.js +2 -0
  211. package/dist/cli/chunks/{quality-KQVKAGWL.js → quality-FCAOFXZ2.js} +2 -2
  212. package/dist/cli/chunks/queen-coordinator-MGLNSTPY.js +2 -0
  213. package/dist/cli/chunks/{real-embeddings-VQXMPAH6.js → real-embeddings-LE6YXNPZ.js} +2 -2
  214. package/dist/cli/chunks/{roocode-installer-RYPQ25JO.js → roocode-installer-ZVGJSAWD.js} +2 -2
  215. package/dist/cli/chunks/router-CXGPFUT2.js +2 -0
  216. package/dist/cli/chunks/routing-feedback-MZ73LFBP.js +2 -0
  217. package/dist/cli/chunks/{routing-handler-U4FEWPIN.js → routing-handler-AGDHK3A2.js} +2 -2
  218. package/dist/cli/chunks/{ruvector-commands-YID52EZ6.js → ruvector-commands-UGZINDCN.js} +2 -2
  219. package/dist/cli/chunks/{rvf-dual-writer-HABBORJW.js → rvf-dual-writer-PW7H6G4V.js} +2 -2
  220. package/dist/cli/chunks/{rvf-migration-adapter-JE5NWU3J.js → rvf-migration-adapter-ZKOTVCHJ.js} +2 -2
  221. package/dist/cli/chunks/{rvf-migration-coordinator-FBIFWTAD.js → rvf-migration-coordinator-SCBEMOP3.js} +2 -2
  222. package/dist/cli/chunks/rvf-native-adapter-T6JBPHTE.js +2 -0
  223. package/dist/cli/chunks/safe-db-DS4SKPYB.js +2 -0
  224. package/dist/cli/chunks/schedule-H2Q7XWAK.js +2 -0
  225. package/dist/cli/chunks/scheduler-PMZMKQIF.js +2 -0
  226. package/dist/cli/chunks/{security-22ERFMD6.js → security-H7QX46VA.js} +3 -3
  227. package/dist/cli/chunks/{shared-rvf-adapter-YU7XN6ND.js → shared-rvf-adapter-LWYHWJIA.js} +2 -2
  228. package/dist/cli/chunks/{shared-rvf-dual-writer-G5VIQHSN.js → shared-rvf-dual-writer-P2U424FB.js} +2 -2
  229. package/dist/cli/chunks/sqlite-persistence-ONKEAMTQ.js +2 -0
  230. package/dist/cli/chunks/{status-handler-5B3FP2DN.js → status-handler-UNX3RA3S.js} +2 -2
  231. package/dist/cli/chunks/{structural-health-6YSKVKQG.js → structural-health-65YV3M5E.js} +2 -2
  232. package/dist/cli/chunks/{sync-2YCW23XX.js → sync-B4O3NDJ6.js} +2 -2
  233. package/dist/cli/chunks/{sync-OFSJUYBU.js → sync-OZ7CHYYO.js} +2 -2
  234. package/dist/cli/chunks/{task-handler-6OIPFSXX.js → task-handler-NIG3USPG.js} +2 -2
  235. package/dist/cli/chunks/{task-handlers-6QY5Q5IH.js → task-handlers-Z2PI7BTO.js} +3 -3
  236. package/dist/cli/chunks/{test-VR6EP23Y.js → test-MNLYS3WS.js} +4 -4
  237. package/dist/cli/chunks/{test-scheduling-OI7N5QBA.js → test-scheduling-VCL6D6T7.js} +3 -3
  238. package/dist/cli/chunks/{token-bootstrap-HZES3TAA.js → token-bootstrap-DGMEU3W4.js} +2 -2
  239. package/dist/cli/chunks/{token-usage-2NSXSNS7.js → token-usage-IXTYAV5K.js} +2 -2
  240. package/dist/cli/chunks/{transformers-4U4PX5YQ.js → transformers-5CWLXT2M.js} +2 -2
  241. package/dist/cli/chunks/{tree-sitter-wasm-parser-NQ3JYKHC.js → tree-sitter-wasm-parser-W3FKJLJG.js} +2 -2
  242. package/dist/cli/chunks/{types-YGTXBQ4T.js → types-NVOCAZCQ.js} +2 -2
  243. package/dist/cli/chunks/unified-memory-PNHI6I3R.js +2 -0
  244. package/dist/cli/chunks/unified-memory-hnsw-CDV3UMBD.js +2 -0
  245. package/dist/cli/chunks/unified-persistence-FMCHCEZV.js +2 -0
  246. package/dist/cli/chunks/{upgrade-GS4EJOHW.js → upgrade-VJYD4U4X.js} +2 -2
  247. package/dist/cli/chunks/{validate-4X7OETYQ.js → validate-CAKTCZ3T.js} +2 -2
  248. package/dist/cli/chunks/{validate-swarm-RSVPLHZQ.js → validate-swarm-H24JHUTN.js} +2 -2
  249. package/dist/cli/chunks/{vibium-SN2J4QEA.js → vibium-247XN6V3.js} +2 -2
  250. package/dist/cli/chunks/visual-security-3WRJQDUY.js +2 -0
  251. package/dist/cli/chunks/{web-tree-sitter-ZO6DPXRC.js → web-tree-sitter-3DOMHLRH.js} +2 -2
  252. package/dist/cli/chunks/{windsurf-installer-RGSOOJSH.js → windsurf-installer-S2MOA5TQ.js} +2 -2
  253. package/dist/cli/chunks/witness-chain-5ZKCKNRJ.js +2 -0
  254. package/dist/cli/chunks/{witness-chain-7XBKRDAW.js → witness-chain-CKLVPFLG.js} +2 -2
  255. package/dist/cli/chunks/{workflow-H7KG5R6L.js → workflow-GU3IV2OD.js} +4 -4
  256. package/dist/cli/chunks/workflow-orchestrator-OBSFY7YK.js +2 -0
  257. package/dist/cli/chunks/{wrappers-3YCDNHDG.js → wrappers-74Y4EKW3.js} +2 -2
  258. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.d.ts +3 -3
  259. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +4 -3
  260. package/dist/cli/commands/hooks-handlers/routing-hooks.js +50 -12
  261. package/dist/cli/commands/hooks-handlers/task-hooks.js +30 -6
  262. package/dist/learning/agent-routing.d.ts +13 -1
  263. package/dist/learning/agent-routing.js +14 -1
  264. package/dist/learning/qe-reasoning-bank.js +4 -2
  265. package/dist/mcp/bundle.js +240 -240
  266. package/package.json +1 -1
  267. package/dist/cli/chunks/adapter-JUISYMI3.js +0 -2
  268. package/dist/cli/chunks/aqe-learning-engine-DEIUPULJ.js +0 -2
  269. package/dist/cli/chunks/base-7SMQWXHT.js +0 -2
  270. package/dist/cli/chunks/browser-workflow-4DGHRZLS.js +0 -2
  271. package/dist/cli/chunks/chunk-PHJK33IV.js +0 -2
  272. package/dist/cli/chunks/client-OSUT6W6W.js +0 -2
  273. package/dist/cli/chunks/cross-domain-router-X5EEGWMA.js +0 -2
  274. package/dist/cli/chunks/dream-CP4VOPNU.js +0 -2
  275. package/dist/cli/chunks/heartbeat-scheduler-MX7EHYU5.js +0 -2
  276. package/dist/cli/chunks/hnsw-adapter-B7FZYZGZ.js +0 -2
  277. package/dist/cli/chunks/hnsw-index-7OVB67MX.js +0 -2
  278. package/dist/cli/chunks/impact-analyzer-TG34YBHU.js +0 -2
  279. package/dist/cli/chunks/init-wizard-MS3A2X5C.js +0 -2
  280. package/dist/cli/chunks/kernel-J4IW4DA6.js +0 -2
  281. package/dist/cli/chunks/knowledge-graph-4LCYX5AN.js +0 -2
  282. package/dist/cli/chunks/load-test-TFBVT7V3.js +0 -2
  283. package/dist/cli/chunks/memory-backend-E7OCG27P.js +0 -2
  284. package/dist/cli/chunks/protocol-executor-MYFH7ZP4.js +0 -2
  285. package/dist/cli/chunks/qe-reasoning-bank-G46PVD2U.js +0 -2
  286. package/dist/cli/chunks/queen-coordinator-ZQRKBBUH.js +0 -2
  287. package/dist/cli/chunks/router-UBQULTOO.js +0 -2
  288. package/dist/cli/chunks/routing-feedback-3VBS3SYD.js +0 -2
  289. package/dist/cli/chunks/rvf-native-adapter-NDKSHCMG.js +0 -2
  290. package/dist/cli/chunks/safe-db-ZPGX4NYW.js +0 -2
  291. package/dist/cli/chunks/schedule-JZUKDE6O.js +0 -2
  292. package/dist/cli/chunks/scheduler-7YIQOOW3.js +0 -2
  293. package/dist/cli/chunks/sqlite-persistence-4STSI5SJ.js +0 -2
  294. package/dist/cli/chunks/unified-memory-R72C7IBY.js +0 -2
  295. package/dist/cli/chunks/unified-memory-hnsw-A4LOFKDQ.js +0 -2
  296. package/dist/cli/chunks/unified-persistence-MYD2R4LE.js +0 -2
  297. package/dist/cli/chunks/visual-security-CUKQ5N37.js +0 -2
  298. package/dist/cli/chunks/witness-chain-S7ADS6TA.js +0 -2
  299. package/dist/cli/chunks/workflow-orchestrator-3GIDXU43.js +0 -2
@@ -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.35");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.36");process.exit(0)}
2
2
  import{randomUUID as v}from"crypto";var m={"claude-opus-4-7":{input:5,output:25,provider:"claude"},"claude-sonnet-4-6":{input:3,output:15,provider:"claude"},"claude-haiku-4-5-20251001":{input:1,output:5,provider:"claude"},"claude-opus-4-5-20251101":{input:15,output:75,provider:"claude"},"claude-sonnet-4-20250514":{input:3,output:15,provider:"claude"},"claude-3-5-haiku-20241022":{input:1,output:5,provider:"claude"},"claude-3-opus-20240229":{input:15,output:75,provider:"claude"},"claude-3-sonnet-20240229":{input:3,output:15,provider:"claude"},"claude-3-haiku-20240307":{input:.25,output:1.25,provider:"claude"},"gpt-4o":{input:5,output:15,provider:"openai"},"gpt-4o-mini":{input:.15,output:.6,provider:"openai"},"gpt-4-turbo":{input:10,output:30,provider:"openai"},"gpt-4":{input:30,output:60,provider:"openai"},"gpt-3.5-turbo":{input:.5,output:1.5,provider:"openai"},llama3:{input:0,output:0,provider:"ollama"},"llama3.1":{input:0,output:0,provider:"ollama"},codellama:{input:0,output:0,provider:"ollama"},mistral:{input:0,output:0,provider:"ollama"},mixtral:{input:0,output:0,provider:"ollama"},phi3:{input:0,output:0,provider:"ollama"},qwen2:{input:0,output:0,provider:"ollama"},"anthropic/claude-3.5-sonnet":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3.5-sonnet:beta":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3-opus":{input:15,output:75,provider:"openrouter"},"anthropic/claude-3-sonnet":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3-haiku":{input:.25,output:1.25,provider:"openrouter"},"openai/gpt-4o":{input:5,output:15,provider:"openrouter"},"openai/gpt-4o-mini":{input:.15,output:.6,provider:"openrouter"},"openai/gpt-4-turbo":{input:10,output:30,provider:"openrouter"},"openai/gpt-3.5-turbo":{input:.5,output:1.5,provider:"openrouter"},"google/gemini-pro":{input:.125,output:.375,provider:"openrouter"},"google/gemini-pro-1.5":{input:3.5,output:10.5,provider:"openrouter"},"meta-llama/llama-3.1-70b-instruct":{input:.59,output:.79,provider:"openrouter"},"meta-llama/llama-3.1-8b-instruct":{input:.06,output:.06,provider:"openrouter"},"mistralai/mistral-large":{input:2,output:6,provider:"openrouter"},"mistralai/mixtral-8x7b-instruct":{input:.24,output:.24,provider:"openrouter"},"mistralai/mistral-7b-instruct":{input:.06,output:.06,provider:"openrouter"},"anthropic.claude-opus-4-5-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-opus-4-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-sonnet-4-5-v2:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-sonnet-4-v1:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-3-5-haiku-v1:0":{input:1,output:5,provider:"bedrock"},"anthropic.claude-3-opus-20240229-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-3-sonnet-20240229-v1:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-3-haiku-20240307-v1:0":{input:.25,output:1.25,provider:"bedrock"},"anthropic.claude-3-5-sonnet-20241022-v2:0":{input:3,output:15,provider:"bedrock"},"azure/gpt-4o":{input:5,output:15,provider:"azure-openai"},"azure/gpt-4o-mini":{input:.15,output:.6,provider:"azure-openai"},"azure/gpt-4-turbo":{input:10,output:30,provider:"azure-openai"},"azure/gpt-4":{input:30,output:60,provider:"azure-openai"},"azure/gpt-35-turbo":{input:.5,output:1.5,provider:"azure-openai"},"azure/text-embedding-ada-002":{input:.1,output:0,provider:"azure-openai"},"azure/text-embedding-3-small":{input:.02,output:0,provider:"azure-openai"},"azure/text-embedding-3-large":{input:.13,output:0,provider:"azure-openai"},"gemini-pro":{input:.5,output:1.5,provider:"gemini"},"gemini-1.0-pro":{input:.5,output:1.5,provider:"gemini"},"gemini-1.5-pro":{input:3.5,output:10.5,provider:"gemini"},"gemini-1.5-pro-latest":{input:3.5,output:10.5,provider:"gemini"},"gemini-1.5-flash":{input:.075,output:.3,provider:"gemini"},"gemini-1.5-flash-latest":{input:.075,output:.3,provider:"gemini"},"gemini-2.0-flash-exp":{input:.075,output:.3,provider:"gemini"},"gemini-ultra":{input:7,output:21,provider:"gemini"},"gemini-1.0-ultra":{input:7,output:21,provider:"gemini"},"text-embedding-004":{input:.025,output:0,provider:"gemini"}},d=class c{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(t=1e4){this.maxRecords=t}static calculateCost(t,r){let e=m[t];if(!e)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let i=r.promptTokens/1e6*e.input,o=r.completionTokens/1e6*e.output;return{inputCost:i,outputCost:o,totalCost:i+o,currency:"USD"}}static getCostPerToken(t){let r=m[t];return r?{input:r.input/1e6,output:r.output/1e6}:{input:0,output:0}}recordUsage(t,r,e,i,o){let n=c.calculateCost(r,e),p={timestamp:new Date,provider:t,model:r,usage:e,cost:n,requestId:i,metadata:o};return this.records.push(p),this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords)),this.checkAlerts(),n}getSummary(t){let r=new Date,e=this.getPeriodStart(r,t),i=r,o=this.records.filter(s=>s.timestamp>=e&&s.timestamp<=i),n={claude:0,openai:0,ollama:0,openrouter:0,bedrock:0,"azure-openai":0,gemini:0},p={},u=0,l=0;for(let s of o)u+=s.cost.totalCost,l+=s.usage.totalTokens,n[s.provider]+=s.cost.totalCost,p[s.model]=(p[s.model]||0)+s.cost.totalCost;return{period:t,periodStart:e,periodEnd:i,totalCost:u,byProvider:n,byModel:p,totalTokens:l,totalRequests:o.length}}getCurrentCost(t){return this.getSummary(t).totalCost}getTotalTokens(t){return this.getSummary(t).totalTokens}getUsageByProvider(t,r="all"){let e=this.getPeriodStart(new Date,r),i=this.records.filter(u=>u.provider===t&&u.timestamp>=e),o={},n=0,p=0;for(let u of i)n+=u.cost.totalCost,p+=u.usage.totalTokens,o[u.model]||(o[u.model]={cost:0,tokens:0,requests:0}),o[u.model].cost+=u.cost.totalCost,o[u.model].tokens+=u.usage.totalTokens,o[u.model].requests+=1;return{totalCost:n,totalTokens:p,totalRequests:i.length,models:o}}addAlert(t,r,e){let i=`alert-${Date.now()}-${v().slice(0,12)}`;return this.alerts.push({threshold:t,period:r,onThreshold:e,active:!0}),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),i}removeAlert(t){return t>=0&&t<this.alerts.length?(this.alerts.splice(t,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getRecords(){return[...this.records]}importRecords(t){for(let r of t)r.timestamp=new Date(r.timestamp),this.records.push(r);this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}clear(){this.records=[]}getRecentRequests(t=10){return this.records.slice(-t)}estimateCost(t,r,e){return c.calculateCost(t,{promptTokens:r,completionTokens:e,totalTokens:r+e})}wouldExceedLimit(t,r,e,i,o){let n=this.getCurrentCost(o),p=this.estimateCost(t,r,e);return n+p.totalCost>i}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}getPeriodStart(t,r){let e=new Date(t);switch(r){case"minute":e.setSeconds(0,0),e.setMinutes(e.getMinutes()-1);break;case"hour":e.setMinutes(0,0,0),e.setHours(e.getHours()-1);break;case"day":e.setHours(0,0,0,0);break;case"week":e.setHours(0,0,0,0),e.setDate(e.getDate()-7);break;case"month":e.setHours(0,0,0,0),e.setDate(1);break;case"all":return new Date(0)}return e}checkAlerts(){for(let t of this.alerts){if(!t.active)continue;let r=this.getSummary(t.period);if(r.totalCost>=t.threshold){t.active=!1;try{t.onThreshold(r)}catch(e){console.error("Cost alert callback error:",e)}}}}},a;function h(){return a||(a=new d),a}function b(){a&&(a.dispose(),a=void 0)}export{m as a,d as b,h as c,b 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.35");process.exit(0)}
2
- import{h as s,k as o,m as c,o as m}from"./chunk-IXOGBA7C.js";import{a,c as d}from"./chunk-DEJW6GYF.js";import{a as r,e as l}from"./chunk-UJTI5MRE.js";d();m();l();var u={dbPath:s.dbPath,walMode:!0,mmapSize:r.MMAP_SIZE_BYTES,cacheSize:r.CACHE_SIZE_KB,busyTimeout:r.BUSY_TIMEOUT_MS},n=class e{static instance=null;static instancePromise=null;unifiedMemory=null;config;initialized=!1;initPromise=null;constructor(i){this.config={...u,...i}}static getInstance(i){return e.instance||(e.instance=new e(i)),e.instance}static async getInstanceAsync(i){return e.instance?.initialized?e.instance:(e.instancePromise||(e.instancePromise=(async()=>{let t=e.getInstance(i);return await t.initialize(),t})()),e.instancePromise)}static resetInstance(){e.instance&&(e.instance.close(),e.instance=null),e.instancePromise=null,c()}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{let i={dbPath:this.config.dbPath,walMode:this.config.walMode,busyTimeout:this.config.busyTimeout,mmapSize:this.config.mmapSize,cacheSize:this.config.cacheSize};this.unifiedMemory=o(i),await this.unifiedMemory.initialize(),this.initialized=!0,console.log(`[UnifiedPersistence] Initialized via UnifiedMemoryManager: ${this.config.dbPath}`)}catch(i){throw this.initPromise=null,new Error(`Failed to initialize UnifiedPersistenceManager: ${a(i)}`)}}getDatabase(){if(!this.unifiedMemory||!this.initialized)throw new Error("UnifiedPersistenceManager not initialized");return this.unifiedMemory.getDatabase()}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(i,t){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.prepare(i,t)}transaction(i){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.transaction(i)}getStats(){if(!this.unifiedMemory)throw new Error("Database not initialized");let i=this.unifiedMemory.getStats();return{tables:i.tables,fileSize:i.fileSize,walSize:i.walSize}}vacuum(){this.getDatabase().exec("VACUUM")}checkpoint(){this.getDatabase().pragma("wal_checkpoint(TRUNCATE)")}close(){this.initialized=!1,console.log("[UnifiedPersistence] Facade closed")}};function g(e){return n.getInstance(e)}async function U(e){let i=g(e);return await i.initialize(),i}function z(){n.resetInstance()}var f=!1;function h(){if(f)return;f=!0;let e=()=>{try{let i=n.instance;i&&i.close()}catch(i){console.debug("[UnifiedPersistence] Cleanup error:",i instanceof Error?i.message:i)}};process.on("beforeExit",e),process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)})}h();export{u as a,n as b,g as c,U as d,z as e};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.36");process.exit(0)}
2
+ import{h as s,k as o,m as c,o as m}from"./chunk-5MSZREOD.js";import{a,c as d}from"./chunk-O4C3JEOR.js";import{a as r,e as l}from"./chunk-IF4ZZ2HD.js";d();m();l();var u={dbPath:s.dbPath,walMode:!0,mmapSize:r.MMAP_SIZE_BYTES,cacheSize:r.CACHE_SIZE_KB,busyTimeout:r.BUSY_TIMEOUT_MS},n=class e{static instance=null;static instancePromise=null;unifiedMemory=null;config;initialized=!1;initPromise=null;constructor(i){this.config={...u,...i}}static getInstance(i){return e.instance||(e.instance=new e(i)),e.instance}static async getInstanceAsync(i){return e.instance?.initialized?e.instance:(e.instancePromise||(e.instancePromise=(async()=>{let t=e.getInstance(i);return await t.initialize(),t})()),e.instancePromise)}static resetInstance(){e.instance&&(e.instance.close(),e.instance=null),e.instancePromise=null,c()}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{let i={dbPath:this.config.dbPath,walMode:this.config.walMode,busyTimeout:this.config.busyTimeout,mmapSize:this.config.mmapSize,cacheSize:this.config.cacheSize};this.unifiedMemory=o(i),await this.unifiedMemory.initialize(),this.initialized=!0,console.log(`[UnifiedPersistence] Initialized via UnifiedMemoryManager: ${this.config.dbPath}`)}catch(i){throw this.initPromise=null,new Error(`Failed to initialize UnifiedPersistenceManager: ${a(i)}`)}}getDatabase(){if(!this.unifiedMemory||!this.initialized)throw new Error("UnifiedPersistenceManager not initialized");return this.unifiedMemory.getDatabase()}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(i,t){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.prepare(i,t)}transaction(i){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.transaction(i)}getStats(){if(!this.unifiedMemory)throw new Error("Database not initialized");let i=this.unifiedMemory.getStats();return{tables:i.tables,fileSize:i.fileSize,walSize:i.walSize}}vacuum(){this.getDatabase().exec("VACUUM")}checkpoint(){this.getDatabase().pragma("wal_checkpoint(TRUNCATE)")}close(){this.initialized=!1,console.log("[UnifiedPersistence] Facade closed")}};function g(e){return n.getInstance(e)}async function U(e){let i=g(e);return await i.initialize(),i}function z(){n.resetInstance()}var f=!1;function h(){if(f)return;f=!0;let e=()=>{try{let i=n.instance;i&&i.close()}catch(i){console.debug("[UnifiedPersistence] Cleanup error:",i instanceof Error?i.message:i)}};process.on("beforeExit",e),process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)})}h();export{u as a,n as b,g as c,U as d,z as e};
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.35");process.exit(0)}
2
- import{k as f,o as P}from"./chunk-IXOGBA7C.js";import{b as h,d as U}from"./chunk-RZDMSTAQ.js";import{d as p,e as y}from"./chunk-BTPDHALG.js";import{a as T,c as C}from"./chunk-DEJW6GYF.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.36");process.exit(0)}
2
+ import{k as f,o as P}from"./chunk-5MSZREOD.js";import{b as h,d as U}from"./chunk-HOZNVDFF.js";import{d as p,e as y}from"./chunk-VENEJ3UI.js";import{a as T,c as C}from"./chunk-O4C3JEOR.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
3
3
  ${c.join(" | ")}`}var E=new m;function $(u){return`$${u.toFixed(2)}`}export{z as a,E as b,$ as c};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.35");process.exit(0)}
2
- import{b as d,d as c}from"./chunk-RZDMSTAQ.js";import{a as l,c as g}from"./chunk-DEJW6GYF.js";g();c();import{existsSync as y,readFileSync as p}from"node:fs";import{join as o,dirname as u}from"node:path";import{fileURLToPath as m}from"node:url";var i=class extends Error{constructor(t,n,r){super(t);this.code=n;this.cause=r;this.name="PatternLoaderError"}code;cause},s=class a{static instance=null;config;patterns;isLoading=!1;constructor(e={}){this.config={basePath:e.basePath??this.getDefaultBasePath(),throwOnMissing:e.throwOnMissing??!1,validatePatterns:e.validatePatterns??!0},this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]}}static getInstance(e){return a.instance||(a.instance=new a(e)),a.instance}static resetInstance(){a.instance=null}getDefaultBasePath(){try{let e=import.meta.url,t=m(e),n=u(t),r=o(n,"..","..","..");return o(r,"assets","patterns")}catch{return o(process.cwd(),"assets","patterns")}}async loadPatterns(){if(!this.isLoading){this.isLoading=!0,this.patterns.errors=[];try{this.patterns.index=this.loadJsonFile("index.json");let[e,t,n,r]=await Promise.all([Promise.resolve(this.loadJsonFile("adr-051-booster-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-router-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-embedding-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-reasoning-patterns.json"))]);this.patterns.booster=e,this.patterns.router=t,this.patterns.embedding=n,this.patterns.reasoning=r,this.patterns.loadedAt=new Date,this.config.validatePatterns&&this.validateLoadedPatterns()}finally{this.isLoading=!1}}}loadJsonFile(e){let t=o(this.config.basePath,e);try{if(!y(t)){let r=`Pattern file not found: ${t}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"FILE_NOT_FOUND");return null}let n=p(t,"utf-8");return d(n)}catch(n){if(n instanceof i)throw n;let r=`Failed to load pattern file ${e}: ${l(n)}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"PARSE_ERROR",n instanceof Error?n:void 0);return null}}validateLoadedPatterns(){this.patterns.booster&&(Array.isArray(this.patterns.booster.patterns)||this.patterns.errors.push("Booster patterns file missing patterns array")),this.patterns.router&&(Array.isArray(this.patterns.router.patterns)||this.patterns.errors.push("Router patterns file missing patterns array")),this.patterns.embedding&&(Array.isArray(this.patterns.embedding.patterns)||this.patterns.errors.push("Embedding patterns file missing patterns array")),this.patterns.reasoning&&(Array.isArray(this.patterns.reasoning.patterns)||this.patterns.errors.push("Reasoning patterns file missing patterns array"))}async ensureLoaded(){this.patterns.loadedAt||await this.loadPatterns()}async getIndex(){return await this.ensureLoaded(),this.patterns.index}async getBoosterPatterns(){return await this.ensureLoaded(),this.patterns.booster}async getRouterPatterns(){return await this.ensureLoaded(),this.patterns.router}async getEmbeddingPatterns(){return await this.ensureLoaded(),this.patterns.embedding}async getReasoningPatterns(){return await this.ensureLoaded(),this.patterns.reasoning}async getBoosterPatternByKey(e){let t=await this.getBoosterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getRouterPatternByKey(e){let t=await this.getRouterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEmbeddingPatternByKey(e){let t=await this.getEmbeddingPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getReasoningPatternByKey(e){let t=await this.getReasoningPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEligibleBoosterTransforms(){let e=await this.getBoosterPatternByKey("booster-transform-eligibility");return e?e.eligibility_criteria.simple_transforms:[]}async getTierHierarchy(){let e=await this.getRouterPatternByKey("router-5tier-complexity");return e?e.tier_hierarchy:null}async getQualityGateThresholds(){let e=await this.getReasoningPatternByKey("reasoning-pattern-quality-gates");return e?e.gate_thresholds:null}isLoaded(){return this.patterns.loadedAt!==null}getLoadedAt(){return this.patterns.loadedAt}getErrors(){return[...this.patterns.errors]}async getStatistics(){let e=await this.getIndex();return e?e.pattern_statistics:null}async reload(){this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]},await this.loadPatterns()}async getAllPatterns(){return await this.ensureLoaded(),{...this.patterns}}};function x(){return s.getInstance()}export{x 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.36");process.exit(0)}
2
+ import{b as d,d as c}from"./chunk-HOZNVDFF.js";import{a as l,c as g}from"./chunk-O4C3JEOR.js";g();c();import{existsSync as y,readFileSync as p}from"node:fs";import{join as o,dirname as u}from"node:path";import{fileURLToPath as m}from"node:url";var i=class extends Error{constructor(t,n,r){super(t);this.code=n;this.cause=r;this.name="PatternLoaderError"}code;cause},s=class a{static instance=null;config;patterns;isLoading=!1;constructor(e={}){this.config={basePath:e.basePath??this.getDefaultBasePath(),throwOnMissing:e.throwOnMissing??!1,validatePatterns:e.validatePatterns??!0},this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]}}static getInstance(e){return a.instance||(a.instance=new a(e)),a.instance}static resetInstance(){a.instance=null}getDefaultBasePath(){try{let e=import.meta.url,t=m(e),n=u(t),r=o(n,"..","..","..");return o(r,"assets","patterns")}catch{return o(process.cwd(),"assets","patterns")}}async loadPatterns(){if(!this.isLoading){this.isLoading=!0,this.patterns.errors=[];try{this.patterns.index=this.loadJsonFile("index.json");let[e,t,n,r]=await Promise.all([Promise.resolve(this.loadJsonFile("adr-051-booster-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-router-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-embedding-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-reasoning-patterns.json"))]);this.patterns.booster=e,this.patterns.router=t,this.patterns.embedding=n,this.patterns.reasoning=r,this.patterns.loadedAt=new Date,this.config.validatePatterns&&this.validateLoadedPatterns()}finally{this.isLoading=!1}}}loadJsonFile(e){let t=o(this.config.basePath,e);try{if(!y(t)){let r=`Pattern file not found: ${t}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"FILE_NOT_FOUND");return null}let n=p(t,"utf-8");return d(n)}catch(n){if(n instanceof i)throw n;let r=`Failed to load pattern file ${e}: ${l(n)}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"PARSE_ERROR",n instanceof Error?n:void 0);return null}}validateLoadedPatterns(){this.patterns.booster&&(Array.isArray(this.patterns.booster.patterns)||this.patterns.errors.push("Booster patterns file missing patterns array")),this.patterns.router&&(Array.isArray(this.patterns.router.patterns)||this.patterns.errors.push("Router patterns file missing patterns array")),this.patterns.embedding&&(Array.isArray(this.patterns.embedding.patterns)||this.patterns.errors.push("Embedding patterns file missing patterns array")),this.patterns.reasoning&&(Array.isArray(this.patterns.reasoning.patterns)||this.patterns.errors.push("Reasoning patterns file missing patterns array"))}async ensureLoaded(){this.patterns.loadedAt||await this.loadPatterns()}async getIndex(){return await this.ensureLoaded(),this.patterns.index}async getBoosterPatterns(){return await this.ensureLoaded(),this.patterns.booster}async getRouterPatterns(){return await this.ensureLoaded(),this.patterns.router}async getEmbeddingPatterns(){return await this.ensureLoaded(),this.patterns.embedding}async getReasoningPatterns(){return await this.ensureLoaded(),this.patterns.reasoning}async getBoosterPatternByKey(e){let t=await this.getBoosterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getRouterPatternByKey(e){let t=await this.getRouterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEmbeddingPatternByKey(e){let t=await this.getEmbeddingPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getReasoningPatternByKey(e){let t=await this.getReasoningPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEligibleBoosterTransforms(){let e=await this.getBoosterPatternByKey("booster-transform-eligibility");return e?e.eligibility_criteria.simple_transforms:[]}async getTierHierarchy(){let e=await this.getRouterPatternByKey("router-5tier-complexity");return e?e.tier_hierarchy:null}async getQualityGateThresholds(){let e=await this.getReasoningPatternByKey("reasoning-pattern-quality-gates");return e?e.gate_thresholds:null}isLoaded(){return this.patterns.loadedAt!==null}getLoadedAt(){return this.patterns.loadedAt}getErrors(){return[...this.patterns.errors]}async getStatistics(){let e=await this.getIndex();return e?e.pattern_statistics:null}async reload(){this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]},await this.loadPatterns()}async getAllPatterns(){return await this.ensureLoaded(),{...this.patterns}}};function x(){return s.getInstance()}export{x 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.35");process.exit(0)}
2
- import{k as p,o as N}from"./chunk-IXOGBA7C.js";N();import{createHash as y}from"crypto";var g="0".repeat(64);function m(s){return y("sha256").update(s,"utf-8").digest("hex")}function R(s){try{return y("shake256",{outputLength:32}).update(s,"utf-8").digest("hex")}catch{return m(s)}}function _(s,t){return s==="shake256"?R(t):m(t)}function f(s){return JSON.stringify({id:s.id,prev_hash:s.prev_hash,action_hash:s.action_hash,action_type:s.action_type,action_data:s.action_data,timestamp:s.timestamp,actor:s.actor})}var d=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}externalDb;db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=p();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.36");process.exit(0)}
2
+ import{k as p,o as N}from"./chunk-5MSZREOD.js";N();import{createHash as y}from"crypto";var g="0".repeat(64);function m(s){return y("sha256").update(s,"utf-8").digest("hex")}function R(s){try{return y("shake256",{outputLength:32}).update(s,"utf-8").digest("hex")}catch{return m(s)}}function _(s,t){return s==="shake256"?R(t):m(t)}function f(s){return JSON.stringify({id:s.id,prev_hash:s.prev_hash,action_hash:s.action_hash,action_type:s.action_type,action_data:s.action_data,timestamp:s.timestamp,actor:s.actor})}var d=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}externalDb;db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=p();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
3
3
  CREATE TABLE IF NOT EXISTS witness_chain (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  prev_hash TEXT NOT NULL, action_hash TEXT NOT NULL, action_type TEXT NOT NULL,
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.35");process.exit(0)}
2
- import{d as m}from"./chunk-3BDZSWCA.js";import{d as T}from"./chunk-HMIRBSTI.js";T();function p(t,r,o){let e=0,n=t.length;for(;e<n;){let i=e+n>>>1;o(t[i],r)<=0?e=i+1:n=i}return e}function a(t,r,o){let e=p(t,r,o);return t.splice(e,0,r),e}function s(){return(t,r)=>t.createdAt.getTime()-r.createdAt.getTime()}m();export{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.36");process.exit(0)}
2
+ import{d as m}from"./chunk-3CIQ6CQ4.js";import{d as T}from"./chunk-KI6RXKP4.js";T();function p(t,r,o){let e=0,n=t.length;for(;e<n;){let i=e+n>>>1;o(t[i],r)<=0?e=i+1:n=i}return e}function a(t,r,o){let e=p(t,r,o);return t.splice(e,0,r),e}function s(){return(t,r)=>t.createdAt.getTime()-r.createdAt.getTime()}m();export{a,s as b};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.35");process.exit(0)}
2
- import{a as W}from"./chunk-UDKBQAAH.js";import{c as V,d as q}from"./chunk-A5LZVQQL.js";import{c as M}from"./chunk-PK3NAZQI.js";import{b as D,d as $}from"./chunk-RZDMSTAQ.js";import{a as H}from"./chunk-PHJK33IV.js";import{c as N}from"./chunk-BTPDHALG.js";import{a as E,c as G}from"./chunk-DEJW6GYF.js";import{i as y}from"./chunk-E7N6CRFV.js";import{a as R,b as U,d as Z}from"./chunk-3BDZSWCA.js";var B={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};$();G();var A=class{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...B,...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.36");process.exit(0)}
2
+ import{a as W}from"./chunk-F57OUXHJ.js";import{c as V,d as q}from"./chunk-P4VQTIJE.js";import{c as M}from"./chunk-A3TOJ4KN.js";import{b as D,d as $}from"./chunk-HOZNVDFF.js";import{a as H}from"./chunk-ZYPSXPQ5.js";import{c as N}from"./chunk-VENEJ3UI.js";import{a as E,c as G}from"./chunk-O4C3JEOR.js";import{i as y}from"./chunk-NKA3X6VT.js";import{a as R,b as U,d as Z}from"./chunk-3CIQ6CQ4.js";var B={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};$();G();var A=class{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...B,...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-UDKBQAAH.js";import{c as V,d as q}from"./chunk-A5LZVQ
59
59
  ORDER BY weight DESC
60
60
  LIMIT -1 OFFSET ?
61
61
  )
62
- `).run(s,e);r+=c.changes}return r})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,r=t.get().count,a={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)a[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:r,byType:a,avgEdgesPerNode:i>0?r/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?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 ee(d){return new A(d)}Z();function te(d,e){if(e<0||e>=d.length)return d[0]??0;let t=0,n=d.length-1;for(;t<n;){let i=t+n>>1;if(d[i]<d[t]){let s=d[t];d[t]=d[i],d[i]=s}if(d[n]<d[t]){let s=d[t];d[t]=d[n],d[n]=s}if(d[i]<d[n]){let s=d[i];d[i]=d[n],d[n]=s}let r=d[n],a=t;for(let s=t;s<n;s++)if(d[s]<=r){let c=d[a];d[a]=d[s],d[s]=c,a++}let o=d[a];if(d[a]=d[n],d[n]=o,a===e)return d[a];a<e?t=a+1:n=a-1}return d[t]}var P=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},w=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(p=>this.graph.getConcept(p)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let p of i)this.graph.setActivation(p,t),this.recordActivation(p,t);let r=0,a=t,o=0,s=0;for(;r<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let p=await this.spreadIteration(),l=this.graph.getActiveNodes(this.config.threshold);for(let u of l)u.activationLevel>a&&(a=u.activationLevel);if(l.length===o&&p===0){if(s++,s>=3)break}else s=0;o=l.length,r++}let c=this.graph.getActiveNodes(this.config.threshold).map(p=>({nodeId:p.id,activation:p.activationLevel})).sort((p,l)=>l.activation-p.activation),h=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:r,nodesActivated:c.length,peakActivation:a,activatedNodes:c,novelAssociations:h.map(p=>({source:p.source.id,target:p.target.id,strength:p.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,r=0,a=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let p=U(0,o.length),l=o[p];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>r&&(r=f.peakActivation);for(let b of f.activatedNodes)a.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),h=Array.from(a).map(p=>{let l=this.graph.getConcept(p);return{nodeId:p,activation:l?.activationLevel??0}}).filter(p=>p.activation>0).sort((p,l)=>l.activation-p.activation);return this.trimHistory(),{iterations:i,nodesActivated:h.length,peakActivation:r,activatedNodes:h,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((a,o)=>o.activationLevel-a.activationLevel).slice(0,i));let r=[];for(let a=0;a<n.length;a++)for(let o=a+1;o<n.length;o++){let s=n[a],c=n[o],h=Math.sqrt(s.activationLevel*c.activationLevel),p=this.graph.getEdge(s.id,c.id),l=this.graph.getEdge(c.id,s.id),u=p!==void 0||l!==void 0,m=p?.weight??l?.weight??0,v=!u||m<.3;h>.3&&(r.push({source:s,target:c,coActivation:h,isNovel:v}),this.trackCoActivation(s.id,c.id))}return r.sort((a,o)=>a.isNovel!==o.isNovel?a.isNovel?-1:1:o.coActivation-a.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=P)return;let e=Math.floor(P*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=te(n,t-1),r=[];for(let[a,o]of this.coActivationCounts){if(r.length>=t)break;o<=i&&r.push(a)}for(let a of r)this.coActivationCounts.delete(a)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let r=this.graph.getEdges(i.id);for(let a of r){let o=this.graph.getConcept(a.target);if(!o)continue;let s=i.activationLevel*a.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,h=Math.min(1,c+s);n.push({nodeId:a.target,newActivation:h})}}}for(let i of n){let r=this.graph.getConcept(i.nodeId);r&&i.newActivation>r.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(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(":"),r=t.get(i);(!r||n.strength>r.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ne}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 r=await this.detectPatternMerges(i);for(let c of r)c.cycleId=e,n.push(c);let a=await this.detectNovelAssociations(t.novelAssociations);for(let c of a)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,h)=>h.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let a=n[i],o=n[r],s=this.graph.getEdge(a.id,o.id),c=this.graph.getEdge(o.id,a.id),h=Math.max(s?.weight??0,c?.weight??0),p=this.calculateContentSimilarity(a.content,o.content),l=Math.sqrt(a.activationLevel*o.activationLevel),u=h*.4+p*.3+l*.3;if(u>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[a.id,o.id]}),v=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[a.id,o.id],edgeWeight:h,contentSimilarity:p,coActivation:l});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[a.id,o.id],description:this.generatePatternMergeDescription(a,o,u),noveltyScore:m,confidenceScore:v,actionable:v>=this.config.minConfidence,applied:!1,suggestedAction:v>=this.config.minConfidence?`Merge "${this.truncate(a.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),r=this.graph.getConcept(n.target);if(!i||!r)continue;let a=this.graph.getEdge(n.source,n.target);if(a&&a.weight>.5)continue;let o=i.conceptType!==r.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,r,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(r.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},r=i.successRate,a=i.executionCount,o=i.confidence,s=r!==void 0&&r<.7,c=a!==void 0&&a>10,h=o!==void 0&&o<.6;if(s||c&&h){let p=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,r,a),noveltyScore:p,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 r=i.conceptType??"pattern";n[r]||(n[r]=[]),n[r].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(r=>r.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ne().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),r=new Set(n),a=new Set(i),o=n.filter(c=>a.has(c)),s=r.size+a.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let r=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${r}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};$();G();H();import{existsSync as ie,unlinkSync as re}from"fs";var T={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},C=class{constructor(e,t=T){this.db=e;this.thresholds=t}db;thresholds;activeBranches=new Map;listeners=[];rvfAdapter;useRvfFork=!1;_witnessChain=null;set witnessChain(e){this._witnessChain=e}setRvfAdapter(e,t=!0){this.rvfAdapter=e,this.useRvfFork=t,import("./feature-flags-TAKLIOWM.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let p=-r/n.patternCount;p>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(p*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let p=o/n.highConfidenceCount;p>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(p*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let p=this.rvfAdapter.dimension?.()??384,l=new Float32Array(p);for(let m=0;m<p;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 h=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:h,patternCountDelta:r,avgConfidenceDelta:a,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&ie(n)&&re(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}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},_=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();try{this.db.pragma("busy_timeout = 60000")}catch{}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(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),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 r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new z(this.graph);await a.loadIntoMemory(30);let s=await new w(a,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await a.persistActivations();let h=await new I(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=h.length;for(let l of h)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 p={cycle:{...this.currentCycle},insights:h,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,p}catch(r){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=E(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async 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);r+=c.changes}return r})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,r=t.get().count,a={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)a[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:r,byType:a,avgEdgesPerNode:i>0?r/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?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 ee(d){return new A(d)}Z();function te(d,e){if(e<0||e>=d.length)return d[0]??0;let t=0,n=d.length-1;for(;t<n;){let i=t+n>>1;if(d[i]<d[t]){let s=d[t];d[t]=d[i],d[i]=s}if(d[n]<d[t]){let s=d[t];d[t]=d[n],d[n]=s}if(d[i]<d[n]){let s=d[i];d[i]=d[n],d[n]=s}let r=d[n],a=t;for(let s=t;s<n;s++)if(d[s]<=r){let c=d[a];d[a]=d[s],d[s]=c,a++}let o=d[a];if(d[a]=d[n],d[n]=o,a===e)return d[a];a<e?t=a+1:n=a-1}return d[t]}var P=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},w=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(p=>this.graph.getConcept(p)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let p of i)this.graph.setActivation(p,t),this.recordActivation(p,t);let r=0,a=t,o=0,s=0;for(;r<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let p=await this.spreadIteration(),l=this.graph.getActiveNodes(this.config.threshold);for(let u of l)u.activationLevel>a&&(a=u.activationLevel);if(l.length===o&&p===0){if(s++,s>=3)break}else s=0;o=l.length,r++}let c=this.graph.getActiveNodes(this.config.threshold).map(p=>({nodeId:p.id,activation:p.activationLevel})).sort((p,l)=>l.activation-p.activation),h=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:r,nodesActivated:c.length,peakActivation:a,activatedNodes:c,novelAssociations:h.map(p=>({source:p.source.id,target:p.target.id,strength:p.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,r=0,a=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let p=U(0,o.length),l=o[p];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>r&&(r=f.peakActivation);for(let b of f.activatedNodes)a.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),h=Array.from(a).map(p=>{let l=this.graph.getConcept(p);return{nodeId:p,activation:l?.activationLevel??0}}).filter(p=>p.activation>0).sort((p,l)=>l.activation-p.activation);return this.trimHistory(),{iterations:i,nodesActivated:h.length,peakActivation:r,activatedNodes:h,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((a,o)=>o.activationLevel-a.activationLevel).slice(0,i));let r=[];for(let a=0;a<n.length;a++)for(let o=a+1;o<n.length;o++){let s=n[a],c=n[o],h=Math.sqrt(s.activationLevel*c.activationLevel),p=this.graph.getEdge(s.id,c.id),l=this.graph.getEdge(c.id,s.id),u=p!==void 0||l!==void 0,m=p?.weight??l?.weight??0,v=!u||m<.3;h>.3&&(r.push({source:s,target:c,coActivation:h,isNovel:v}),this.trackCoActivation(s.id,c.id))}return r.sort((a,o)=>a.isNovel!==o.isNovel?a.isNovel?-1:1:o.coActivation-a.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=P)return;let e=Math.floor(P*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=te(n,t-1),r=[];for(let[a,o]of this.coActivationCounts){if(r.length>=t)break;o<=i&&r.push(a)}for(let a of r)this.coActivationCounts.delete(a)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let r=this.graph.getEdges(i.id);for(let a of r){let o=this.graph.getConcept(a.target);if(!o)continue;let s=i.activationLevel*a.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,h=Math.min(1,c+s);n.push({nodeId:a.target,newActivation:h})}}}for(let i of n){let r=this.graph.getConcept(i.nodeId);r&&i.newActivation>r.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(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(":"),r=t.get(i);(!r||n.strength>r.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ne}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 r=await this.detectPatternMerges(i);for(let c of r)c.cycleId=e,n.push(c);let a=await this.detectNovelAssociations(t.novelAssociations);for(let c of a)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,h)=>h.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let a=n[i],o=n[r],s=this.graph.getEdge(a.id,o.id),c=this.graph.getEdge(o.id,a.id),h=Math.max(s?.weight??0,c?.weight??0),p=this.calculateContentSimilarity(a.content,o.content),l=Math.sqrt(a.activationLevel*o.activationLevel),u=h*.4+p*.3+l*.3;if(u>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[a.id,o.id]}),v=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[a.id,o.id],edgeWeight:h,contentSimilarity:p,coActivation:l});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[a.id,o.id],description:this.generatePatternMergeDescription(a,o,u),noveltyScore:m,confidenceScore:v,actionable:v>=this.config.minConfidence,applied:!1,suggestedAction:v>=this.config.minConfidence?`Merge "${this.truncate(a.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),r=this.graph.getConcept(n.target);if(!i||!r)continue;let a=this.graph.getEdge(n.source,n.target);if(a&&a.weight>.5)continue;let o=i.conceptType!==r.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,r,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(r.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},r=i.successRate,a=i.executionCount,o=i.confidence,s=r!==void 0&&r<.7,c=a!==void 0&&a>10,h=o!==void 0&&o<.6;if(s||c&&h){let p=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,r,a),noveltyScore:p,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 r=i.conceptType??"pattern";n[r]||(n[r]=[]),n[r].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(r=>r.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ne().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),r=new Set(n),a=new Set(i),o=n.filter(c=>a.has(c)),s=r.size+a.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let r=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${r}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};$();G();H();import{existsSync as ie,unlinkSync as re}from"fs";var T={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},C=class{constructor(e,t=T){this.db=e;this.thresholds=t}db;thresholds;activeBranches=new Map;listeners=[];rvfAdapter;useRvfFork=!1;_witnessChain=null;set witnessChain(e){this._witnessChain=e}setRvfAdapter(e,t=!0){this.rvfAdapter=e,this.useRvfFork=t,import("./feature-flags-TKDXIHOH.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let p=-r/n.patternCount;p>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(p*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let p=o/n.highConfidenceCount;p>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(p*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let p=this.rvfAdapter.dimension?.()??384,l=new Float32Array(p);for(let m=0;m<p;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 h=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:h,patternCountDelta:r,avgConfidenceDelta:a,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&ie(n)&&re(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}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},_=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();try{this.db.pragma("busy_timeout = 60000")}catch{}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(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),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 r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new z(this.graph);await a.loadIntoMemory(30);let s=await new w(a,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await a.persistActivations();let h=await new I(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=h.length;for(let l of h)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 p={cycle:{...this.currentCycle},insights:h,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,p}catch(r){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=E(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async 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-UDKBQAAH.js";import{c as V,d as q}from"./chunk-A5LZVQ
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 ae(d){let e=new _(d);return import("./feature-flags-TAKLIOWM.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-YU7XN6ND.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var se=_;H();var Y="learning:loop-health";async function J(d,e,t){try{let n=new Date().toISOString(),i=await d.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await d.set(Y,i)}catch{}}var g=N.create("DreamScheduler"),K={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},L=class d{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...K,...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});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&g.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){g.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),g.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&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 maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-YU7XN6ND.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&g.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){g.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-G5VIQHSN.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&g.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){g.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new W,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>d.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>d.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 oe(d,e){return new L(d,e)}var ce=[{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}}],k=class{constructor(e,t){this.db=e;this.branchManager=new C(e,t??T)}db;branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,h)=>{let p=this.scoreValidation(c.validation);return this.scoreValidation(h.validation)>p?h:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,K as b,L as c,oe as d,B as e,A as f,ee as g,P as h,O as i,F as j,j as k,w as l,Q as m,I as n,T as o,C as p,X as q,_ as r,ae as s,se as t,ce as u,k as v};
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 ae(d){let e=new _(d);return import("./feature-flags-TKDXIHOH.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-LWYHWJIA.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var se=_;H();var Y="learning:loop-health";async function J(d,e,t){try{let n=new Date().toISOString(),i=await d.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await d.set(Y,i)}catch{}}var g=N.create("DreamScheduler"),K={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},L=class d{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...K,...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});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&g.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){g.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),g.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&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 maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-LWYHWJIA.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&g.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){g.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-P2U424FB.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&g.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){g.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new W,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>d.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>d.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 oe(d,e){return new L(d,e)}var ce=[{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}}],k=class{constructor(e,t){this.db=e;this.branchManager=new C(e,t??T)}db;branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,h)=>{let p=this.scoreValidation(c.validation);return this.scoreValidation(h.validation)>p?h:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,K as b,L as c,oe as d,B as e,A as f,ee as g,P as h,O as i,F as j,j as k,w as l,Q as m,I as n,T as o,C as p,X as q,_ as r,ae as s,se as t,ce as u,k as v};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.35");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.36");process.exit(0)}
2
2
  var t=["claude","openai","ollama","openrouter","gemini","azure-openai","bedrock","onnx"];var e={maxAttempts:3,delayMs:100,trySameProviderAlternateModel:!0,skipOpenCircuits:!0,retryableErrors:["RATE_LIMITED","TIMEOUT","NETWORK_ERROR","PROVIDER_UNAVAILABLE"]},r=[{provider:"claude",models:["claude-sonnet-4-6","claude-haiku-4-5-20251001"],enabled:!0,priority:100,maxAttempts:2,timeoutMs:3e4},{provider:"openai",models:["gpt-4o","gpt-4o-mini"],enabled:!0,priority:90,maxAttempts:2,timeoutMs:3e4},{provider:"openrouter",models:["anthropic/claude-sonnet-4","openai/gpt-4o"],enabled:!0,priority:85,maxAttempts:2,timeoutMs:3e4},{provider:"ollama",models:["llama3.1","mistral"],enabled:!0,priority:80,maxAttempts:2,timeoutMs:6e4},{provider:"onnx",models:["phi-4","all-MiniLM-L6-v2"],enabled:!0,priority:70,maxAttempts:1,timeoutMs:12e4}],o={id:"default-fallback-chain",entries:r,maxRetries:3,retryDelayMs:100,backoffMultiplier:2,maxDelayMs:5e3},n={mode:"rule-based",rules:[],defaultProvider:"claude",defaultModel:"claude-sonnet-4-6",fallbackChain:o,fallbackBehavior:e,providers:{claude:{enabled:!0,defaultModel:"claude-sonnet-4-6"},openai:{enabled:!0,defaultModel:"gpt-4o"},ollama:{enabled:!0,defaultModel:"llama3.1"},openrouter:{enabled:!0,defaultModel:"anthropic/claude-sonnet-4"},gemini:{enabled:!1,defaultModel:"gemini-pro"},"azure-openai":{enabled:!1},bedrock:{enabled:!1},onnx:{enabled:!0,defaultModel:"phi-4"}},enableMetrics:!0,metricsConfig:{enabled:!0,collectionIntervalMs:6e4,retentionMs:864e5,trackPerRequest:!0},maxDecisionTimeMs:10,cacheDecisions:!0,decisionCacheTtlMs:6e4,cacheConfig:{enabled:!0,ttlMs:6e4,maxEntries:1e3,keyStrategy:"agent-domain"},auditConfig:{enabled:!0,maxEntries:1e4,logContent:!1,logResponse:!1}},a=[{canonicalId:"claude-opus-4-7",canonicalName:"Claude Opus 4.7",providerIds:{claude:"claude-opus-4-7",openrouter:"anthropic/claude-opus-4.7",bedrock:"anthropic.claude-opus-4-7-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:5,outputCostPer1M:25},{canonicalId:"claude-sonnet-4-6",canonicalName:"Claude Sonnet 4.6",providerIds:{claude:"claude-sonnet-4-6",openrouter:"anthropic/claude-sonnet-4.6",bedrock:"anthropic.claude-sonnet-4-6-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:2e5,maxOutputTokens:64e3},tier:"advanced",family:"claude",inputCostPer1M:3,outputCostPer1M:15},{canonicalId:"claude-haiku-4-5",canonicalName:"Claude Haiku 4.5",providerIds:{claude:"claude-haiku-4-5-20251001",openrouter:"anthropic/claude-haiku-4.5",bedrock:"anthropic.claude-haiku-4-5-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:2e5,maxOutputTokens:16384},tier:"standard",family:"claude",inputCostPer1M:1,outputCostPer1M:5},{canonicalId:"gpt-4o",canonicalName:"GPT-4o",providerIds:{openai:"gpt-4o","azure-openai":"gpt-4o",openrouter:"openai/gpt-4o"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"advanced",family:"gpt",inputCostPer1M:2.5,outputCostPer1M:10},{canonicalId:"gpt-4o-mini",canonicalName:"GPT-4o Mini",providerIds:{openai:"gpt-4o-mini","azure-openai":"gpt-4o-mini",openrouter:"openai/gpt-4o-mini"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"standard",family:"gpt",inputCostPer1M:.15,outputCostPer1M:.6},{canonicalId:"gemini-pro",canonicalName:"Gemini 2.0 Pro",providerIds:{gemini:"gemini-2.0-pro",openrouter:"google/gemini-2.0-pro"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:2e6,maxOutputTokens:8192},tier:"advanced",family:"gemini",inputCostPer1M:1.25,outputCostPer1M:5},{canonicalId:"llama-3.1-70b",canonicalName:"LLaMA 3.1 70B",providerIds:{ollama:"llama3.1:70b",openrouter:"meta-llama/llama-3.1-70b",bedrock:"meta.llama3-1-70b-instruct-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:4096},tier:"advanced",family:"llama",inputCostPer1M:.9,outputCostPer1M:.9},{canonicalId:"phi-4",canonicalName:"Microsoft Phi-4",providerIds:{ollama:"phi4",onnx:"phi-4",openrouter:"microsoft/phi-4"},capabilities:{supportsStreaming:!0,supportsTools:!1,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!1,maxContextTokens:16e3,maxOutputTokens:4096,requiresNetwork:!1},tier:"efficient",family:"phi",inputCostPer1M:0,outputCostPer1M:0}];export{t as a,n as b,a as c};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.35");process.exit(0)}
2
- import{f as p}from"./chunk-FMV22K3J.js";import{a as f,c as R}from"./chunk-DEJW6GYF.js";R();var u=class extends p{config={name:"qe/workflows/browser-load",description:"Load, validate, and prepare browser automation workflows from inline YAML or built-in templates. Returns the resolved workflow with steps and variable bindings, ready for browser execution. Templates: login-flow, form-validation, visual-regression, oauth-flow, etc.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{workflowYaml:{type:"string",description:"Inline YAML workflow definition. Mutually exclusive with templateName."},templateName:{type:"string",description:"Built-in template name to load.",enum:["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"]},variables:{type:"object",description:'Runtime variable overrides (e.g., { "baseUrl": "https://example.com" })'}}}}async execute(r,C){try{let{WorkflowLoader:n,WORKFLOW_TEMPLATES:g,WORKFLOW_DESCRIPTIONS:v,interpolateVariables:b}=await import("./browser-BMM57TA3.js"),{parse:k}=await import("yaml"),d=new n,l=[...g],y=v;if(!r.workflowYaml&&!r.templateName)return{success:!0,data:{workflowName:"none",description:"No workflow specified. Use templateName or workflowYaml.",source:"none",templateUsed:null,steps:[],variables:{defined:[],provided:{}},validation:{valid:!0,errors:[],warnings:[]},availableTemplates:l,summary:`Available templates: ${l.join(", ")}`}};let e,i,t=null;r.workflowYaml?(i="inline-yaml",e=k(r.workflowYaml)):(i="template",t=r.templateName,e=await d.load(r.templateName));let a=await d.validate(e),w=(e.steps??[]).map(o=>{let s=o.config;if(r.variables){let c={};for(let[h,m]of Object.entries(s))c[h]=typeof m=="string"?b(m,r.variables):m;s=c}return{name:o.name,action:o.action,config:s,optional:o.optional??!1,assertionCount:o.assertions?.length??0}});return{success:!0,data:{workflowName:e.name||t||"custom",description:e.description||t&&y[t]||"",source:i,templateUsed:t,steps:w,variables:{defined:(e.variables??[]).map(o=>({name:o.name,type:o.type,required:o.required,hasDefault:o.default!==void 0})),provided:r.variables||{}},validation:{valid:a.valid,errors:a.errors,warnings:a.warnings},availableTemplates:l,summary:a.valid?`Workflow "${e.name}" loaded (${i}): ${w.length} steps, ${(e.variables??[]).length} variables`:`Workflow "${e.name}" has validation errors: ${a.errors.join("; ")}`}}}catch(n){return{success:!1,error:f(n)}}}};export{u 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.36");process.exit(0)}
2
+ import{f as p}from"./chunk-JD3VV2BD.js";import{a as f,c as R}from"./chunk-O4C3JEOR.js";R();var u=class extends p{config={name:"qe/workflows/browser-load",description:"Load, validate, and prepare browser automation workflows from inline YAML or built-in templates. Returns the resolved workflow with steps and variable bindings, ready for browser execution. Templates: login-flow, form-validation, visual-regression, oauth-flow, etc.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{workflowYaml:{type:"string",description:"Inline YAML workflow definition. Mutually exclusive with templateName."},templateName:{type:"string",description:"Built-in template name to load.",enum:["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"]},variables:{type:"object",description:'Runtime variable overrides (e.g., { "baseUrl": "https://example.com" })'}}}}async execute(r,C){try{let{WorkflowLoader:n,WORKFLOW_TEMPLATES:g,WORKFLOW_DESCRIPTIONS:v,interpolateVariables:b}=await import("./browser-ZFZCR7LP.js"),{parse:k}=await import("yaml"),d=new n,l=[...g],y=v;if(!r.workflowYaml&&!r.templateName)return{success:!0,data:{workflowName:"none",description:"No workflow specified. Use templateName or workflowYaml.",source:"none",templateUsed:null,steps:[],variables:{defined:[],provided:{}},validation:{valid:!0,errors:[],warnings:[]},availableTemplates:l,summary:`Available templates: ${l.join(", ")}`}};let e,i,t=null;r.workflowYaml?(i="inline-yaml",e=k(r.workflowYaml)):(i="template",t=r.templateName,e=await d.load(r.templateName));let a=await d.validate(e),w=(e.steps??[]).map(o=>{let s=o.config;if(r.variables){let c={};for(let[h,m]of Object.entries(s))c[h]=typeof m=="string"?b(m,r.variables):m;s=c}return{name:o.name,action:o.action,config:s,optional:o.optional??!1,assertionCount:o.assertions?.length??0}});return{success:!0,data:{workflowName:e.name||t||"custom",description:e.description||t&&y[t]||"",source:i,templateUsed:t,steps:w,variables:{defined:(e.variables??[]).map(o=>({name:o.name,type:o.type,required:o.required,hasDefault:o.default!==void 0})),provided:r.variables||{}},validation:{valid:a.valid,errors:a.errors,warnings:a.warnings},availableTemplates:l,summary:a.valid?`Workflow "${e.name}" loaded (${i}): ${w.length} steps, ${(e.variables??[]).length} variables`:`Workflow "${e.name}" has validation errors: ${a.errors.join("; ")}`}}}catch(n){return{success:!1,error:f(n)}}}};export{u 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.35");process.exit(0)}
2
- import{o as me}from"./chunk-BKF3E3UJ.js";import{b as w,c as E,d as A,f as j,k as de,o as ue}from"./chunk-IXOGBA7C.js";import{a as Re,b as _,d as ee}from"./chunk-RZDMSTAQ.js";import{a as v}from"./chunk-PHJK33IV.js";import{c as b}from"./chunk-BTPDHALG.js";import{a as d,b as L,c as P}from"./chunk-DEJW6GYF.js";import{i as I}from"./chunk-E7N6CRFV.js";import{a as T,b as z}from"./chunk-NZB2JE2D.js";import{a as le,d as Te}from"./chunk-HMIRBSTI.js";import{f as Ce}from"./chunk-HSR7EHVN.js";var k={cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},environment:process.env.AQE_ENV||"all",batchSize:1e3,sources:[{name:"qe-patterns",cloudTable:"aqe.qe_patterns",localTable:"qe_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","embedding","sync_version"],transforms:{reusable:"boolean-to-int"}},{name:"sona-patterns",cloudTable:"aqe.sona_patterns",localTable:"sona_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],transforms:{is_active:"boolean-to-int",requires_fine_tuning:"boolean-to-int"}},{name:"goap-actions",cloudTable:"aqe.goap_actions",localTable:"goap_actions",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{duration_estimate:"estimated_duration_ms"}},{name:"goap-plans",cloudTable:"aqe.goap_plans",localTable:"goap_plans",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{estimated_duration:"estimated_duration_ms"}},{name:"memory-entries",cloudTable:"aqe.memory_entries",localTable:"kv_store",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}},{name:"learning-experiences",cloudTable:"aqe.learning_experiences",localTable:"captured_experiences",enabled:!0,priority:"high",mode:"append",dropColumns:["id","source_env","sync_version"],columnMap:{agent_id:"agent",task_id:"task",task_type:"domain",state:"result_json",action:"steps_json",reward:"quality",next_state:"routing_json",episode_id:"tags",created_at:"started_at"}},{name:"qlearning-patterns",cloudTable:"aqe.qlearning_patterns",localTable:"rl_q_values",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{state:"state_key",action:"action_key",last_update:"updated_at"}},{name:"routing-outcomes",cloudTable:"aqe.routing_outcomes",localTable:"routing_outcomes",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version"]},{name:"qe-trajectories",cloudTable:"aqe.qe_trajectories",localTable:"qe_trajectories",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version","embedding"]},{name:"dream-insights",cloudTable:"aqe.dream_insights",localTable:"dream_insights",enabled:!0,priority:"low",mode:"append",dropColumns:["source_env","sync_version"]},{name:"claude-flow-memory",cloudTable:"aqe.claude_flow_memory",localTable:"kv_store",enabled:!0,priority:"low",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}}]},Pe={TEXT:"TEXT",INTEGER:"INTEGER",REAL:"REAL",BLOB:"BYTEA",NULL:"NULL"},x={local:{v3MemoryDb:"./.agentic-qe/memory.db",rootMemoryDb:"./.agentic-qe/memory.db",claudeFlowMemory:"./.claude-flow/memory/store.json",claudeFlowDaemon:"./.claude-flow/daemon-state.json",claudeFlowMetrics:"./.claude-flow/metrics/",intelligenceJson:"./.ruvector/intelligence.json",swarmMemoryDb:"./.swarm/memory.db",v2PatternsDb:""},cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},sync:{mode:"incremental",interval:"1h",batchSize:1e3,conflictResolution:"newer-wins",sourcePriority:{qePatterns:1,sonaPatterns:2,goapActions:3,kvStore:4,experiences:5,claudeFlowMemory:6,intelligenceJson:7},sources:[{name:"root-qe-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_patterns",priority:"high",mode:"incremental",query:"SELECT id, pattern_type, qe_domain, domain, name, description, confidence, usage_count, success_rate, quality_score, tier, template_json, context_json, successful_uses, created_at, updated_at, last_used_at, tokens_used, input_tokens, output_tokens, latency_ms, reusable, reuse_count, average_token_savings, total_tokens_saved FROM qe_patterns",enabled:!0},{name:"root-sona-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.sona_patterns",priority:"high",mode:"incremental",query:"SELECT * FROM sona_patterns",enabled:!0},{name:"root-goap-actions",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_actions",priority:"high",mode:"incremental",query:"SELECT * FROM goap_actions",enabled:!0},{name:"root-kv-store",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.memory_entries",priority:"high",mode:"incremental",query:"SELECT key, namespace as partition, CASE WHEN json_valid(value) THEN value ELSE json_quote(value) END as value, created_at, expires_at FROM kv_store WHERE json_valid(value) OR json_valid(json_quote(value))",enabled:!0},{name:"root-captured-experiences",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.learning_experiences",priority:"high",mode:"append",query:"SELECT agent as agent_id, task as task_id, domain as task_type, COALESCE(result_json, '{}') as state, COALESCE(steps_json, '{}') as action, quality as reward, COALESCE(routing_json, '{}') as next_state, tags as episode_id, started_at as created_at FROM captured_experiences",enabled:!0},{name:"root-goap-plans",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_plans",priority:"medium",mode:"incremental",query:"SELECT id, goal_id, action_sequence as sequence, initial_state, goal_state, action_sequence, total_cost, estimated_duration_ms as estimated_duration, status, created_at, completed_at FROM goap_plans",enabled:!0},{name:"root-rl-q-values",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qlearning_patterns",priority:"medium",mode:"incremental",query:"SELECT DISTINCT state_key as state, action_key as action, q_value, visits, updated_at as last_update, created_at FROM rl_q_values GROUP BY state_key, action_key",enabled:!0},{name:"root-routing-outcomes",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.routing_outcomes",priority:"medium",mode:"append",query:"SELECT * FROM routing_outcomes",enabled:!0},{name:"root-qe-trajectories",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_trajectories",priority:"medium",mode:"append",query:"SELECT * FROM qe_trajectories",enabled:!0},{name:"root-dream-insights",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.dream_insights",priority:"low",mode:"append",query:"SELECT * FROM dream_insights",enabled:!0},{name:"claude-flow-memory",type:"json",path:"./.claude-flow/memory/store.json",targetTable:"aqe.claude_flow_memory",priority:"medium",mode:"full",enabled:!0},{name:"intelligence-qlearning",type:"json",path:"./.ruvector/intelligence.json",targetTable:"aqe.qlearning_patterns",priority:"low",mode:"full",jsonPath:"$.qvalues",enabled:!0}]},environment:process.env.AQE_ENV||"devpod"};z();A();ee();P();v();import*as te from"fs";import*as ge from"path";var F=b.create("sqlite-reader"),W=class{name;type="sqlite";db=null;config;dbPath;constructor(e){this.config=e,this.name=e.source.name,this.dbPath=ge.resolve(e.baseDir,e.source.path)}async initialize(){if(!this.db){if(!te.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}`);try{this.db=T(this.dbPath,{readonly:!0}),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),console.log(`[SQLiteReader:${this.name}] Initialized: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async readAll(){if(!this.db)throw new Error("Reader not initialized");let e=this.config.source.query||`SELECT * FROM ${w(this.getTableName())}`;try{return this.tableExists(this.getTableName())?this.db.prepare(e).all().map(r=>this.transformRecord(r)):(console.warn(`[SQLiteReader:${this.name}] Table not found, returning empty`),[])}catch(t){throw new Error(`Failed to read from ${this.name}: ${d(t)}`)}}async readChanged(e){if(!this.db)throw new Error("Reader not initialized");let t=this.findTimestampColumn();if(!t)return console.warn(`[SQLiteReader:${this.name}] No timestamp column found, falling back to readAll`),this.readAll();let n=this.getTableName();if(!this.tableExists(n))return[];let r=e.toISOString(),i=`SELECT * FROM ${w(n)} WHERE ${t} > ?`;try{return this.db.prepare(i).all(r).map(a=>this.transformRecord(a))}catch{return console.warn(`[SQLiteReader:${this.name}] Changed query failed, falling back to readAll`),this.readAll()}}async count(){if(!this.db)throw new Error("Reader not initialized");let e=this.getTableName();if(!this.tableExists(e))return 0;try{return this.db.prepare(`SELECT COUNT(*) as count FROM ${w(e)}`).get().count}catch(t){return F.debug("Record count query failed",{table:e,error:d(t)}),0}}async close(){this.db&&(this.db.close(),this.db=null,console.log(`[SQLiteReader:${this.name}] Closed`))}getTableName(){let e=this.config.source.query;if(e){let r=e.match(/FROM\s+(\w+)/i);if(r)return r[1]}let n=this.config.source.targetTable.split(".");return n[n.length-1]}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch(t){return F.debug("Table existence check failed",{table:e,error:t instanceof Error?t.message:String(t)}),!1}}findTimestampColumn(){if(!this.db)return null;let e=this.getTableName(),t=["updated_at","created_at","timestamp","last_used_at","modified_at"];try{let i=this.db.prepare(`PRAGMA table_info(${w(e)})`).all().map(o=>o.name.toLowerCase());for(let o of t)if(i.includes(o))return o}catch(n){return F.debug("Timestamp column detection failed",{table:e,error:n instanceof Error?n.message:String(n)}),null}return null}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t)){if(typeof r=="string"&&this.looksLikeJson(r))try{t[n]=_(r)}catch(i){F.debug("JSON parse failed for record field",{key:n,error:i instanceof Error?i.message:String(i)})}if(n.endsWith("_at")&&typeof r=="number"&&(t[n]=new Date(r).toISOString()),r instanceof Buffer)if(n.includes("embedding")){let i=e.dimension||384;t[n]=Array.from(new Float32Array(r.buffer,r.byteOffset,i))}else t[n]=r.toString("base64")}return t}looksLikeJson(e){if(!e)return!1;let t=e.trim();return t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")}getInfo(){let e=te.existsSync(this.dbPath),t=[];if(e&&this.db)try{t=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all().map(r=>r.name)}catch(n){console.debug("[SQLiteReader] Table listing error:",n instanceof Error?n.message:n)}return{path:this.dbPath,exists:e,tables:t}}};function re(l){return new W(l)}var he=Ce(Re(),1);P();import{randomUUID as ve}from"crypto";import*as C from"fs";import*as pe from"path";var U=class{name;type="json";config;filePath;data=null;fileModTime=null;constructor(e){this.config=e,this.name=e.source.name,this.filePath=pe.resolve(e.baseDir,e.source.path)}async initialize(){if(!C.existsSync(this.filePath)){console.warn(`[JSONReader:${this.name}] File not found: ${this.filePath}`),this.data=[];return}let e=C.statSync(this.filePath);this.fileModTime=e.mtime,console.log(`[JSONReader:${this.name}] Initialized: ${this.filePath}`)}async readAll(){if(!C.existsSync(this.filePath))return[];try{let e=C.readFileSync(this.filePath,"utf-8"),t=he.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${d(e)}`),[]}}async readChanged(e){return C.existsSync(this.filePath)?C.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([i,o])=>({state:i,...typeof o=="object"?o:{value:o}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,i]of Object.entries(n)){if(r.startsWith("_"))continue;let o="general";r.includes("adr")?o="adr-analysis":r.includes("agent")?o="agent-patterns":r.includes("pattern")?o="patterns":r.includes("metric")&&(o="metrics"),t.push({key:r,value:typeof i=="object"?i:{data:i},category:o})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null)for(let[s,a]of Object.entries(o)){let c=typeof a=="object"?a:{value:a};t.push({state:i,action:s,q_value:c.value||c.q_value||0,visits:c.visits||0,last_update:c.lastUpdate||c.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let i=r;t.push({id:i.id||`mem_${Date.now()}_${ve().slice(0,12)}`,memory_type:i.type||"file_access",content:i.content||i.path,embedding:i.embedding,metadata:i.metadata,timestamp:i.timestamp})}}return t}extractDaemonState(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.workers&&typeof n.workers=="object"){let r=n.workers;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null){let s=o;t.push({worker_type:i,run_count:s.runCount||s.runs||0,success_count:s.successCount||s.successes||0,failure_count:s.failureCount||s.failures||0,avg_duration_ms:s.avgDuration||s.averageDurationMs,last_run:s.lastRun})}}return t}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t))(n.includes("timestamp")||n.endsWith("_at")||n==="last_update")&&(typeof r=="number"?t[n]=new Date(r).toISOString():typeof r=="string"&&!isNaN(Date.parse(r))&&(t[n]=new Date(r).toISOString())),typeof r=="object"&&r!==null&&!Array.isArray(r)&&["value","metadata","embedding"].includes(n);return t.created_at||(t.created_at=new Date().toISOString()),t}getInfo(){let e=C.existsSync(this.filePath),t=0,n=null;if(e){let r=C.statSync(this.filePath);t=r.size,n=r.mtime}return{path:this.filePath,exists:e,modTime:n,size:t}}};function ne(l){return new U(l)}v();import{spawn as _e}from"child_process";import{createConnection as xe}from"net";var Ae=b.create("tunnel-manager");function fe(l){try{let e=new URL(l);return e.password&&(e.password="***"),e.toString()}catch(e){return Ae.debug("URL parse failed during redaction, using regex fallback",{error:e instanceof Error?e.message:String(e)}),l.replace(/:\/\/([^:]+):([^@]+)@/,"://$1:***@")}}var M=class{process=null;connection=null;config;constructor(e){this.config=e}checkPort(e,t,n=2e3){return new Promise(r=>{let i=xe({host:e,port:t}),o=setTimeout(()=>{i.destroy(),r(!1)},n);i.on("connect",()=>{clearTimeout(o),i.destroy(),r(!0)}),i.on("error",()=>{clearTimeout(o),i.destroy(),r(!1)})})}async start(){return this.process&&this.connection?(console.log("[TunnelManager] Tunnel already running"),this.connection):await this.checkPort("localhost",this.config.tunnelPort)?(console.log(`[TunnelManager] External tunnel detected on port ${this.config.tunnelPort}, reusing`),this.connection={host:"localhost",port:this.config.tunnelPort,startedAt:new Date},this.connection):new Promise((t,n)=>{let r=["compute","start-iap-tunnel",this.config.instance,"5432",`--local-host-port=localhost:${this.config.tunnelPort}`,`--zone=${this.config.zone}`,`--project=${this.config.project}`];console.log(`[TunnelManager] Starting IAP tunnel: gcloud ${r.join(" ")}`),this.process=_e("gcloud",r,{stdio:["ignore","pipe","pipe"]});let i=!1,o="",s=!1;this.process.stderr?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`),["Listening on port","tunnel is running","Testing if tunnel connection works"].some(m=>c.includes(m))&&!i&&!s&&(s=!0,setTimeout(async()=>{for(let g=0;g<10;g++){if(console.log(`[TunnelManager] Checking port connectivity (attempt ${g+1}/10)...`),await this.checkPort("localhost",this.config.tunnelPort)){i=!0,this.connection={host:"localhost",port:this.config.tunnelPort,pid:this.process?.pid,startedAt:new Date},console.log(`[TunnelManager] Tunnel ready on port ${this.config.tunnelPort}`),t(this.connection);return}await new Promise(y=>setTimeout(y,1e3))}s=!1},2e3)),o+=c}),this.process.stdout?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`)}),this.process.on("error",a=>{console.error(`[TunnelManager] Process error: ${a.message}`),i||n(new Error(`Failed to start tunnel: ${a.message}`))}),this.process.on("close",a=>{console.log(`[TunnelManager] Process closed with code ${a}`),this.process=null,this.connection=null,i||n(new Error(`Tunnel process exited with code ${a}: ${o}`))}),setTimeout(()=>{i||(this.stop(),n(new Error("Tunnel connection timeout")))},6e4)})}async stop(){this.process&&(console.log("[TunnelManager] Stopping tunnel"),this.process.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),this.process&&this.process.kill("SIGKILL"),this.process=null,this.connection=null)}isActive(){return this.process!==null&&this.connection!==null}getConnection(){return this.connection}getConnectionString(){if(!this.connection)throw new Error("Tunnel not active");let{database:e,user:t}=this.config,n=process.env.PGPASSWORD||"",r=this.connection.host,i=this.connection.port;return`postgresql://${t}:${n}@${r}:${i}/${e}`}getRedactedConnectionString(){return fe(this.getConnectionString())}};function ke(l){return new M(l)}var B=class{connection=null;connectionString;constructor(e){this.connectionString=e}async start(){let e=new URL(this.connectionString);return this.connection={host:e.hostname,port:parseInt(e.port||"5432",10),startedAt:new Date},this.connection}async stop(){this.connection=null}isActive(){return this.connection!==null}getConnection(){return this.connection}getConnectionString(){return this.connectionString}getRedactedConnectionString(){return fe(this.connectionString)}};function $(l){return l.connectionString?new B(l.connectionString):new M(l)}A();P();v();import{createRequire as Me}from"module";var N=b.create("postgres-writer"),$e=Me(import.meta.url),J=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=$e("pg")}catch(o){N.debug("pg module not installed, using mock mode",{error:o instanceof Error?o.message:String(o)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let i={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(i),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],i=Object.keys(r),o=n?.conflictColumns||this.inferConflictColumns(e,i),s=n?.updateColumns||i.filter(u=>!o.includes(u)),a=0,c=100;for(let u=0;u<t.length;u+=c){let p=t.slice(u,u+c);try{let m=await this.upsertBatch(e,p,i,o,s,n?.skipIfExists);a+=m}catch(m){let g=Math.floor(u/c)+1,h=Math.ceil(t.length/c);N.debug(`Batch ${g}/${h} failed for ${e}, retrying individually`,{error:d(m)});let y=0;for(let f of p)try{let S=await this.upsertBatch(e,[f],i,o,s,n?.skipIfExists);y+=S}catch(S){let R=f.id||f.key||"?";N.debug(`Skipped record ${String(R).slice(0,50)} in ${e}`,{error:d(S)})}a+=y,y<p.length&&console.warn(`[PostgresWriter] Batch ${g}/${h} for ${e}: ${y}/${p.length} recovered (${p.length-y} skipped)`)}}return a}async upsertBatch(e,t,n,r,i,o){if(!this.client)return 0;let s=[],a=[],c=1;for(let f of t){let S=[];for(let R of n){let Ee=f[R];S.push(`$${c++}`),a.push(this.serializeValue(Ee,R))}s.push(`(${S.join(", ")})`)}let u=E(e),p=n.map(E),m=r.map(E),g=i.map(E),h="";if(m.length>0){if(o)h=`ON CONFLICT (${m.join(", ")}) DO NOTHING`;else if(g.length>0){let f=g.map(S=>`${S} = EXCLUDED.${S}`).join(", ");h=`ON CONFLICT (${m.join(", ")}) DO UPDATE SET ${f}`}}let y=`
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.36");process.exit(0)}
2
+ import{o as me}from"./chunk-PY4B37U3.js";import{b as w,c as E,d as A,f as j,k as de,o as ue}from"./chunk-5MSZREOD.js";import{a as Re,b as _,d as ee}from"./chunk-HOZNVDFF.js";import{a as v}from"./chunk-ZYPSXPQ5.js";import{c as b}from"./chunk-VENEJ3UI.js";import{a as d,b as L,c as P}from"./chunk-O4C3JEOR.js";import{i as I}from"./chunk-NKA3X6VT.js";import{a as T,b as z}from"./chunk-TXSVZYFA.js";import{a as le,d as Te}from"./chunk-KI6RXKP4.js";import{f as Ce}from"./chunk-SCBWRKPE.js";var k={cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},environment:process.env.AQE_ENV||"all",batchSize:1e3,sources:[{name:"qe-patterns",cloudTable:"aqe.qe_patterns",localTable:"qe_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","embedding","sync_version"],transforms:{reusable:"boolean-to-int"}},{name:"sona-patterns",cloudTable:"aqe.sona_patterns",localTable:"sona_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],transforms:{is_active:"boolean-to-int",requires_fine_tuning:"boolean-to-int"}},{name:"goap-actions",cloudTable:"aqe.goap_actions",localTable:"goap_actions",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{duration_estimate:"estimated_duration_ms"}},{name:"goap-plans",cloudTable:"aqe.goap_plans",localTable:"goap_plans",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{estimated_duration:"estimated_duration_ms"}},{name:"memory-entries",cloudTable:"aqe.memory_entries",localTable:"kv_store",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}},{name:"learning-experiences",cloudTable:"aqe.learning_experiences",localTable:"captured_experiences",enabled:!0,priority:"high",mode:"append",dropColumns:["id","source_env","sync_version"],columnMap:{agent_id:"agent",task_id:"task",task_type:"domain",state:"result_json",action:"steps_json",reward:"quality",next_state:"routing_json",episode_id:"tags",created_at:"started_at"}},{name:"qlearning-patterns",cloudTable:"aqe.qlearning_patterns",localTable:"rl_q_values",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{state:"state_key",action:"action_key",last_update:"updated_at"}},{name:"routing-outcomes",cloudTable:"aqe.routing_outcomes",localTable:"routing_outcomes",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version"]},{name:"qe-trajectories",cloudTable:"aqe.qe_trajectories",localTable:"qe_trajectories",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version","embedding"]},{name:"dream-insights",cloudTable:"aqe.dream_insights",localTable:"dream_insights",enabled:!0,priority:"low",mode:"append",dropColumns:["source_env","sync_version"]},{name:"claude-flow-memory",cloudTable:"aqe.claude_flow_memory",localTable:"kv_store",enabled:!0,priority:"low",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}}]},Pe={TEXT:"TEXT",INTEGER:"INTEGER",REAL:"REAL",BLOB:"BYTEA",NULL:"NULL"},x={local:{v3MemoryDb:"./.agentic-qe/memory.db",rootMemoryDb:"./.agentic-qe/memory.db",claudeFlowMemory:"./.claude-flow/memory/store.json",claudeFlowDaemon:"./.claude-flow/daemon-state.json",claudeFlowMetrics:"./.claude-flow/metrics/",intelligenceJson:"./.ruvector/intelligence.json",swarmMemoryDb:"./.swarm/memory.db",v2PatternsDb:""},cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},sync:{mode:"incremental",interval:"1h",batchSize:1e3,conflictResolution:"newer-wins",sourcePriority:{qePatterns:1,sonaPatterns:2,goapActions:3,kvStore:4,experiences:5,claudeFlowMemory:6,intelligenceJson:7},sources:[{name:"root-qe-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_patterns",priority:"high",mode:"incremental",query:"SELECT id, pattern_type, qe_domain, domain, name, description, confidence, usage_count, success_rate, quality_score, tier, template_json, context_json, successful_uses, created_at, updated_at, last_used_at, tokens_used, input_tokens, output_tokens, latency_ms, reusable, reuse_count, average_token_savings, total_tokens_saved FROM qe_patterns",enabled:!0},{name:"root-sona-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.sona_patterns",priority:"high",mode:"incremental",query:"SELECT * FROM sona_patterns",enabled:!0},{name:"root-goap-actions",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_actions",priority:"high",mode:"incremental",query:"SELECT * FROM goap_actions",enabled:!0},{name:"root-kv-store",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.memory_entries",priority:"high",mode:"incremental",query:"SELECT key, namespace as partition, CASE WHEN json_valid(value) THEN value ELSE json_quote(value) END as value, created_at, expires_at FROM kv_store WHERE json_valid(value) OR json_valid(json_quote(value))",enabled:!0},{name:"root-captured-experiences",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.learning_experiences",priority:"high",mode:"append",query:"SELECT agent as agent_id, task as task_id, domain as task_type, COALESCE(result_json, '{}') as state, COALESCE(steps_json, '{}') as action, quality as reward, COALESCE(routing_json, '{}') as next_state, tags as episode_id, started_at as created_at FROM captured_experiences",enabled:!0},{name:"root-goap-plans",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_plans",priority:"medium",mode:"incremental",query:"SELECT id, goal_id, action_sequence as sequence, initial_state, goal_state, action_sequence, total_cost, estimated_duration_ms as estimated_duration, status, created_at, completed_at FROM goap_plans",enabled:!0},{name:"root-rl-q-values",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qlearning_patterns",priority:"medium",mode:"incremental",query:"SELECT DISTINCT state_key as state, action_key as action, q_value, visits, updated_at as last_update, created_at FROM rl_q_values GROUP BY state_key, action_key",enabled:!0},{name:"root-routing-outcomes",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.routing_outcomes",priority:"medium",mode:"append",query:"SELECT * FROM routing_outcomes",enabled:!0},{name:"root-qe-trajectories",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_trajectories",priority:"medium",mode:"append",query:"SELECT * FROM qe_trajectories",enabled:!0},{name:"root-dream-insights",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.dream_insights",priority:"low",mode:"append",query:"SELECT * FROM dream_insights",enabled:!0},{name:"claude-flow-memory",type:"json",path:"./.claude-flow/memory/store.json",targetTable:"aqe.claude_flow_memory",priority:"medium",mode:"full",enabled:!0},{name:"intelligence-qlearning",type:"json",path:"./.ruvector/intelligence.json",targetTable:"aqe.qlearning_patterns",priority:"low",mode:"full",jsonPath:"$.qvalues",enabled:!0}]},environment:process.env.AQE_ENV||"devpod"};z();A();ee();P();v();import*as te from"fs";import*as ge from"path";var F=b.create("sqlite-reader"),W=class{name;type="sqlite";db=null;config;dbPath;constructor(e){this.config=e,this.name=e.source.name,this.dbPath=ge.resolve(e.baseDir,e.source.path)}async initialize(){if(!this.db){if(!te.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}`);try{this.db=T(this.dbPath,{readonly:!0}),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),console.log(`[SQLiteReader:${this.name}] Initialized: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async readAll(){if(!this.db)throw new Error("Reader not initialized");let e=this.config.source.query||`SELECT * FROM ${w(this.getTableName())}`;try{return this.tableExists(this.getTableName())?this.db.prepare(e).all().map(r=>this.transformRecord(r)):(console.warn(`[SQLiteReader:${this.name}] Table not found, returning empty`),[])}catch(t){throw new Error(`Failed to read from ${this.name}: ${d(t)}`)}}async readChanged(e){if(!this.db)throw new Error("Reader not initialized");let t=this.findTimestampColumn();if(!t)return console.warn(`[SQLiteReader:${this.name}] No timestamp column found, falling back to readAll`),this.readAll();let n=this.getTableName();if(!this.tableExists(n))return[];let r=e.toISOString(),i=`SELECT * FROM ${w(n)} WHERE ${t} > ?`;try{return this.db.prepare(i).all(r).map(a=>this.transformRecord(a))}catch{return console.warn(`[SQLiteReader:${this.name}] Changed query failed, falling back to readAll`),this.readAll()}}async count(){if(!this.db)throw new Error("Reader not initialized");let e=this.getTableName();if(!this.tableExists(e))return 0;try{return this.db.prepare(`SELECT COUNT(*) as count FROM ${w(e)}`).get().count}catch(t){return F.debug("Record count query failed",{table:e,error:d(t)}),0}}async close(){this.db&&(this.db.close(),this.db=null,console.log(`[SQLiteReader:${this.name}] Closed`))}getTableName(){let e=this.config.source.query;if(e){let r=e.match(/FROM\s+(\w+)/i);if(r)return r[1]}let n=this.config.source.targetTable.split(".");return n[n.length-1]}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch(t){return F.debug("Table existence check failed",{table:e,error:t instanceof Error?t.message:String(t)}),!1}}findTimestampColumn(){if(!this.db)return null;let e=this.getTableName(),t=["updated_at","created_at","timestamp","last_used_at","modified_at"];try{let i=this.db.prepare(`PRAGMA table_info(${w(e)})`).all().map(o=>o.name.toLowerCase());for(let o of t)if(i.includes(o))return o}catch(n){return F.debug("Timestamp column detection failed",{table:e,error:n instanceof Error?n.message:String(n)}),null}return null}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t)){if(typeof r=="string"&&this.looksLikeJson(r))try{t[n]=_(r)}catch(i){F.debug("JSON parse failed for record field",{key:n,error:i instanceof Error?i.message:String(i)})}if(n.endsWith("_at")&&typeof r=="number"&&(t[n]=new Date(r).toISOString()),r instanceof Buffer)if(n.includes("embedding")){let i=e.dimension||384;t[n]=Array.from(new Float32Array(r.buffer,r.byteOffset,i))}else t[n]=r.toString("base64")}return t}looksLikeJson(e){if(!e)return!1;let t=e.trim();return t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")}getInfo(){let e=te.existsSync(this.dbPath),t=[];if(e&&this.db)try{t=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all().map(r=>r.name)}catch(n){console.debug("[SQLiteReader] Table listing error:",n instanceof Error?n.message:n)}return{path:this.dbPath,exists:e,tables:t}}};function re(l){return new W(l)}var he=Ce(Re(),1);P();import{randomUUID as ve}from"crypto";import*as C from"fs";import*as pe from"path";var U=class{name;type="json";config;filePath;data=null;fileModTime=null;constructor(e){this.config=e,this.name=e.source.name,this.filePath=pe.resolve(e.baseDir,e.source.path)}async initialize(){if(!C.existsSync(this.filePath)){console.warn(`[JSONReader:${this.name}] File not found: ${this.filePath}`),this.data=[];return}let e=C.statSync(this.filePath);this.fileModTime=e.mtime,console.log(`[JSONReader:${this.name}] Initialized: ${this.filePath}`)}async readAll(){if(!C.existsSync(this.filePath))return[];try{let e=C.readFileSync(this.filePath,"utf-8"),t=he.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${d(e)}`),[]}}async readChanged(e){return C.existsSync(this.filePath)?C.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([i,o])=>({state:i,...typeof o=="object"?o:{value:o}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,i]of Object.entries(n)){if(r.startsWith("_"))continue;let o="general";r.includes("adr")?o="adr-analysis":r.includes("agent")?o="agent-patterns":r.includes("pattern")?o="patterns":r.includes("metric")&&(o="metrics"),t.push({key:r,value:typeof i=="object"?i:{data:i},category:o})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null)for(let[s,a]of Object.entries(o)){let c=typeof a=="object"?a:{value:a};t.push({state:i,action:s,q_value:c.value||c.q_value||0,visits:c.visits||0,last_update:c.lastUpdate||c.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let i=r;t.push({id:i.id||`mem_${Date.now()}_${ve().slice(0,12)}`,memory_type:i.type||"file_access",content:i.content||i.path,embedding:i.embedding,metadata:i.metadata,timestamp:i.timestamp})}}return t}extractDaemonState(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.workers&&typeof n.workers=="object"){let r=n.workers;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null){let s=o;t.push({worker_type:i,run_count:s.runCount||s.runs||0,success_count:s.successCount||s.successes||0,failure_count:s.failureCount||s.failures||0,avg_duration_ms:s.avgDuration||s.averageDurationMs,last_run:s.lastRun})}}return t}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t))(n.includes("timestamp")||n.endsWith("_at")||n==="last_update")&&(typeof r=="number"?t[n]=new Date(r).toISOString():typeof r=="string"&&!isNaN(Date.parse(r))&&(t[n]=new Date(r).toISOString())),typeof r=="object"&&r!==null&&!Array.isArray(r)&&["value","metadata","embedding"].includes(n);return t.created_at||(t.created_at=new Date().toISOString()),t}getInfo(){let e=C.existsSync(this.filePath),t=0,n=null;if(e){let r=C.statSync(this.filePath);t=r.size,n=r.mtime}return{path:this.filePath,exists:e,modTime:n,size:t}}};function ne(l){return new U(l)}v();import{spawn as _e}from"child_process";import{createConnection as xe}from"net";var Ae=b.create("tunnel-manager");function fe(l){try{let e=new URL(l);return e.password&&(e.password="***"),e.toString()}catch(e){return Ae.debug("URL parse failed during redaction, using regex fallback",{error:e instanceof Error?e.message:String(e)}),l.replace(/:\/\/([^:]+):([^@]+)@/,"://$1:***@")}}var M=class{process=null;connection=null;config;constructor(e){this.config=e}checkPort(e,t,n=2e3){return new Promise(r=>{let i=xe({host:e,port:t}),o=setTimeout(()=>{i.destroy(),r(!1)},n);i.on("connect",()=>{clearTimeout(o),i.destroy(),r(!0)}),i.on("error",()=>{clearTimeout(o),i.destroy(),r(!1)})})}async start(){return this.process&&this.connection?(console.log("[TunnelManager] Tunnel already running"),this.connection):await this.checkPort("localhost",this.config.tunnelPort)?(console.log(`[TunnelManager] External tunnel detected on port ${this.config.tunnelPort}, reusing`),this.connection={host:"localhost",port:this.config.tunnelPort,startedAt:new Date},this.connection):new Promise((t,n)=>{let r=["compute","start-iap-tunnel",this.config.instance,"5432",`--local-host-port=localhost:${this.config.tunnelPort}`,`--zone=${this.config.zone}`,`--project=${this.config.project}`];console.log(`[TunnelManager] Starting IAP tunnel: gcloud ${r.join(" ")}`),this.process=_e("gcloud",r,{stdio:["ignore","pipe","pipe"]});let i=!1,o="",s=!1;this.process.stderr?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`),["Listening on port","tunnel is running","Testing if tunnel connection works"].some(m=>c.includes(m))&&!i&&!s&&(s=!0,setTimeout(async()=>{for(let g=0;g<10;g++){if(console.log(`[TunnelManager] Checking port connectivity (attempt ${g+1}/10)...`),await this.checkPort("localhost",this.config.tunnelPort)){i=!0,this.connection={host:"localhost",port:this.config.tunnelPort,pid:this.process?.pid,startedAt:new Date},console.log(`[TunnelManager] Tunnel ready on port ${this.config.tunnelPort}`),t(this.connection);return}await new Promise(y=>setTimeout(y,1e3))}s=!1},2e3)),o+=c}),this.process.stdout?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`)}),this.process.on("error",a=>{console.error(`[TunnelManager] Process error: ${a.message}`),i||n(new Error(`Failed to start tunnel: ${a.message}`))}),this.process.on("close",a=>{console.log(`[TunnelManager] Process closed with code ${a}`),this.process=null,this.connection=null,i||n(new Error(`Tunnel process exited with code ${a}: ${o}`))}),setTimeout(()=>{i||(this.stop(),n(new Error("Tunnel connection timeout")))},6e4)})}async stop(){this.process&&(console.log("[TunnelManager] Stopping tunnel"),this.process.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),this.process&&this.process.kill("SIGKILL"),this.process=null,this.connection=null)}isActive(){return this.process!==null&&this.connection!==null}getConnection(){return this.connection}getConnectionString(){if(!this.connection)throw new Error("Tunnel not active");let{database:e,user:t}=this.config,n=process.env.PGPASSWORD||"",r=this.connection.host,i=this.connection.port;return`postgresql://${t}:${n}@${r}:${i}/${e}`}getRedactedConnectionString(){return fe(this.getConnectionString())}};function ke(l){return new M(l)}var B=class{connection=null;connectionString;constructor(e){this.connectionString=e}async start(){let e=new URL(this.connectionString);return this.connection={host:e.hostname,port:parseInt(e.port||"5432",10),startedAt:new Date},this.connection}async stop(){this.connection=null}isActive(){return this.connection!==null}getConnection(){return this.connection}getConnectionString(){return this.connectionString}getRedactedConnectionString(){return fe(this.connectionString)}};function $(l){return l.connectionString?new B(l.connectionString):new M(l)}A();P();v();import{createRequire as Me}from"module";var N=b.create("postgres-writer"),$e=Me(import.meta.url),J=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=$e("pg")}catch(o){N.debug("pg module not installed, using mock mode",{error:o instanceof Error?o.message:String(o)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let i={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(i),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],i=Object.keys(r),o=n?.conflictColumns||this.inferConflictColumns(e,i),s=n?.updateColumns||i.filter(u=>!o.includes(u)),a=0,c=100;for(let u=0;u<t.length;u+=c){let p=t.slice(u,u+c);try{let m=await this.upsertBatch(e,p,i,o,s,n?.skipIfExists);a+=m}catch(m){let g=Math.floor(u/c)+1,h=Math.ceil(t.length/c);N.debug(`Batch ${g}/${h} failed for ${e}, retrying individually`,{error:d(m)});let y=0;for(let f of p)try{let S=await this.upsertBatch(e,[f],i,o,s,n?.skipIfExists);y+=S}catch(S){let R=f.id||f.key||"?";N.debug(`Skipped record ${String(R).slice(0,50)} in ${e}`,{error:d(S)})}a+=y,y<p.length&&console.warn(`[PostgresWriter] Batch ${g}/${h} for ${e}: ${y}/${p.length} recovered (${p.length-y} skipped)`)}}return a}async upsertBatch(e,t,n,r,i,o){if(!this.client)return 0;let s=[],a=[],c=1;for(let f of t){let S=[];for(let R of n){let Ee=f[R];S.push(`$${c++}`),a.push(this.serializeValue(Ee,R))}s.push(`(${S.join(", ")})`)}let u=E(e),p=n.map(E),m=r.map(E),g=i.map(E),h="";if(m.length>0){if(o)h=`ON CONFLICT (${m.join(", ")}) DO NOTHING`;else if(g.length>0){let f=g.map(S=>`${S} = EXCLUDED.${S}`).join(", ");h=`ON CONFLICT (${m.join(", ")}) DO UPDATE SET ${f}`}}let y=`
3
3
  INSERT INTO ${u} (${p.join(", ")})
4
4
  VALUES ${s.join(", ")}
5
5
  ${h}
@@ -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.35");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.36");process.exit(0)}
2
2
  var i=class{s0;s1;s2;s3;constructor(s){this.s0=this.splitmix32(s),this.s1=this.splitmix32(this.s0),this.s2=this.splitmix32(this.s1),this.s3=this.splitmix32(this.s2)}splitmix32(s){return s=s+2654435769|0,s=Math.imul(s^s>>>16,2246822507),s=Math.imul(s^s>>>13,3266489909),(s^s>>>16)>>>0}next(){let s=this.s3,t=this.s0;return this.s3=this.s2,this.s2=this.s1,this.s1=t,t^=t<<11,t^=t>>>8,this.s0=t^s^s>>>19,this.s0>>>0}nextFloat(){return this.next()/4294967296}nextGaussian(){let s=this.nextFloat()||1e-10,t=this.nextFloat();return Math.sqrt(-2*Math.log(s))*Math.cos(2*Math.PI*t)}};export{i as a};