agentic-qe 3.13.5 → 3.13.6

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 (341) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +41 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/cli/bundle.js +5 -5
  5. package/dist/cli/chunks/adapter-7XXMDGFO.js +2 -0
  6. package/dist/cli/chunks/{agent-booster-wasm-XDKGG2GP.js → agent-booster-wasm-TMON22NL.js} +2 -2
  7. package/dist/cli/chunks/{agent-handler-CTPXGR5P.js → agent-handler-JOX6O26U.js} +2 -2
  8. package/dist/cli/chunks/{agent-memory-branch-MG5OV7AY.js → agent-memory-branch-AMIJIDCM.js} +2 -2
  9. package/dist/cli/chunks/aqe-learning-engine-2KGMCBJG.js +2 -0
  10. package/dist/cli/chunks/{arena-FAHVOHNG.js → arena-N6SO2CCQ.js} +2 -2
  11. package/dist/cli/chunks/{arena-NYO4EUNQ.js → arena-RKLFXDMO.js} +4 -4
  12. package/dist/cli/chunks/{audit-6544RL5D.js → audit-ZJE3DUH6.js} +3 -3
  13. package/dist/cli/chunks/base-4M3VL4XK.js +2 -0
  14. package/dist/cli/chunks/{better-sqlite3-MTEONNCQ.js → better-sqlite3-5G6AR6LX.js} +2 -2
  15. package/dist/cli/chunks/{brain-handler-DPKCUQUC.js → brain-handler-QD4DZ574.js} +3 -3
  16. package/dist/cli/chunks/{branch-enumerator-SU2KHC2C.js → branch-enumerator-PG3OUYE6.js} +2 -2
  17. package/dist/cli/chunks/{browser-ITDN72YJ.js → browser-Y2DJG7HQ.js} +2 -2
  18. package/dist/cli/chunks/browser-workflow-DHIPXEGO.js +2 -0
  19. package/dist/cli/chunks/{chunk-OJZ5LI3O.js → chunk-2BUDKFIE.js} +1 -1
  20. package/dist/cli/chunks/{chunk-OF5UL3FA.js → chunk-2FTAMEOB.js} +1 -1
  21. package/dist/cli/chunks/{chunk-6L5V3JGJ.js → chunk-2ILX73JG.js} +1 -1
  22. package/dist/cli/chunks/{chunk-YGMCRJSC.js → chunk-2SVDR5KB.js} +2 -2
  23. package/dist/cli/chunks/{chunk-OUWZTYRZ.js → chunk-2VUXU22M.js} +2 -2
  24. package/dist/cli/chunks/{chunk-L6I2Q6UQ.js → chunk-3OUHOJBN.js} +1 -1
  25. package/dist/cli/chunks/{chunk-PSD2L2JB.js → chunk-3QJH5W55.js} +2 -2
  26. package/dist/cli/chunks/{chunk-BAJK26EI.js → chunk-3TC4ZPGR.js} +2 -2
  27. package/dist/cli/chunks/{chunk-KAVYTFAS.js → chunk-463VBHHH.js} +2 -2
  28. package/dist/cli/chunks/{chunk-W7H46LAX.js → chunk-4VWB64OH.js} +1 -1
  29. package/dist/cli/chunks/{chunk-ELC3UEML.js → chunk-4YFBAXRD.js} +1 -1
  30. package/dist/cli/chunks/{chunk-G47WJMHM.js → chunk-523XPMTU.js} +1 -1
  31. package/dist/cli/chunks/{chunk-EPMUAKU2.js → chunk-5CMZDVUR.js} +2 -2
  32. package/dist/cli/chunks/{chunk-UGER2PGN.js → chunk-5VGQABM3.js} +4 -4
  33. package/dist/cli/chunks/{chunk-EROQSNGD.js → chunk-5VV5MOED.js} +2 -2
  34. package/dist/cli/chunks/{chunk-IC5JGTM4.js → chunk-6FICUNAV.js} +1 -1
  35. package/dist/cli/chunks/{chunk-ND7IWTVQ.js → chunk-6ITWOYET.js} +2 -2
  36. package/dist/cli/chunks/{chunk-GITS44TM.js → chunk-6QZSF6RL.js} +2 -2
  37. package/dist/cli/chunks/{chunk-6ZCAZ3TR.js → chunk-6UPQD42K.js} +2 -2
  38. package/dist/cli/chunks/{chunk-CHFZHORO.js → chunk-6VUEUYFL.js} +5 -5
  39. package/dist/cli/chunks/{chunk-VNRWJ5JZ.js → chunk-7225UNNY.js} +2 -2
  40. package/dist/cli/chunks/{chunk-7SQXEYII.js → chunk-75QKZ6VX.js} +2 -2
  41. package/dist/cli/chunks/{chunk-ZQ7XQLLV.js → chunk-7GTB7LVJ.js} +3 -3
  42. package/dist/cli/chunks/{chunk-D4P6BKGF.js → chunk-7KRZ2Q6B.js} +3 -3
  43. package/dist/cli/chunks/{chunk-HBYVYLBN.js → chunk-7NYCYSGW.js} +2 -2
  44. package/dist/cli/chunks/{chunk-2CF3XZAS.js → chunk-7TON6JSG.js} +2 -2
  45. package/dist/cli/chunks/{chunk-DK7MV2W3.js → chunk-ACHMNMEJ.js} +1 -1
  46. package/dist/cli/chunks/{chunk-5I5KMIFY.js → chunk-ADYY2GKC.js} +2 -2
  47. package/dist/cli/chunks/{chunk-GUO6JZMS.js → chunk-AOUULKKT.js} +2 -2
  48. package/dist/cli/chunks/{chunk-AKZ6PWHM.js → chunk-AU3APBY2.js} +2 -2
  49. package/dist/cli/chunks/{chunk-GWBV26SE.js → chunk-BAOKXLIV.js} +2 -2
  50. package/dist/cli/chunks/{chunk-DFBJPOJR.js → chunk-BDVZF46F.js} +2 -2
  51. package/dist/cli/chunks/{chunk-OQ4HOHBI.js → chunk-BGLSIA4U.js} +2 -2
  52. package/dist/cli/chunks/{chunk-FW6OPDA6.js → chunk-BI6UU3Z3.js} +1 -1
  53. package/dist/cli/chunks/{chunk-Z5YNYVFO.js → chunk-BOM5NGCR.js} +1 -1
  54. package/dist/cli/chunks/{chunk-XACF7ZLM.js → chunk-CBXJ4AQS.js} +2 -2
  55. package/dist/cli/chunks/{chunk-QLD2WVWN.js → chunk-CKYRZ3TA.js} +2 -2
  56. package/dist/cli/chunks/{chunk-2KPGJ4LO.js → chunk-CTILSLXF.js} +2 -2
  57. package/dist/cli/chunks/{chunk-BKI5NFQ5.js → chunk-CVXEOTIK.js} +2 -2
  58. package/dist/cli/chunks/{chunk-JTUTZUED.js → chunk-D777E2MT.js} +2 -2
  59. package/dist/cli/chunks/{chunk-LELWVGN6.js → chunk-DKGDBKBJ.js} +1 -1
  60. package/dist/cli/chunks/{chunk-YFD6K7AS.js → chunk-DLBJ7IZT.js} +23 -23
  61. package/dist/cli/chunks/{chunk-S2EUFKHL.js → chunk-DR2M2SI2.js} +2 -2
  62. package/dist/cli/chunks/{chunk-OGUPLNRY.js → chunk-DS53MJCN.js} +1 -1
  63. package/dist/cli/chunks/{chunk-K55D3PAR.js → chunk-DSIS6WQD.js} +3 -3
  64. package/dist/cli/chunks/{chunk-6BEMH5K5.js → chunk-DSTQ2OWI.js} +1 -1
  65. package/dist/cli/chunks/{chunk-2RZ2S6YR.js → chunk-DXM7IN2W.js} +2 -2
  66. package/dist/cli/chunks/{chunk-NVZ3QROA.js → chunk-E3OKRZCH.js} +2 -2
  67. package/dist/cli/chunks/{chunk-MX35PIGJ.js → chunk-E7MD5LHC.js} +2 -2
  68. package/dist/cli/chunks/{chunk-7PHF2JM3.js → chunk-EKWEJOV7.js} +1 -1
  69. package/dist/cli/chunks/chunk-EP4ORDFE.js +2 -0
  70. package/dist/cli/chunks/{chunk-PDOL3FGO.js → chunk-EVJSK56E.js} +3 -3
  71. package/dist/cli/chunks/{chunk-42KQE5H6.js → chunk-EY44JDUL.js} +3 -3
  72. package/dist/cli/chunks/{chunk-BX5MY65W.js → chunk-EYHRYIBX.js} +1 -1
  73. package/dist/cli/chunks/{chunk-PEHSTLU7.js → chunk-EYWR4Y3J.js} +1 -1
  74. package/dist/cli/chunks/{chunk-4Z7JP7CD.js → chunk-F66FYZQF.js} +2 -2
  75. package/dist/cli/chunks/{chunk-QIHKSRUZ.js → chunk-FGQH5LOG.js} +2 -2
  76. package/dist/cli/chunks/{chunk-7BLXINIL.js → chunk-FH6H4KOZ.js} +17 -17
  77. package/dist/cli/chunks/{chunk-WDDU4I5Z.js → chunk-FV47SYXK.js} +1 -1
  78. package/dist/cli/chunks/chunk-GA7PUAMT.js +2 -0
  79. package/dist/cli/chunks/{chunk-ZE3WS57T.js → chunk-GEH3S5DI.js} +2 -2
  80. package/dist/cli/chunks/{chunk-SN57SNLU.js → chunk-GQCYO54W.js} +2 -2
  81. package/dist/cli/chunks/{chunk-JOJ2UFHM.js → chunk-GSZL3WST.js} +2 -2
  82. package/dist/cli/chunks/{chunk-PNDWHSZO.js → chunk-GV3C224P.js} +2 -2
  83. package/dist/cli/chunks/{chunk-RDHBUCKQ.js → chunk-HBNMEYJS.js} +10 -10
  84. package/dist/cli/chunks/{chunk-54C3OHES.js → chunk-HPRX5S74.js} +1 -1
  85. package/dist/cli/chunks/{chunk-76OWM3ZO.js → chunk-HWWMINXV.js} +2 -2
  86. package/dist/cli/chunks/{chunk-UWM4CCK7.js → chunk-IHUAEQZN.js} +1 -1
  87. package/dist/cli/chunks/{chunk-WSSFH23M.js → chunk-ISOTSVI7.js} +1 -1
  88. package/dist/cli/chunks/{chunk-3EWWP3AO.js → chunk-JDADNBWS.js} +1 -1
  89. package/dist/cli/chunks/{chunk-ZUIPUO7Q.js → chunk-JGQZ7ECC.js} +1 -1
  90. package/dist/cli/chunks/{chunk-UUFLYBUO.js → chunk-JH6KUV74.js} +2 -2
  91. package/dist/cli/chunks/{chunk-3XKCC7LE.js → chunk-JPJSOS4H.js} +1 -1
  92. package/dist/cli/chunks/{chunk-2QI3OJAC.js → chunk-JQXAWTS5.js} +3 -3
  93. package/dist/cli/chunks/{chunk-WZI2REDL.js → chunk-K7ZFBGLE.js} +2 -2
  94. package/dist/cli/chunks/{chunk-DVYNBMMP.js → chunk-KBHSID6C.js} +2 -2
  95. package/dist/cli/chunks/{chunk-ZMA5OWIQ.js → chunk-KHDE4KT5.js} +4 -4
  96. package/dist/cli/chunks/{chunk-64GTU5LR.js → chunk-KMCI3RGD.js} +2 -2
  97. package/dist/cli/chunks/{chunk-NFE4RV2Q.js → chunk-LGP26FTM.js} +2 -2
  98. package/dist/cli/chunks/{chunk-6RV3W2UZ.js → chunk-LLVXOXAK.js} +1 -1
  99. package/dist/cli/chunks/{chunk-VE5STFDP.js → chunk-LQYAJ7RR.js} +2 -2
  100. package/dist/cli/chunks/{chunk-GHSP4AC5.js → chunk-LVLGRUUJ.js} +1 -1
  101. package/dist/cli/chunks/{chunk-ZWLFEZQC.js → chunk-LYGHX4II.js} +1 -1
  102. package/dist/cli/chunks/{chunk-557BFPDB.js → chunk-MOIKR7RU.js} +2 -2
  103. package/dist/cli/chunks/{chunk-M7456ZW5.js → chunk-MSA6MD5C.js} +1 -1
  104. package/dist/cli/chunks/{chunk-LARAXKTZ.js → chunk-MTEEFP6V.js} +2 -2
  105. package/dist/cli/chunks/{chunk-THQ5ZBWP.js → chunk-N6QUDQ5H.js} +2 -2
  106. package/dist/cli/chunks/{chunk-4E2NA2GY.js → chunk-N7JRGAJF.js} +2 -2
  107. package/dist/cli/chunks/{chunk-FQPYD6YE.js → chunk-NNIAUDHF.js} +1 -1
  108. package/dist/cli/chunks/{chunk-AX4XIG4G.js → chunk-NUCVMWDJ.js} +2 -2
  109. package/dist/cli/chunks/{chunk-5YIGAWBO.js → chunk-NUDDFJYU.js} +2 -2
  110. package/dist/cli/chunks/{chunk-R4VDRE75.js → chunk-NX6FOAS4.js} +1 -1
  111. package/dist/cli/chunks/{chunk-HZV3J4VQ.js → chunk-O34674VM.js} +2 -2
  112. package/dist/cli/chunks/{chunk-Q3J5OTZ2.js → chunk-OIGWREK7.js} +1 -1
  113. package/dist/cli/chunks/{chunk-AAGOBPIJ.js → chunk-OS56PKRO.js} +2 -2
  114. package/dist/cli/chunks/{chunk-YSWI3APU.js → chunk-P4CHYYJN.js} +2 -2
  115. package/dist/cli/chunks/{chunk-AKYOY5KR.js → chunk-P6A35LKJ.js} +2 -2
  116. package/dist/cli/chunks/{chunk-MF6OT43N.js → chunk-PA6SUNDD.js} +1 -1
  117. package/dist/cli/chunks/{chunk-HMNBNGNO.js → chunk-PGDDPZ7W.js} +1 -1
  118. package/dist/cli/chunks/{chunk-L6H4MWVN.js → chunk-PLYGIUFO.js} +2 -2
  119. package/dist/cli/chunks/{chunk-JID7JO7K.js → chunk-POZ3S4UO.js} +2 -2
  120. package/dist/cli/chunks/{chunk-FYWTMDID.js → chunk-PSAXLKDZ.js} +2 -2
  121. package/dist/cli/chunks/{chunk-74QRMQFR.js → chunk-PTBW2QXE.js} +2 -2
  122. package/dist/cli/chunks/{chunk-BUN4WBPW.js → chunk-PW3JLQGH.js} +2 -2
  123. package/dist/cli/chunks/{chunk-6H3I36DL.js → chunk-PX7MVV6F.js} +2 -2
  124. package/dist/cli/chunks/{chunk-CPIAZGHF.js → chunk-Q4RU4XG6.js} +2 -2
  125. package/dist/cli/chunks/{chunk-EGI6SKQD.js → chunk-QQA4N3YT.js} +4 -4
  126. package/dist/cli/chunks/chunk-QSO5RFJ4.js +15 -0
  127. package/dist/cli/chunks/{chunk-YIEMVVUH.js → chunk-R2GHZ2QG.js} +2 -2
  128. package/dist/cli/chunks/{chunk-JX5IY2YK.js → chunk-R5FSKAS3.js} +1 -1
  129. package/dist/cli/chunks/{chunk-KRCIC4JK.js → chunk-R5LDNZVB.js} +2 -2
  130. package/dist/cli/chunks/{chunk-RGBYJAKQ.js → chunk-RBNSZFVL.js} +3 -3
  131. package/dist/cli/chunks/{chunk-ZOD37GNG.js → chunk-RDSO3R2R.js} +3 -3
  132. package/dist/cli/chunks/{chunk-7M4X6WTF.js → chunk-SZO6JIFM.js} +2 -2
  133. package/dist/cli/chunks/{chunk-QHX7VLVT.js → chunk-TGSL4OOT.js} +2 -2
  134. package/dist/cli/chunks/{chunk-U5GGDJ44.js → chunk-THW6LF5I.js} +2 -2
  135. package/dist/cli/chunks/{chunk-APMLMLSL.js → chunk-TMM5NKPI.js} +1 -1
  136. package/dist/cli/chunks/{chunk-XNGYWOAK.js → chunk-TWNXZOJY.js} +2 -2
  137. package/dist/cli/chunks/{chunk-DIRFXY3J.js → chunk-U63JEFF5.js} +2 -2
  138. package/dist/cli/chunks/{chunk-IS3P5VBL.js → chunk-UHQA6EH6.js} +2 -2
  139. package/dist/cli/chunks/{chunk-WLY2J6JP.js → chunk-UN2MXDJT.js} +2 -2
  140. package/dist/cli/chunks/{chunk-YU4U3BUY.js → chunk-UNLH7NPY.js} +1 -1
  141. package/dist/cli/chunks/{chunk-43BXSNKU.js → chunk-V4QQTPZF.js} +2 -2
  142. package/dist/cli/chunks/{chunk-AJYJFIKO.js → chunk-V5MS6XNT.js} +2 -2
  143. package/dist/cli/chunks/{chunk-CD4YWKJ2.js → chunk-VK5I4JSN.js} +2 -2
  144. package/dist/cli/chunks/{chunk-TU5S33SD.js → chunk-VSP2IB5N.js} +2 -2
  145. package/dist/cli/chunks/{chunk-VRV7CXEM.js → chunk-WA553ALQ.js} +1 -1
  146. package/dist/cli/chunks/{chunk-YG45ZONW.js → chunk-X3CHYV7G.js} +2 -2
  147. package/dist/cli/chunks/{chunk-PKCVQ2I4.js → chunk-X75OYPS6.js} +1 -1
  148. package/dist/cli/chunks/{chunk-V2T7QEPV.js → chunk-XF2TKGSC.js} +1 -1
  149. package/dist/cli/chunks/{chunk-2XZWYKXQ.js → chunk-XLDEWLP4.js} +1 -1
  150. package/dist/cli/chunks/{chunk-EXXWOOUL.js → chunk-XRH2D6JV.js} +3 -3
  151. package/dist/cli/chunks/{chunk-RKXN5TVS.js → chunk-XZPAKAFJ.js} +1 -1
  152. package/dist/cli/chunks/{chunk-G73XY2NK.js → chunk-Y2QZK46R.js} +2 -2
  153. package/dist/cli/chunks/{chunk-SQDHFTGQ.js → chunk-YL7CAOQG.js} +3 -3
  154. package/dist/cli/chunks/{chunk-BI6OTPC6.js → chunk-YOVQBSTW.js} +2 -2
  155. package/dist/cli/chunks/{chunk-7LR4VP2I.js → chunk-YQUZGPUQ.js} +1 -1
  156. package/dist/cli/chunks/{chunk-7A4EXSMN.js → chunk-YRRYKR7U.js} +2 -2
  157. package/dist/cli/chunks/{chunk-23AO43XW.js → chunk-Z6SAS2NU.js} +1 -1
  158. package/dist/cli/chunks/{ci-IRCNFD32.js → ci-MWQVCZ2W.js} +2 -2
  159. package/dist/cli/chunks/{ci-output-NFOUNDJ2.js → ci-output-ZCH4IZ7H.js} +2 -2
  160. package/dist/cli/chunks/{circuit-breaker-GB7SQRD2.js → circuit-breaker-N3VSQM5X.js} +2 -2
  161. package/dist/cli/chunks/{claude-flow-setup-STFKPPVL.js → claude-flow-setup-TSJFOGXN.js} +2 -2
  162. package/dist/cli/chunks/client-IEN43WBH.js +2 -0
  163. package/dist/cli/chunks/{cline-installer-MLKKIHIV.js → cline-installer-OHKWAB4I.js} +2 -2
  164. package/dist/cli/chunks/{code-ZRCJC42H.js → code-3UTIL3QR.js} +2 -2
  165. package/dist/cli/chunks/{code-index-extractor-VWDYYQY2.js → code-index-extractor-TVG2V2NY.js} +2 -2
  166. package/dist/cli/chunks/{codex-installer-I5BTWYQV.js → codex-installer-L6ZOTOO2.js} +2 -2
  167. package/dist/cli/chunks/{completions-5JCAFTQV.js → completions-SFRB664X.js} +2 -2
  168. package/dist/cli/chunks/{complexity-analyzer-6JLLAPGO.js → complexity-analyzer-HDZKVO6D.js} +2 -2
  169. package/dist/cli/chunks/{continuedev-installer-YBOLMUZR.js → continuedev-installer-HKLZR3UO.js} +2 -2
  170. package/dist/cli/chunks/{copilot-installer-GDBJZBXS.js → copilot-installer-5P3LX3C5.js} +2 -2
  171. package/dist/cli/chunks/core-handlers-PBITKHVP.js +2 -0
  172. package/dist/cli/chunks/{cost-tracker-NEAVGEZI.js → cost-tracker-MZR5RB6E.js} +2 -2
  173. package/dist/cli/chunks/{coverage-DXS5XNAA.js → coverage-L6V6NFIM.js} +3 -3
  174. package/dist/cli/chunks/cross-domain-router-JGCWQ7BO.js +2 -0
  175. package/dist/cli/chunks/{cursor-installer-3KEMFIFA.js → cursor-installer-FD6DT23Y.js} +2 -2
  176. package/dist/cli/chunks/{daemon-JN377KTA.js → daemon-HTSRODRG.js} +4 -4
  177. package/dist/cli/chunks/{daemon-FT2J6VY4.js → daemon-I5ESGZGX.js} +3 -3
  178. package/dist/cli/chunks/{dag-attention-scheduler-EJFEWFXI.js → dag-attention-scheduler-JPTHWB2Q.js} +2 -2
  179. package/dist/cli/chunks/{detect-E5MN6N3L.js → detect-RTUZDBEZ.js} +2 -2
  180. package/dist/cli/chunks/{dist-node-ZFSAQMFD.js → dist-node-5HLWHNYA.js} +2 -2
  181. package/dist/cli/chunks/{domain-handler-S7VFZ2MY.js → domain-handler-R7IPUX54.js} +2 -2
  182. package/dist/cli/chunks/{domain-transfer-LGHT3FN4.js → domain-transfer-E3I2LMCB.js} +2 -2
  183. package/dist/cli/chunks/dream-52MPUF5Q.js +2 -0
  184. package/dist/cli/chunks/{embed-and-insert-pattern-OVQS6IKK.js → embed-and-insert-pattern-BXUWG73R.js} +2 -2
  185. package/dist/cli/chunks/{eval-45UWDD2R.js → eval-3ZFM75YA.js} +2 -2
  186. package/dist/cli/chunks/{experience-capture-middleware-XDRJSNPY.js → experience-capture-middleware-NJ3BT657.js} +3 -3
  187. package/dist/cli/chunks/{fast-paths-VEDCJL75.js → fast-paths-Q3V5C5IM.js} +2 -2
  188. package/dist/cli/chunks/{feature-flags-NOTQVBLP.js → feature-flags-D3JGPHXY.js} +2 -2
  189. package/dist/cli/chunks/{feature-flags-TGA3NWVL.js → feature-flags-XZGJNPZ7.js} +2 -2
  190. package/dist/cli/chunks/{file-discovery-AHMR6IGX.js → file-discovery-MZOYXIOS.js} +2 -2
  191. package/dist/cli/chunks/{fleet-CQBUCH2S.js → fleet-FG3EBA75.js} +3 -3
  192. package/dist/cli/chunks/{gnn-wrapper-SOZCIONJ.js → gnn-wrapper-PKZLZHL2.js} +2 -2
  193. package/dist/cli/chunks/{heartbeat-handler-6XNV4DGM.js → heartbeat-handler-YZTRVH75.js} +4 -4
  194. package/dist/cli/chunks/heartbeat-scheduler-LMAEJQYQ.js +2 -0
  195. package/dist/cli/chunks/hnsw-adapter-DGGDYJEL.js +2 -0
  196. package/dist/cli/chunks/hnsw-index-KA7WDTHX.js +2 -0
  197. package/dist/cli/chunks/{hnsw-legacy-bridge-UILVP37N.js → hnsw-legacy-bridge-WONHB63F.js} +2 -2
  198. package/dist/cli/chunks/{hnswlib-node-OHJQOSAH.js → hnswlib-node-Q4VPSJJM.js} +2 -2
  199. package/dist/cli/chunks/{hooks-QVDOGEHG.js → hooks-RWX5ZZCE.js} +47 -47
  200. package/dist/cli/chunks/hybrid-router-Q6JQTV55.js +2 -0
  201. package/dist/cli/chunks/{hypergraph-engine-YMVPBXZS.js → hypergraph-engine-G6N24L5G.js} +2 -2
  202. package/dist/cli/chunks/{hypergraph-handler-SHUNZXUK.js → hypergraph-handler-4RGOLL6F.js} +3 -3
  203. package/dist/cli/chunks/impact-analyzer-7LFSGIQP.js +2 -0
  204. package/dist/cli/chunks/{init-handler-JE5FYJAV.js → init-handler-L7DZAHXO.js} +6 -6
  205. package/dist/cli/chunks/init-wizard-T4K44J6D.js +2 -0
  206. package/dist/cli/chunks/kernel-TGHK6X7F.js +2 -0
  207. package/dist/cli/chunks/{kilocode-installer-TVP4YOOK.js → kilocode-installer-G7PUCUDZ.js} +2 -2
  208. package/dist/cli/chunks/{kiro-installer-XBSGANX7.js → kiro-installer-H6234HEB.js} +2 -2
  209. package/dist/cli/chunks/knowledge-graph-MV3OSGCB.js +2 -0
  210. package/dist/cli/chunks/learning-346CA4DH.js +119 -0
  211. package/dist/cli/chunks/{llm-router-FXXJHARR.js → llm-router-ATNRDTEM.js} +4 -4
  212. package/dist/cli/chunks/llm-router-service-OOCNAPJO.js +2 -0
  213. package/dist/cli/chunks/{load-IVF6G2SK.js → load-3L2CK4ML.js} +2 -2
  214. package/dist/cli/chunks/load-test-4OZPYWL4.js +2 -0
  215. package/dist/cli/chunks/{mcp-VXSDVG3H.js → mcp-JJ4ZDUJB.js} +2 -2
  216. package/dist/cli/chunks/{memory-BINJV3M6.js → memory-U3K2Y777.js} +5 -5
  217. package/dist/cli/chunks/memory-backend-LMRIHJQY.js +2 -0
  218. package/dist/cli/chunks/memory-handlers-J6CVQ5DS.js +2 -0
  219. package/dist/cli/chunks/{multi-model-executor-RJHYK6JI.js → multi-model-executor-DPCU4CSM.js} +2 -2
  220. package/dist/cli/chunks/{opencode-installer-VCTF5ETL.js → opencode-installer-KNUCUSRG.js} +2 -2
  221. package/dist/cli/chunks/{orchestrator-5SKZ2BOK.js → orchestrator-DJV2NUWD.js} +5 -5
  222. package/dist/cli/chunks/pattern-null-store-AQWPHLRW.js +2 -0
  223. package/dist/cli/chunks/{pattern-usage-recorder-AY2DAOQO.js → pattern-usage-recorder-TQ7KECBB.js} +2 -2
  224. package/dist/cli/chunks/{pipeline-EMBMC75N.js → pipeline-JG57VFOB.js} +2 -2
  225. package/dist/cli/chunks/{platform-GADIFXCI.js → platform-L7LOBG4E.js} +2 -2
  226. package/dist/cli/chunks/{plugin-Q234ZAAY.js → plugin-ATBPEU2K.js} +2 -2
  227. package/dist/cli/chunks/{prime-radiant-advanced-wasm-CXXKYB2P.js → prime-radiant-advanced-wasm-XCX7CNVW.js} +2 -2
  228. package/dist/cli/chunks/protocol-executor-FWUT6L6K.js +2 -0
  229. package/dist/cli/chunks/{protocol-handler-ZZRFBVNA.js → protocol-handler-DOFLSB4N.js} +2 -2
  230. package/dist/cli/chunks/{prove-7674ATXK.js → prove-CDBMRPBD.js} +2 -2
  231. package/dist/cli/chunks/provider-manager-4PY7IR3V.js +2 -0
  232. package/dist/cli/chunks/qe-reasoning-bank-M4XVWRPY.js +2 -0
  233. package/dist/cli/chunks/{quality-QCIGVN2S.js → quality-5CMQBYP3.js} +2 -2
  234. package/dist/cli/chunks/{quality-gate-AKV564GE.js → quality-gate-LU66IWRT.js} +3 -3
  235. package/dist/cli/chunks/queen-coordinator-KSRI42QZ.js +2 -0
  236. package/dist/cli/chunks/{real-embeddings-74POUVMX.js → real-embeddings-3B7AXYOP.js} +2 -2
  237. package/dist/cli/chunks/{roocode-installer-INBL5AG7.js → roocode-installer-GF4YJW7E.js} +2 -2
  238. package/dist/cli/chunks/router-F2TCXNSG.js +2 -0
  239. package/dist/cli/chunks/routing-feedback-VHOWXUY7.js +2 -0
  240. package/dist/cli/chunks/{routing-handler-C7HMM7RL.js → routing-handler-PWQMWFND.js} +2 -2
  241. package/dist/cli/chunks/{ruvector-commands-PT6LRVCW.js → ruvector-commands-SMD6KSBD.js} +2 -2
  242. package/dist/cli/chunks/{rvf-dual-writer-PRKROTP3.js → rvf-dual-writer-M5TEJ56X.js} +2 -2
  243. package/dist/cli/chunks/{rvf-migration-adapter-ZI2XW4UX.js → rvf-migration-adapter-EHLWMZYI.js} +2 -2
  244. package/dist/cli/chunks/{rvf-migration-coordinator-5JTGP35V.js → rvf-migration-coordinator-GMVLX3FX.js} +2 -2
  245. package/dist/cli/chunks/rvf-native-adapter-XG3LFOYW.js +2 -0
  246. package/dist/cli/chunks/{rvf-store-integrity-3B5TZTFR.js → rvf-store-integrity-PDADEHAZ.js} +2 -2
  247. package/dist/cli/chunks/safe-db-CTHJ3SXC.js +2 -0
  248. package/dist/cli/chunks/schedule-LLYADLGL.js +2 -0
  249. package/dist/cli/chunks/scheduler-72YIGDIX.js +2 -0
  250. package/dist/cli/chunks/{security-IMIWSAHW.js → security-PSMBTUSM.js} +3 -3
  251. package/dist/cli/chunks/{shared-rvf-adapter-UDKJNX6I.js → shared-rvf-adapter-DP2Z4YLV.js} +2 -2
  252. package/dist/cli/chunks/{shared-rvf-dual-writer-FQOBQ6S5.js → shared-rvf-dual-writer-UOU6ORBJ.js} +2 -2
  253. package/dist/cli/chunks/sqlite-persistence-N7OO3ZOE.js +2 -0
  254. package/dist/cli/chunks/{status-handler-7WON7M7F.js → status-handler-T565F47D.js} +2 -2
  255. package/dist/cli/chunks/{structural-health-JTKTO3A4.js → structural-health-54WNSZ7Y.js} +2 -2
  256. package/dist/cli/chunks/{sync-6ABYTAOL.js → sync-5ZGYF7JF.js} +2 -2
  257. package/dist/cli/chunks/{sync-UJSHBY3B.js → sync-EXADT5IZ.js} +2 -2
  258. package/dist/cli/chunks/{task-handler-5TZNOCCB.js → task-handler-JXWQZDEX.js} +2 -2
  259. package/dist/cli/chunks/{task-handlers-G7ZUGBHM.js → task-handlers-UKHRILMM.js} +3 -3
  260. package/dist/cli/chunks/{test-BSJ6MVTG.js → test-3SU56PMM.js} +4 -4
  261. package/dist/cli/chunks/{test-scheduling-OSJJXIYQ.js → test-scheduling-CZZ4KKWM.js} +3 -3
  262. package/dist/cli/chunks/{token-bootstrap-MRNFR4YI.js → token-bootstrap-RSIAPUIV.js} +2 -2
  263. package/dist/cli/chunks/{token-usage-YQN7ND7G.js → token-usage-7HW43ORO.js} +2 -2
  264. package/dist/cli/chunks/{transformers-QL3AG25C.js → transformers-A5REG7OI.js} +2 -2
  265. package/dist/cli/chunks/{tree-sitter-wasm-parser-BECZRRZP.js → tree-sitter-wasm-parser-F43MC7E5.js} +2 -2
  266. package/dist/cli/chunks/{types-FQSNLPWS.js → types-DEOHTTJ3.js} +2 -2
  267. package/dist/cli/chunks/unified-memory-Q55MJWAM.js +2 -0
  268. package/dist/cli/chunks/unified-memory-hnsw-4BEKV2K5.js +2 -0
  269. package/dist/cli/chunks/unified-persistence-IIB5MR67.js +2 -0
  270. package/dist/cli/chunks/{upgrade-2ICXXV6D.js → upgrade-7NKNCL2I.js} +2 -2
  271. package/dist/cli/chunks/{validate-LPAUH2F4.js → validate-SN2UY7CT.js} +2 -2
  272. package/dist/cli/chunks/{validate-swarm-VWVE2GM7.js → validate-swarm-YITFMCXY.js} +2 -2
  273. package/dist/cli/chunks/{vibium-U3LBEI4K.js → vibium-AZNIG6O7.js} +2 -2
  274. package/dist/cli/chunks/visual-security-F4FUP6KV.js +2 -0
  275. package/dist/cli/chunks/{web-tree-sitter-QGZXQPXU.js → web-tree-sitter-DY4YXPMR.js} +2 -2
  276. package/dist/cli/chunks/{windsurf-installer-GGLQJWUI.js → windsurf-installer-HXD4BK7N.js} +2 -2
  277. package/dist/cli/chunks/witness-chain-SQ5LCKUQ.js +2 -0
  278. package/dist/cli/chunks/{witness-chain-47A2AXUS.js → witness-chain-UV7BOO6T.js} +2 -2
  279. package/dist/cli/chunks/{witness-key-manager-FVS7UOWM.js → witness-key-manager-BCNW3SZH.js} +2 -2
  280. package/dist/cli/chunks/{workflow-KIZPLTYW.js → workflow-R3SSSWA5.js} +4 -4
  281. package/dist/cli/chunks/workflow-orchestrator-Z4PZXWVY.js +2 -0
  282. package/dist/cli/chunks/{wrappers-ER6XCMT6.js → wrappers-6JUXYAML.js} +2 -2
  283. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +16 -27
  284. package/dist/cli/commands/learning.js +66 -0
  285. package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.d.ts +2 -0
  286. package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.js +14 -0
  287. package/dist/kernel/hybrid-backend.d.ts +1 -1
  288. package/dist/kernel/hybrid-backend.js +2 -2
  289. package/dist/kernel/interfaces.d.ts +2 -2
  290. package/dist/kernel/memory-backend.d.ts +1 -1
  291. package/dist/kernel/memory-backend.js +3 -1
  292. package/dist/kernel/unified-memory.d.ts +1 -1
  293. package/dist/kernel/unified-memory.js +19 -4
  294. package/dist/learning/real-embeddings.js +1 -1
  295. package/dist/learning/sqlite-persistence.d.ts +3 -2
  296. package/dist/learning/sqlite-persistence.js +7 -8
  297. package/dist/mcp/bundle.js +228 -228
  298. package/dist/mcp/handlers/memory-handlers.js +2 -5
  299. package/package.json +1 -1
  300. package/dist/cli/chunks/adapter-QGJAFSG5.js +0 -2
  301. package/dist/cli/chunks/aqe-learning-engine-ZU735SG7.js +0 -2
  302. package/dist/cli/chunks/base-EKTX2PRE.js +0 -2
  303. package/dist/cli/chunks/browser-workflow-BUPIMI3E.js +0 -2
  304. package/dist/cli/chunks/chunk-ELKWYWTD.js +0 -2
  305. package/dist/cli/chunks/chunk-WAELEQP5.js +0 -2
  306. package/dist/cli/chunks/chunk-X53GJW2E.js +0 -15
  307. package/dist/cli/chunks/client-M4WF22UT.js +0 -2
  308. package/dist/cli/chunks/core-handlers-3MNFXL44.js +0 -2
  309. package/dist/cli/chunks/cross-domain-router-Q5X6ZLJY.js +0 -2
  310. package/dist/cli/chunks/dream-5QB6JABW.js +0 -2
  311. package/dist/cli/chunks/heartbeat-scheduler-ZRLIMPKO.js +0 -2
  312. package/dist/cli/chunks/hnsw-adapter-R4VAEQ2B.js +0 -2
  313. package/dist/cli/chunks/hnsw-index-GTUOS6DF.js +0 -2
  314. package/dist/cli/chunks/hybrid-router-CYEXFWDT.js +0 -2
  315. package/dist/cli/chunks/impact-analyzer-HMJ7LAXR.js +0 -2
  316. package/dist/cli/chunks/init-wizard-OIK6S3PQ.js +0 -2
  317. package/dist/cli/chunks/kernel-NZCGR72Y.js +0 -2
  318. package/dist/cli/chunks/knowledge-graph-HA7XW46B.js +0 -2
  319. package/dist/cli/chunks/learning-O4ZXQVRE.js +0 -117
  320. package/dist/cli/chunks/llm-router-service-FVGQSXYC.js +0 -2
  321. package/dist/cli/chunks/load-test-IQTO35GE.js +0 -2
  322. package/dist/cli/chunks/memory-backend-YGSOJ7SI.js +0 -2
  323. package/dist/cli/chunks/memory-handlers-BJNFJZFP.js +0 -2
  324. package/dist/cli/chunks/pattern-null-store-4WN5O2PF.js +0 -2
  325. package/dist/cli/chunks/protocol-executor-EYTJXPXY.js +0 -2
  326. package/dist/cli/chunks/provider-manager-TM3JHYLL.js +0 -2
  327. package/dist/cli/chunks/qe-reasoning-bank-6JLFP3HE.js +0 -2
  328. package/dist/cli/chunks/queen-coordinator-OKGOKGHI.js +0 -2
  329. package/dist/cli/chunks/router-J45OF4SP.js +0 -2
  330. package/dist/cli/chunks/routing-feedback-VTZFH57X.js +0 -2
  331. package/dist/cli/chunks/rvf-native-adapter-BDPUBFNP.js +0 -2
  332. package/dist/cli/chunks/safe-db-FHJBWJIB.js +0 -2
  333. package/dist/cli/chunks/schedule-LP7YYT4P.js +0 -2
  334. package/dist/cli/chunks/scheduler-BOZWGKJG.js +0 -2
  335. package/dist/cli/chunks/sqlite-persistence-TDM36AHF.js +0 -2
  336. package/dist/cli/chunks/unified-memory-6PHUOZRH.js +0 -2
  337. package/dist/cli/chunks/unified-memory-hnsw-WYSFH3PS.js +0 -2
  338. package/dist/cli/chunks/unified-persistence-QBGHDCCO.js +0 -2
  339. package/dist/cli/chunks/visual-security-LH7DRCDS.js +0 -2
  340. package/dist/cli/chunks/witness-chain-2BDZOPJ2.js +0 -2
  341. package/dist/cli/chunks/workflow-orchestrator-UYOPFK2T.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.13.5");process.exit(0)}
2
- import{i as e}from"./chunk-V2T7QEPV.js";function g(t,n,r,a){return{id:e(),type:t,timestamp:new Date,source:n,correlationId:a,payload:r}}var i={TestGenerated:"test-generation.TestGenerated",TestSuiteCreated:"test-generation.TestSuiteCreated",PatternLearned:"test-generation.PatternLearned",GenerationFailed:"test-generation.GenerationFailed"},s={TestRunStarted:"test-execution.TestRunStarted",TestRunCompleted:"test-execution.TestRunCompleted",FlakyTestDetected:"test-execution.FlakyTestDetected",RetryTriggered:"test-execution.RetryTriggered"},o={CoverageReportCreated:"coverage-analysis.CoverageReportCreated",CoverageGapDetected:"coverage-analysis.CoverageGapDetected",RiskZoneIdentified:"coverage-analysis.RiskZoneIdentified"},d={QualityGateEvaluated:"quality-assessment.QualityGateEvaluated",DeploymentApproved:"quality-assessment.DeploymentApproved",DeploymentBlocked:"quality-assessment.DeploymentBlocked"},l={DefectPredicted:"defect-intelligence.DefectPredicted",RootCauseIdentified:"defect-intelligence.RootCauseIdentified",RegressionRiskAnalyzed:"defect-intelligence.RegressionRiskAnalyzed"},c={KnowledgeGraphUpdated:"code-intelligence.KnowledgeGraphUpdated",ImpactAnalysisCompleted:"code-intelligence.ImpactAnalysisCompleted",SemanticSearchCompleted:"code-intelligence.SemanticSearchCompleted",C4DiagramsGenerated:"code-intelligence.C4DiagramsGenerated"},m={VulnerabilityDetected:"security-compliance.VulnerabilityDetected",ComplianceValidated:"security-compliance.ComplianceValidated",SecurityAuditCompleted:"security-compliance.SecurityAuditCompleted"},p={PatternConsolidated:"learning-optimization.PatternConsolidated",TransferCompleted:"learning-optimization.TransferCompleted",OptimizationApplied:"learning-optimization.OptimizationApplied",DreamCycleCompleted:"learning-optimization.dream.completed"},y={...i,...s,...o,...d,...l,...c,...m,...p};export{g as a,i as b,s as c,o as d,d as e,l as f,c as g,m as h,p as i};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.6");process.exit(0)}
2
+ import{i as e}from"./chunk-XF2TKGSC.js";function g(t,n,r,a){return{id:e(),type:t,timestamp:new Date,source:n,correlationId:a,payload:r}}var i={TestGenerated:"test-generation.TestGenerated",TestSuiteCreated:"test-generation.TestSuiteCreated",PatternLearned:"test-generation.PatternLearned",GenerationFailed:"test-generation.GenerationFailed"},s={TestRunStarted:"test-execution.TestRunStarted",TestRunCompleted:"test-execution.TestRunCompleted",FlakyTestDetected:"test-execution.FlakyTestDetected",RetryTriggered:"test-execution.RetryTriggered"},o={CoverageReportCreated:"coverage-analysis.CoverageReportCreated",CoverageGapDetected:"coverage-analysis.CoverageGapDetected",RiskZoneIdentified:"coverage-analysis.RiskZoneIdentified"},d={QualityGateEvaluated:"quality-assessment.QualityGateEvaluated",DeploymentApproved:"quality-assessment.DeploymentApproved",DeploymentBlocked:"quality-assessment.DeploymentBlocked"},l={DefectPredicted:"defect-intelligence.DefectPredicted",RootCauseIdentified:"defect-intelligence.RootCauseIdentified",RegressionRiskAnalyzed:"defect-intelligence.RegressionRiskAnalyzed"},c={KnowledgeGraphUpdated:"code-intelligence.KnowledgeGraphUpdated",ImpactAnalysisCompleted:"code-intelligence.ImpactAnalysisCompleted",SemanticSearchCompleted:"code-intelligence.SemanticSearchCompleted",C4DiagramsGenerated:"code-intelligence.C4DiagramsGenerated"},m={VulnerabilityDetected:"security-compliance.VulnerabilityDetected",ComplianceValidated:"security-compliance.ComplianceValidated",SecurityAuditCompleted:"security-compliance.SecurityAuditCompleted"},p={PatternConsolidated:"learning-optimization.PatternConsolidated",TransferCompleted:"learning-optimization.TransferCompleted",OptimizationApplied:"learning-optimization.OptimizationApplied",DreamCycleCompleted:"learning-optimization.dream.completed"},y={...i,...s,...o,...d,...l,...c,...m,...p};export{g as a,i as b,s as c,o as d,d as e,l as f,c as g,m as h,p as i};
@@ -1 +1 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.5");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.6");process.exit(0)}
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.5");process.exit(0)}
2
- import{b as v}from"./chunk-NFE4RV2Q.js";import{a as he,c as ge}from"./chunk-R4VDRE75.js";import{a as se,b as Me}from"./chunk-4E2NA2GY.js";import{a}from"./chunk-APMLMLSL.js";import{d as fe}from"./chunk-7LR4VP2I.js";import{b as R,c as me}from"./chunk-7PHF2JM3.js";import{b as K,d as de}from"./chunk-OUWZTYRZ.js";import{b as E,c as L}from"./chunk-6ZCAZ3TR.js";import{b as pe,d as we}from"./chunk-6H3I36DL.js";we();L();var ye={failureThreshold:5,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,includeTimeouts:!0},ne=class{state="closed";failures=[];successCount=0;totalRequests=0;totalSuccesses=0;totalFailures=0;rejectedCount=0;lastFailureTime;lastSuccessTime;openedAt;halfOpenSuccesses=0;config;providerType;constructor(t,e={}){this.providerType=t,this.config={...ye,...e}}getState(){return this.state==="open"&&this.openedAt&&Date.now()-this.openedAt.getTime()>=this.config.resetTimeoutMs&&this.transitionTo("half-open"),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t!=="open"}async execute(t){if(this.totalRequests++,this.getState()==="open")throw this.rejectedCount++,a(`Circuit breaker is open for provider ${this.providerType}`,"CIRCUIT_OPEN",{provider:this.providerType,retryable:!0,retryAfterMs:this.getTimeUntilTransition()});try{let r=await t();return this.recordSuccess(),r}catch(r){throw this.recordFailure(E(r)),r}}recordSuccess(){this.successCount++,this.totalSuccesses++,this.lastSuccessTime=new Date,this.getState()==="half-open"&&(this.halfOpenSuccesses++,this.halfOpenSuccesses>=this.config.halfOpenSuccessThreshold&&this.transitionTo("closed"))}recordFailure(t){if(this.totalFailures++,this.lastFailureTime=new Date,(t.message.toLowerCase().includes("timeout")||t.name==="TimeoutError"||t.name==="AbortError")&&!this.config.includeTimeouts)return;this.failures.push({timestamp:new Date,error:t}),this.cleanOldFailures();let r=this.getState();if(r==="half-open"){this.transitionTo("open");return}r==="closed"&&this.failures.length>=this.config.failureThreshold&&this.transitionTo("open")}getStats(){return{state:this.getState(),totalRequests:this.totalRequests,successCount:this.totalSuccesses,failureCount:this.totalFailures,rejectedCount:this.rejectedCount,lastFailureTime:this.lastFailureTime,lastSuccessTime:this.lastSuccessTime,timeUntilTransitionMs:this.getTimeUntilTransition()}}reset(){this.state="closed",this.failures=[],this.successCount=0,this.halfOpenSuccesses=0,this.openedAt=void 0}forceOpen(){this.transitionTo("open")}forceHalfOpen(){this.transitionTo("half-open")}getRecentFailures(t=5){return this.failures.slice(-t).map(e=>`[${e.timestamp.toISOString()}] ${e.error.message}`)}transitionTo(t){if(this.state!==t)switch(this.state=t,t){case"open":this.openedAt=new Date,this.halfOpenSuccesses=0;break;case"half-open":this.halfOpenSuccesses=0;break;case"closed":this.failures=[],this.openedAt=void 0,this.halfOpenSuccesses=0;break}}cleanOldFailures(){let t=Date.now()-this.config.failureWindowMs;this.failures=this.failures.filter(e=>e.timestamp.getTime()>t)}getTimeUntilTransition(){if(this.state==="open"&&this.openedAt){let t=Date.now()-this.openedAt.getTime(),e=this.config.resetTimeoutMs-t;return Math.max(0,e)}}},q=class{breakers=new Map;defaultConfig;constructor(t={}){this.defaultConfig={...ye,...t}}getBreaker(t,e){let r=this.breakers.get(t);return r||(r=new ne(t,{...this.defaultConfig,...e}),this.breakers.set(t,r)),r}getAllStats(){let t={};for(let[e,r]of this.breakers)t[e]=r.getStats();return t}getAvailableProviders(){let t=[];for(let[e,r]of this.breakers)r.canExecute()&&t.push(e);return t}resetAll(){for(let t of this.breakers.values())t.reset()}reset(t){let e=this.breakers.get(t);e&&e.reset()}};var be={maxSize:1e3,defaultTtlMs:36e5,enableLRU:!0,cacheGenerations:!0,cacheEmbeddings:!0,cacheCompletions:!0},M=class{cache=new Map;accessOrder=[];config;hits=0;misses=0;evictions=0;constructor(t={}){this.config={...be,...t}}static generateKey(t,e,r){let n=[t,r?.model??"default",String(r?.temperature??.7),String(r?.maxTokens??0),r?.systemPrompt??"",e].join("|"),s=0;for(let i=0;i<n.length;i++){let l=n.charCodeAt(i);s=(s<<5)-s+l,s=s&s}return`${t}:${Math.abs(s).toString(36)}`}get(t){let e=this.cache.get(t);if(!e){this.misses++;return}if(e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs){this.delete(t),this.misses++;return}return this.hits++,e.lastAccessedAt=new Date,e.accessCount++,this.config.enableLRU&&this.updateAccessOrder(t),e.value}set(t,e,r){this.cache.size>=this.config.maxSize&&!this.cache.has(t)&&this.evictLRU();let o={value:e,createdAt:new Date,lastAccessedAt:new Date,accessCount:1,ttlMs:r??this.config.defaultTtlMs,keyHash:t};this.cache.set(t,o),this.config.enableLRU&&this.updateAccessOrder(t)}has(t){let e=this.cache.get(t);return e?e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs?(this.delete(t),!1):!0:!1}delete(t){let e=this.cache.delete(t);if(e){let r=this.accessOrder.indexOf(t);r!==-1&&this.accessOrder.splice(r,1)}return e}clear(){this.cache.clear(),this.accessOrder=[],this.hits=0,this.misses=0,this.evictions=0}getStats(){let t=this.hits+this.misses,e=t>0?this.hits/t:0,r=0;for(let o of this.cache.values())r+=this.estimateSize(o.value);return{size:this.cache.size,maxSize:this.config.maxSize,hits:this.hits,misses:this.misses,hitRate:e,evictions:this.evictions,memoryUsageBytes:r}}keys(){return Array.from(this.cache.keys())}entries(){return Array.from(this.cache.entries())}import(t){for(let[e,r]of t)r.createdAt=new Date(r.createdAt),r.lastAccessedAt=new Date(r.lastAccessedAt),this.cache.set(e,r),this.accessOrder.push(e);for(;this.cache.size>this.config.maxSize;)this.evictLRU()}pruneExpired(){let t=Date.now(),e=0;for(let[r,o]of this.cache.entries())o.ttlMs>0&&t-o.createdAt.getTime()>o.ttlMs&&(this.delete(r),e++);return e}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e!==-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t)}evictLRU(){if(this.accessOrder.length===0){let e=this.cache.keys().next().value;e&&(this.cache.delete(e),this.evictions++);return}let t=this.accessOrder.shift();t&&(this.cache.delete(t),this.evictions++)}estimateSize(t){return t==null?0:JSON.stringify(t).length*2}},B=class{generationCache;embeddingCache;completionCache;config;constructor(t={}){this.config={...be,...t},this.generationCache=new M(t),this.embeddingCache=new M(t),this.completionCache=new M(t)}getGeneration(t,e){if(!this.config.cacheGenerations)return;let r=M.generateKey("generation",t,e);return this.generationCache.get(r)}setGeneration(t,e,r,o){if(!this.config.cacheGenerations)return;let n=M.generateKey("generation",t,r);this.generationCache.set(n,e,o)}getEmbedding(t,e){if(!this.config.cacheEmbeddings)return;let r=M.generateKey("embedding",t,e);return this.embeddingCache.get(r)}setEmbedding(t,e,r,o){if(!this.config.cacheEmbeddings)return;let n=M.generateKey("embedding",t,r);this.embeddingCache.set(n,e,o)}getCompletion(t,e){if(!this.config.cacheCompletions)return;let r=M.generateKey("completion",t,e);return this.completionCache.get(r)}setCompletion(t,e,r,o){if(!this.config.cacheCompletions)return;let n=M.generateKey("completion",t,r);this.completionCache.set(n,e,o)}getStats(){let t=this.generationCache.getStats(),e=this.embeddingCache.getStats(),r=this.completionCache.getStats(),o=t.hits+e.hits+r.hits,n=t.misses+e.misses+r.misses,s=o+n;return{generation:t,embedding:e,completion:r,total:{size:t.size+e.size+r.size,maxSize:this.config.maxSize*3,hits:o,misses:n,hitRate:s>0?o/s:0,evictions:t.evictions+e.evictions+r.evictions,memoryUsageBytes:t.memoryUsageBytes+e.memoryUsageBytes+r.memoryUsageBytes}}}clear(){this.generationCache.clear(),this.embeddingCache.clear(),this.completionCache.clear()}pruneExpired(){return this.generationCache.pruneExpired()+this.embeddingCache.pruneExpired()+this.completionCache.pruneExpired()}};var ie="(unattributed)",Ae=`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.6");process.exit(0)}
2
+ import{b as v}from"./chunk-LGP26FTM.js";import{a as he,c as ge}from"./chunk-NX6FOAS4.js";import{a as se,b as Me}from"./chunk-N7JRGAJF.js";import{a}from"./chunk-TMM5NKPI.js";import{d as fe}from"./chunk-YQUZGPUQ.js";import{b as R,c as me}from"./chunk-EKWEJOV7.js";import{b as K,d as de}from"./chunk-2VUXU22M.js";import{b as E,c as L}from"./chunk-6UPQD42K.js";import{b as pe,d as we}from"./chunk-PX7MVV6F.js";we();L();var ye={failureThreshold:5,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,includeTimeouts:!0},ne=class{state="closed";failures=[];successCount=0;totalRequests=0;totalSuccesses=0;totalFailures=0;rejectedCount=0;lastFailureTime;lastSuccessTime;openedAt;halfOpenSuccesses=0;config;providerType;constructor(t,e={}){this.providerType=t,this.config={...ye,...e}}getState(){return this.state==="open"&&this.openedAt&&Date.now()-this.openedAt.getTime()>=this.config.resetTimeoutMs&&this.transitionTo("half-open"),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t!=="open"}async execute(t){if(this.totalRequests++,this.getState()==="open")throw this.rejectedCount++,a(`Circuit breaker is open for provider ${this.providerType}`,"CIRCUIT_OPEN",{provider:this.providerType,retryable:!0,retryAfterMs:this.getTimeUntilTransition()});try{let r=await t();return this.recordSuccess(),r}catch(r){throw this.recordFailure(E(r)),r}}recordSuccess(){this.successCount++,this.totalSuccesses++,this.lastSuccessTime=new Date,this.getState()==="half-open"&&(this.halfOpenSuccesses++,this.halfOpenSuccesses>=this.config.halfOpenSuccessThreshold&&this.transitionTo("closed"))}recordFailure(t){if(this.totalFailures++,this.lastFailureTime=new Date,(t.message.toLowerCase().includes("timeout")||t.name==="TimeoutError"||t.name==="AbortError")&&!this.config.includeTimeouts)return;this.failures.push({timestamp:new Date,error:t}),this.cleanOldFailures();let r=this.getState();if(r==="half-open"){this.transitionTo("open");return}r==="closed"&&this.failures.length>=this.config.failureThreshold&&this.transitionTo("open")}getStats(){return{state:this.getState(),totalRequests:this.totalRequests,successCount:this.totalSuccesses,failureCount:this.totalFailures,rejectedCount:this.rejectedCount,lastFailureTime:this.lastFailureTime,lastSuccessTime:this.lastSuccessTime,timeUntilTransitionMs:this.getTimeUntilTransition()}}reset(){this.state="closed",this.failures=[],this.successCount=0,this.halfOpenSuccesses=0,this.openedAt=void 0}forceOpen(){this.transitionTo("open")}forceHalfOpen(){this.transitionTo("half-open")}getRecentFailures(t=5){return this.failures.slice(-t).map(e=>`[${e.timestamp.toISOString()}] ${e.error.message}`)}transitionTo(t){if(this.state!==t)switch(this.state=t,t){case"open":this.openedAt=new Date,this.halfOpenSuccesses=0;break;case"half-open":this.halfOpenSuccesses=0;break;case"closed":this.failures=[],this.openedAt=void 0,this.halfOpenSuccesses=0;break}}cleanOldFailures(){let t=Date.now()-this.config.failureWindowMs;this.failures=this.failures.filter(e=>e.timestamp.getTime()>t)}getTimeUntilTransition(){if(this.state==="open"&&this.openedAt){let t=Date.now()-this.openedAt.getTime(),e=this.config.resetTimeoutMs-t;return Math.max(0,e)}}},q=class{breakers=new Map;defaultConfig;constructor(t={}){this.defaultConfig={...ye,...t}}getBreaker(t,e){let r=this.breakers.get(t);return r||(r=new ne(t,{...this.defaultConfig,...e}),this.breakers.set(t,r)),r}getAllStats(){let t={};for(let[e,r]of this.breakers)t[e]=r.getStats();return t}getAvailableProviders(){let t=[];for(let[e,r]of this.breakers)r.canExecute()&&t.push(e);return t}resetAll(){for(let t of this.breakers.values())t.reset()}reset(t){let e=this.breakers.get(t);e&&e.reset()}};var be={maxSize:1e3,defaultTtlMs:36e5,enableLRU:!0,cacheGenerations:!0,cacheEmbeddings:!0,cacheCompletions:!0},M=class{cache=new Map;accessOrder=[];config;hits=0;misses=0;evictions=0;constructor(t={}){this.config={...be,...t}}static generateKey(t,e,r){let n=[t,r?.model??"default",String(r?.temperature??.7),String(r?.maxTokens??0),r?.systemPrompt??"",e].join("|"),s=0;for(let i=0;i<n.length;i++){let l=n.charCodeAt(i);s=(s<<5)-s+l,s=s&s}return`${t}:${Math.abs(s).toString(36)}`}get(t){let e=this.cache.get(t);if(!e){this.misses++;return}if(e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs){this.delete(t),this.misses++;return}return this.hits++,e.lastAccessedAt=new Date,e.accessCount++,this.config.enableLRU&&this.updateAccessOrder(t),e.value}set(t,e,r){this.cache.size>=this.config.maxSize&&!this.cache.has(t)&&this.evictLRU();let o={value:e,createdAt:new Date,lastAccessedAt:new Date,accessCount:1,ttlMs:r??this.config.defaultTtlMs,keyHash:t};this.cache.set(t,o),this.config.enableLRU&&this.updateAccessOrder(t)}has(t){let e=this.cache.get(t);return e?e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs?(this.delete(t),!1):!0:!1}delete(t){let e=this.cache.delete(t);if(e){let r=this.accessOrder.indexOf(t);r!==-1&&this.accessOrder.splice(r,1)}return e}clear(){this.cache.clear(),this.accessOrder=[],this.hits=0,this.misses=0,this.evictions=0}getStats(){let t=this.hits+this.misses,e=t>0?this.hits/t:0,r=0;for(let o of this.cache.values())r+=this.estimateSize(o.value);return{size:this.cache.size,maxSize:this.config.maxSize,hits:this.hits,misses:this.misses,hitRate:e,evictions:this.evictions,memoryUsageBytes:r}}keys(){return Array.from(this.cache.keys())}entries(){return Array.from(this.cache.entries())}import(t){for(let[e,r]of t)r.createdAt=new Date(r.createdAt),r.lastAccessedAt=new Date(r.lastAccessedAt),this.cache.set(e,r),this.accessOrder.push(e);for(;this.cache.size>this.config.maxSize;)this.evictLRU()}pruneExpired(){let t=Date.now(),e=0;for(let[r,o]of this.cache.entries())o.ttlMs>0&&t-o.createdAt.getTime()>o.ttlMs&&(this.delete(r),e++);return e}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e!==-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t)}evictLRU(){if(this.accessOrder.length===0){let e=this.cache.keys().next().value;e&&(this.cache.delete(e),this.evictions++);return}let t=this.accessOrder.shift();t&&(this.cache.delete(t),this.evictions++)}estimateSize(t){return t==null?0:JSON.stringify(t).length*2}},B=class{generationCache;embeddingCache;completionCache;config;constructor(t={}){this.config={...be,...t},this.generationCache=new M(t),this.embeddingCache=new M(t),this.completionCache=new M(t)}getGeneration(t,e){if(!this.config.cacheGenerations)return;let r=M.generateKey("generation",t,e);return this.generationCache.get(r)}setGeneration(t,e,r,o){if(!this.config.cacheGenerations)return;let n=M.generateKey("generation",t,r);this.generationCache.set(n,e,o)}getEmbedding(t,e){if(!this.config.cacheEmbeddings)return;let r=M.generateKey("embedding",t,e);return this.embeddingCache.get(r)}setEmbedding(t,e,r,o){if(!this.config.cacheEmbeddings)return;let n=M.generateKey("embedding",t,r);this.embeddingCache.set(n,e,o)}getCompletion(t,e){if(!this.config.cacheCompletions)return;let r=M.generateKey("completion",t,e);return this.completionCache.get(r)}setCompletion(t,e,r,o){if(!this.config.cacheCompletions)return;let n=M.generateKey("completion",t,r);this.completionCache.set(n,e,o)}getStats(){let t=this.generationCache.getStats(),e=this.embeddingCache.getStats(),r=this.completionCache.getStats(),o=t.hits+e.hits+r.hits,n=t.misses+e.misses+r.misses,s=o+n;return{generation:t,embedding:e,completion:r,total:{size:t.size+e.size+r.size,maxSize:this.config.maxSize*3,hits:o,misses:n,hitRate:s>0?o/s:0,evictions:t.evictions+e.evictions+r.evictions,memoryUsageBytes:t.memoryUsageBytes+e.memoryUsageBytes+r.memoryUsageBytes}}}clear(){this.generationCache.clear(),this.embeddingCache.clear(),this.completionCache.clear()}pruneExpired(){return this.generationCache.pruneExpired()+this.embeddingCache.pruneExpired()+this.completionCache.pruneExpired()}};var ie="(unattributed)",Ae=`
3
3
  CREATE TABLE IF NOT EXISTS llm_spend (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  ts INTEGER NOT NULL,
@@ -17,7 +17,7 @@ CREATE INDEX IF NOT EXISTS idx_llm_spend_ts ON llm_spend(ts);
17
17
  VALUES (@ts, @provider, @model, @cost_usd, @cost_source, @prompt_tokens, @completion_tokens, @request_id, @agent_type)`).run({ts:Date.now(),provider:t.provider,model:t.model,cost_usd:t.costUsd,cost_source:t.costSource,prompt_tokens:t.promptTokens,completion_tokens:t.completionTokens,request_id:t.requestId,agent_type:t.agent??null}):this.db.prepare(`INSERT INTO llm_spend
18
18
  (ts, provider, model, cost_usd, cost_source, prompt_tokens, completion_tokens, request_id)
19
19
  VALUES (@ts, @provider, @model, @cost_usd, @cost_source, @prompt_tokens, @completion_tokens, @request_id)`).run({ts:Date.now(),provider:t.provider,model:t.model,cost_usd:t.costUsd,cost_source:t.costSource,prompt_tokens:t.promptTokens,completion_tokens:t.completionTokens,request_id:t.requestId})}catch{}}spentSince(t,e=Date.now()){try{return this.db.prepare("SELECT COALESCE(SUM(cost_usd), 0) AS total FROM llm_spend WHERE ts >= ?").get(e-t)?.total??0}catch{return 0}}spentByAgentSince(t,e=Date.now()){try{let r=this.db.prepare(`SELECT COALESCE(agent_type, ?) AS agent, COALESCE(SUM(cost_usd), 0) AS total
20
- FROM llm_spend WHERE ts >= ? GROUP BY COALESCE(agent_type, ?)`).all(ie,e-t,ie),o={};for(let n of r)o[n.agent]=n.total;return o}catch{return{}}}},N=class{entries=[];record(t){this.entries.push({ts:Date.now(),costUsd:t.costUsd,agent:t.agent??ie})}spentSince(t,e=Date.now()){let r=e-t,o=0;for(let n of this.entries)n.ts>=r&&(o+=n.costUsd);return o}spentByAgentSince(t,e=Date.now()){let r=e-t,o={};for(let n of this.entries)n.ts>=r&&(o[n.agent]=(o[n.agent]??0)+n.costUsd);return o}};async function ve(){try{let t=(await import("./unified-memory-6PHUOZRH.js")).getUnifiedMemory();return t.isInitialized()||await t.initialize(),new ae(t.getDatabase())}catch{return new N}}L();function ce(g,t,e,r){let o=Math.min(t*Math.pow(2,g),e),n=Math.random()*r*o;return o+n}var Le=1e3,Pe=3e4;function T(g,t=Le,e=Pe){return ce(g,t,e,0)}import{readFileSync as Oe}from"fs";import*as Te from"path";var le=["low","medium","high","xhigh","max"],Ie="xhigh";function G(g){return typeof g=="string"&&le.includes(g)}var $;function Se(g){try{let e=Oe(g,"utf8").match(/^\s*effort_level\s*:\s*['"]?([a-z]+)['"]?\s*$/m);return e&&G(e[1])?e[1]:null}catch{return null}}function ke(g={}){if(g.override&&G(g.override))return g.override;if(g.agentEffort&&G(g.agentEffort))return g.agentEffort;let e=(g.env??process.env).QE_EFFORT_LEVEL;if(e&&G(e))return e;let r=g.fleetDefaultsPath??Te.join(process.cwd(),"config","fleet-defaults.yaml");return $===void 0&&($=Se(r)),$||Ie}function Ee(g,t){let e=le.indexOf(g),r=le.indexOf(t);return e>r?t:g}var xe={model:"claude-sonnet-4-6",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,anthropicVersion:"2023-06-01",enableCache:!0,enableCircuitBreaker:!0},F=class{type="claude";name="Anthropic Claude";config;requestId=0;constructor(t={}){this.config={...xe,...t}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getApiKey())return{healthy:!1,error:"API key not configured. Set ANTHROPIC_API_KEY environment variable."};let e=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:this.config.model,max_tokens:1,messages:[{role:"user",content:"Hi"}]})},5e3),o=Date.now()-e;if(!r.ok){let n=await r.text();return{healthy:!1,latencyMs:o,error:`API error: ${r.status} - ${n}`}}return{healthy:!0,latencyMs:o,models:this.getSupportedModels(),details:{apiVersion:this.config.anthropicVersion,defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){if(!this.getApiKey())throw a("Anthropic API key not configured","API_KEY_MISSING",{provider:"claude",retryable:!1});let o=this.formatMessages(t),n=e?.model??this.config.model,s=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`claude-${++this.requestId}-${Date.now()}`,p=Date.now(),m={model:n,max_tokens:s,temperature:i,messages:o};e?.systemPrompt&&(m.system=this.config.enableCache!==!1?[{type:"text",text:e.systemPrompt,cache_control:{type:"ephemeral"}}]:e.systemPrompt),e?.stopSequences&&e.stopSequences.length>0&&(m.stop_sequences=e.stopSequences);try{if(fe(n).supportsEffortXHigh){let u=ke({override:e?.effort}),d=Ee(u,"xhigh");m.thinking={type:"adaptive",effort:d}}}catch{}try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(m)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),u=Date.now()-p;if(!c.ok){let k=await c.json().catch(()=>({error:{message:"Unknown error"}}));throw this.handleApiError(c.status,k,n)}let d=await c.json(),h=d.usage.cache_creation_input_tokens??0,f=d.usage.cache_read_input_tokens??0,b={promptTokens:d.usage.input_tokens,completionTokens:d.usage.output_tokens,totalTokens:d.usage.input_tokens+h+f+d.usage.output_tokens,cacheCreationTokens:h,cacheReadTokens:f},y=R.calculateCost(n,b);return v.recordTokenUsage(l,"claude-provider","llm","generate",{inputTokens:d.usage.input_tokens,outputTokens:d.usage.output_tokens,totalTokens:d.usage.input_tokens+d.usage.output_tokens,estimatedCostUsd:y.totalCost}),{content:d.content.filter(k=>k.type==="text").map(k=>k.text).join(""),model:d.model,provider:"claude",usage:b,cost:y,latencyMs:u,finishReason:this.mapFinishReason(d.stop_reason),cached:!1,requestId:l}}catch(c){throw c instanceof Error&&"code"in c?c:a(c instanceof Error?c.message:"Request failed","NETWORK_ERROR",{provider:"claude",model:n,retryable:!0,cause:c})}}async embed(t,e){throw a("Claude does not support native embeddings. Use OpenAI or Ollama for embeddings.","MODEL_NOT_FOUND",{provider:"claude",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
20
+ FROM llm_spend WHERE ts >= ? GROUP BY COALESCE(agent_type, ?)`).all(ie,e-t,ie),o={};for(let n of r)o[n.agent]=n.total;return o}catch{return{}}}},N=class{entries=[];record(t){this.entries.push({ts:Date.now(),costUsd:t.costUsd,agent:t.agent??ie})}spentSince(t,e=Date.now()){let r=e-t,o=0;for(let n of this.entries)n.ts>=r&&(o+=n.costUsd);return o}spentByAgentSince(t,e=Date.now()){let r=e-t,o={};for(let n of this.entries)n.ts>=r&&(o[n.agent]=(o[n.agent]??0)+n.costUsd);return o}};async function ve(){try{let t=(await import("./unified-memory-Q55MJWAM.js")).getUnifiedMemory();return t.isInitialized()||await t.initialize(),new ae(t.getDatabase())}catch{return new N}}L();function ce(g,t,e,r){let o=Math.min(t*Math.pow(2,g),e),n=Math.random()*r*o;return o+n}var Le=1e3,Pe=3e4;function T(g,t=Le,e=Pe){return ce(g,t,e,0)}import{readFileSync as Oe}from"fs";import*as Te from"path";var le=["low","medium","high","xhigh","max"],Ie="xhigh";function G(g){return typeof g=="string"&&le.includes(g)}var $;function Se(g){try{let e=Oe(g,"utf8").match(/^\s*effort_level\s*:\s*['"]?([a-z]+)['"]?\s*$/m);return e&&G(e[1])?e[1]:null}catch{return null}}function ke(g={}){if(g.override&&G(g.override))return g.override;if(g.agentEffort&&G(g.agentEffort))return g.agentEffort;let e=(g.env??process.env).QE_EFFORT_LEVEL;if(e&&G(e))return e;let r=g.fleetDefaultsPath??Te.join(process.cwd(),"config","fleet-defaults.yaml");return $===void 0&&($=Se(r)),$||Ie}function Ee(g,t){let e=le.indexOf(g),r=le.indexOf(t);return e>r?t:g}var xe={model:"claude-sonnet-4-6",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,anthropicVersion:"2023-06-01",enableCache:!0,enableCircuitBreaker:!0},F=class{type="claude";name="Anthropic Claude";config;requestId=0;constructor(t={}){this.config={...xe,...t}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getApiKey())return{healthy:!1,error:"API key not configured. Set ANTHROPIC_API_KEY environment variable."};let e=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:this.config.model,max_tokens:1,messages:[{role:"user",content:"Hi"}]})},5e3),o=Date.now()-e;if(!r.ok){let n=await r.text();return{healthy:!1,latencyMs:o,error:`API error: ${r.status} - ${n}`}}return{healthy:!0,latencyMs:o,models:this.getSupportedModels(),details:{apiVersion:this.config.anthropicVersion,defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){if(!this.getApiKey())throw a("Anthropic API key not configured","API_KEY_MISSING",{provider:"claude",retryable:!1});let o=this.formatMessages(t),n=e?.model??this.config.model,s=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,l=`claude-${++this.requestId}-${Date.now()}`,p=Date.now(),m={model:n,max_tokens:s,temperature:i,messages:o};e?.systemPrompt&&(m.system=this.config.enableCache!==!1?[{type:"text",text:e.systemPrompt,cache_control:{type:"ephemeral"}}]:e.systemPrompt),e?.stopSequences&&e.stopSequences.length>0&&(m.stop_sequences=e.stopSequences);try{if(fe(n).supportsEffortXHigh){let u=ke({override:e?.effort}),d=Ee(u,"xhigh");m.thinking={type:"adaptive",effort:d}}}catch{}try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(m)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),u=Date.now()-p;if(!c.ok){let k=await c.json().catch(()=>({error:{message:"Unknown error"}}));throw this.handleApiError(c.status,k,n)}let d=await c.json(),h=d.usage.cache_creation_input_tokens??0,f=d.usage.cache_read_input_tokens??0,b={promptTokens:d.usage.input_tokens,completionTokens:d.usage.output_tokens,totalTokens:d.usage.input_tokens+h+f+d.usage.output_tokens,cacheCreationTokens:h,cacheReadTokens:f},y=R.calculateCost(n,b);return v.recordTokenUsage(l,"claude-provider","llm","generate",{inputTokens:d.usage.input_tokens,outputTokens:d.usage.output_tokens,totalTokens:d.usage.input_tokens+d.usage.output_tokens,estimatedCostUsd:y.totalCost}),{content:d.content.filter(k=>k.type==="text").map(k=>k.text).join(""),model:d.model,provider:"claude",usage:b,cost:y,latencyMs:u,finishReason:this.mapFinishReason(d.stop_reason),cached:!1,requestId:l}}catch(c){throw c instanceof Error&&"code"in c?c:a(c instanceof Error?c.message:"Request failed","NETWORK_ERROR",{provider:"claude",model:n,retryable:!0,cause:c})}}async embed(t,e){throw a("Claude does not support native embeddings. Use OpenAI or Ollama for embeddings.","MODEL_NOT_FOUND",{provider:"claude",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
21
21
 
22
22
  `,"```"]});return{completion:r.content,model:r.model,provider:"claude",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return["claude-opus-4-7","claude-sonnet-4-6","claude-haiku-4-5-20251001","claude-3-opus-20240229","claude-3-sonnet-20240229","claude-3-haiku-20240307"]}getCostPerToken(){return R.getCostPerToken(this.config.model)}async dispose(){}getApiKey(){return this.config.apiKey??process.env.ANTHROPIC_API_KEY}getBaseUrl(){return(this.config.baseUrl??process.env.ANTHROPIC_BASE_URL??"https://api.anthropic.com").replace(/\/$/,"")}getHeaders(){return{"Content-Type":"application/json","x-api-key":this.getApiKey(),"anthropic-version":this.config.anthropicVersion??"2023-06-01"}}formatMessages(t){return typeof t=="string"?[{role:"user",content:t}]:t.filter(e=>e.role!=="system").map(e=>({role:e.role,content:e.content}))}mapFinishReason(t){switch(t){case"end_turn":return"stop";case"max_tokens":return"length";case"stop_sequence":return"stop";default:return"stop"}}handleApiError(t,e,r){let o="error"in e?e.error?.message??"Unknown API error":"Unknown API error",n="error"in e&&"type"in e.error?e.error.type:"";switch(t){case 401:throw a(o,"API_KEY_INVALID",{provider:"claude",model:r,retryable:!1});case 429:throw a(o,"RATE_LIMITED",{provider:"claude",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw n==="invalid_request_error"&&o.includes("context")?a(o,"CONTEXT_LENGTH_EXCEEDED",{provider:"claude",model:r,retryable:!1}):a(o,"UNKNOWN",{provider:"claude",model:r,retryable:!1});case 500:case 502:case 503:throw a(o,"PROVIDER_UNAVAILABLE",{provider:"claude",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(o,"UNKNOWN",{provider:"claude",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){let o=new AbortController,n=setTimeout(()=>o.abort(),r);try{return await fetch(t,{...e,signal:o.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"claude",retryable:!0}):s}finally{clearTimeout(n)}}async fetchWithRetry(t,e,r,o){let n;for(let s=0;s<o;s++)try{let i=await this.fetchWithTimeout(t,e,r);if(i.status>=400&&i.status<500&&i.status!==429)return i;if((i.status>=500||i.status===429)&&s<o-1){let l=T(s);await this.sleep(l);continue}return i}catch(i){if(n=E(i),s<o-1){let l=T(s);await this.sleep(l)}}throw n??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};import{spawn as Ue}from"node:child_process";var Ne=["ANTHROPIC_API_KEY","CLAUDE_API_KEY","ANTHROPIC_AUTH_TOKEN"],De={model:"sonnet",maxTokens:4096,temperature:.7,timeoutMs:12e4,maxRetries:1,binaryPath:"claude",maxConcurrency:2,disallowedTools:["Bash","Edit","Write","NotebookEdit","WebFetch","WebSearch","Task"]},W=class g{type="claude-code";name="Claude Code (subscription)";billingMode="subscription";config;requestId=0;availabilityCache;active=0;queue=[];constructor(t={}){this.config={...De,...t};let e=Number.parseInt(process.env.AQE_CLAUDE_CODE_CONCURRENCY??"",10);Number.isFinite(e)&&e>0&&(this.config.maxConcurrency=e)}async isAvailable(){let t=Date.now();if(this.availabilityCache&&t-this.availabilityCache.at<6e4)return this.availabilityCache.available;let e=!1;try{let{code:r}=await this.runProcess(["--version"],void 0,5e3);e=r===0}catch{e=!1}return this.availabilityCache={at:t,available:e},e}async healthCheck(){let t=Date.now(),e=await this.isAvailable(),r=Date.now()-t;return e?{healthy:!0,latencyMs:r,models:this.getSupportedModels(),details:{binaryPath:this.config.binaryPath,billing:"subscription"}}:{healthy:!1,latencyMs:r,error:`Claude Code CLI ("${this.config.binaryPath}") not found or not runnable. Install Claude Code and log in with your Pro/Max account.`}}async generate(t,e){let r=this.toCliModel(e?.model??this.config.model),o=`claude-code-${++this.requestId}-${Date.now()}`,{prompt:n,systemPrompt:s}=this.flatten(t,e?.systemPrompt),i=["-p","--output-format","json","--model",r];s&&i.push("--append-system-prompt",s);let l=this.config.disallowedTools??[];l.length>0&&i.push("--disallowedTools",...l);let p=Date.now(),m=e?.timeoutMs??this.config.timeoutMs??12e4,{code:c,stdout:u,stderr:d}=await this.withConcurrency(()=>this.runProcess(i,n,m)),h=Date.now()-p;if(c!==0&&!u.trim())throw this.classifyError(d||`claude exited with code ${c}`,r);let f;try{f=JSON.parse(u)}catch{throw a(`Could not parse claude -p JSON output: ${u.slice(0,200)}`,"PROVIDER_UNAVAILABLE",{provider:"claude-code",model:r,retryable:!0})}if(f.is_error)throw this.classifyError(f.result??f.api_error_status??"claude error",r);let b=f.usage??{},y={promptTokens:b.input_tokens??0,completionTokens:b.output_tokens??0,totalTokens:(b.input_tokens??0)+(b.output_tokens??0),cacheCreationTokens:b.cache_creation_input_tokens??0,cacheReadTokens:b.cache_read_input_tokens??0},C=f.modelUsage&&Object.keys(f.modelUsage)[0]||r;return v.recordTokenUsage(o,"claude-code-provider","llm","generate",{inputTokens:y.promptTokens,outputTokens:y.completionTokens,totalTokens:y.totalTokens,estimatedCostUsd:0}),{content:f.result??"",model:C,provider:"claude-code",usage:y,cost:{inputCost:0,outputCost:0,totalCost:0,currency:"USD",source:"provider-receipt"},latencyMs:h,finishReason:this.mapFinishReason(f.stop_reason),cached:!1,requestId:o}}async embed(t,e){throw a("Claude Code provider does not support embeddings. Use openai, ollama, or cognitum.","MODEL_NOT_FOUND",{provider:"claude-code",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256});return{completion:r.content,model:r.model,provider:"claude-code",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return["opus","sonnet","haiku"]}getCostPerToken(){return{input:0,output:0}}async dispose(){}toCliModel(t){let e=t.toLowerCase();return e.includes("opus")?"opus":e.includes("haiku")?"haiku":e.includes("sonnet")?"sonnet":t}flatten(t,e){if(typeof t=="string")return{prompt:t,systemPrompt:e};let r=t.filter(n=>n.role==="system").map(n=>n.content);return e&&r.unshift(e),{prompt:t.filter(n=>n.role!=="system").map(n=>`${n.role==="assistant"?"Assistant":"User"}: ${n.content}`).join(`
23
23
 
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.5");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.6");process.exit(0)}
2
2
  var h={0:"sqlite-only",1:"hybrid",2:"dual-write-sqlite-primary",3:"dual-write-rvf-primary",4:"rvf-primary"},g=class{config;db=null;rvfStore=null;totalWrites=0;totalReads=0;rvfWriteFailures=0;rvfReadFailures=0;fallbacksUsed=0;sqliteLatencies=[];rvfLatencies=[];sqliteWriteLatencies=[];rvfWriteLatencies=[];constructor(e){this.config={rvfPath:".agentic-qe/patterns.rvf",dimensions:384,enableFallback:!0,...e}}setSqliteDb(e){this.db=e}setRvfStore(e){this.rvfStore=e}get stage(){return this.config.stage}setStage(e){this.config={...this.config,stage:e}}write(e,t){this.totalWrites++;let s={sqliteSuccess:!1,rvfSuccess:!1,stage:this.config.stage,fallbackUsed:!1},n=this.config.stage<4,o=this.config.stage>=2;if(n&&this.db){let i=performance.now();try{let r=Buffer.from(t instanceof Float32Array?t.buffer:new Float32Array(t).buffer);this.db.prepare(`
3
3
  INSERT INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model, created_at)
4
4
  VALUES (?, ?, ?, 'all-MiniLM-L6-v2', datetime('now'))
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.5");process.exit(0)}
2
- import{l as p}from"./chunk-FYWTMDID.js";import{a as f,c as R}from"./chunk-6ZCAZ3TR.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-ITDN72YJ.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.13.6");process.exit(0)}
2
+ import{l as p}from"./chunk-PSAXLKDZ.js";import{a as f,c as R}from"./chunk-6UPQD42K.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-Y2DJG7HQ.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,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.5");process.exit(0)}
2
- import{a as v,b as k}from"./chunk-74QRMQFR.js";import{i as g,m as P}from"./chunk-7BLXINIL.js";import{a as d,b as y,c as R}from"./chunk-6ZCAZ3TR.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,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.13.6");process.exit(0)}
2
+ import{a as v,b as k}from"./chunk-PTBW2QXE.js";import{i as g,m as P}from"./chunk-FH6H4KOZ.js";import{a as d,b as y,c as R}from"./chunk-6UPQD42K.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,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.13.5");process.exit(0)}
2
- import{c as e}from"./chunk-WSSFH23M.js";function r(t){t.exec(n)}var n,a=e(()=>{"use strict";n=`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.6");process.exit(0)}
2
+ import{c as e}from"./chunk-ISOTSVI7.js";function r(t){t.exec(n)}var n,a=e(()=>{"use strict";n=`
3
3
  -- Negative pattern records (ADR-110 kept nulls)
4
4
  CREATE TABLE IF NOT EXISTS qe_pattern_nulls (
5
5
  id TEXT PRIMARY KEY,
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.5");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.6");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,o){let e=m[t];if(!e)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let i=o.promptTokens/1e6*e.input+(o.cacheReadTokens??0)/1e6*e.input*.1+(o.cacheCreationTokens??0)/1e6*e.input*1.25,r=o.completionTokens/1e6*e.output;return{inputCost:i,outputCost:r,totalCost:i+r,currency:"USD"}}static getCostPerToken(t){let o=m[t];return o?{input:o.input/1e6,output:o.output/1e6}:{input:0,output:0}}recordUsage(t,o,e,i,r){let n=c.calculateCost(o,e),p={timestamp:new Date,provider:t,model:o,usage:e,cost:n,requestId:i,metadata:r};return this.records.push(p),this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords)),this.checkAlerts(),n}getSummary(t){let o=new Date,e=this.getPeriodStart(o,t),i=o,r=this.records.filter(a=>a.timestamp>=e&&a.timestamp<=i),n={claude:0,"claude-code":0,codex:0,openai:0,ollama:0,openrouter:0,bedrock:0,"azure-openai":0,gemini:0,cognitum:0},p={},u=0,l=0;for(let a of r)u+=a.cost.totalCost,l+=a.usage.totalTokens,n[a.provider]+=a.cost.totalCost,p[a.model]=(p[a.model]||0)+a.cost.totalCost;return{period:t,periodStart:e,periodEnd:i,totalCost:u,byProvider:n,byModel:p,totalTokens:l,totalRequests:r.length}}getCurrentCost(t){return this.getSummary(t).totalCost}getTotalTokens(t){return this.getSummary(t).totalTokens}getUsageByProvider(t,o="all"){let e=this.getPeriodStart(new Date,o),i=this.records.filter(u=>u.provider===t&&u.timestamp>=e),r={},n=0,p=0;for(let u of i)n+=u.cost.totalCost,p+=u.usage.totalTokens,r[u.model]||(r[u.model]={cost:0,tokens:0,requests:0}),r[u.model].cost+=u.cost.totalCost,r[u.model].tokens+=u.usage.totalTokens,r[u.model].requests+=1;return{totalCost:n,totalTokens:p,totalRequests:i.length,models:r}}addAlert(t,o,e){let i=`alert-${Date.now()}-${v().slice(0,12)}`;return this.alerts.push({threshold:t,period:o,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 o of t)o.timestamp=new Date(o.timestamp),this.records.push(o);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,o,e){return c.calculateCost(t,{promptTokens:o,completionTokens:e,totalTokens:o+e})}wouldExceedLimit(t,o,e,i,r){let n=this.getCurrentCost(r),p=this.estimateCost(t,o,e);return n+p.totalCost>i}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}getPeriodStart(t,o){let e=new Date(t);switch(o){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 o=this.getSummary(t.period);if(o.totalCost>=t.threshold){t.active=!1;try{t.onThreshold(o)}catch(e){console.error("Cost alert callback error:",e)}}}}},s;function h(){return s||(s=new d),s}function b(){s&&(s.dispose(),s=void 0)}export{m as a,d as b,h as c,b as d};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.6");process.exit(0)}
2
+ import{a,e as p}from"./chunk-Q4RU4XG6.js";import{a as l,d}from"./chunk-OS56PKRO.js";d();p();var u=class{store=new Map;vectors=new Map;cleanupInterval;async initialize(){this.cleanupInterval=setInterval(()=>this.cleanup(),a.CLEANUP_INTERVAL_MS),this.cleanupInterval.unref&&this.cleanupInterval.unref()}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.store.clear(),this.vectors.clear()}async set(t,r,e){let s={value:r,namespace:e?.namespace??"default",createdAt:Date.now()};e?.ttl&&(s.expiresAt=Date.now()+e.ttl*a.TTL_MULTIPLIER_MS);let n=this.buildKey(t,e?.namespace);this.store.set(n,s)}async get(t,r){let e=this.buildKey(t,r?.namespace),s=this.store.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.store.delete(e);return}return s.value}}async delete(t,r){let e=this.buildKey(t,r?.namespace);return this.store.delete(e)}async has(t,r){return await this.get(t,r)!==void 0}async search(t,r=a.DEFAULT_SEARCH_LIMIT,e){let s=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(s.replace(/\*/g,".*")),i=[],o=e?.namespace?`${e.namespace}:`:void 0;for(let c of this.store.keys())if(!(o&&!c.startsWith(o))&&n.test(c)&&(i.push(c),i.length>=r))break;return i}async vectorSearch(t,r,e){let s=[];for(let[n,i]of this.vectors.entries()){if(e&&!n.startsWith(e))continue;let o=l(t,i.embedding);s.push({key:n,score:o,metadata:i.metadata})}return s.sort((n,i)=>i.score-n.score).slice(0,r)}async storeVector(t,r,e){this.vectors.set(t,{embedding:r,metadata:e})}buildKey(t,r){return r?`${r}:${t}`:t}cleanup(){let t=Date.now();for(let[r,e]of this.store.entries())e.expiresAt&&t>e.expiresAt&&this.store.delete(r)}getStats(){return{entries:this.store.size,vectors:this.vectors.size}}async clear(t){if(t){let r=`${t}:`;for(let e of this.store.keys())e.startsWith(r)&&this.store.delete(e)}else this.store.clear()}async count(t){let r=0,e=`${t}:`;for(let s of this.store.keys())if(s.startsWith(e)){let n=this.store.get(s);n&&(!n.expiresAt||Date.now()<=n.expiresAt)&&r++}return r}async hasCodeIntelligenceIndex(){return await this.count("code-intelligence:kg")>0}};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.13.5");process.exit(0)}
2
- import{a as U,b as G}from"./chunk-2CF3XZAS.js";import{h as N}from"./chunk-EXXWOOUL.js";import{a as W}from"./chunk-UGER2PGN.js";import{e as F}from"./chunk-FQPYD6YE.js";import{b as v,c as x}from"./chunk-L6H4MWVN.js";import{a as re}from"./chunk-ELKWYWTD.js";import{c as O}from"./chunk-4Z7JP7CD.js";import{b as k,d as q}from"./chunk-OUWZTYRZ.js";import{b,c as E}from"./chunk-3EWWP3AO.js";import{a as y,c as I}from"./chunk-6ZCAZ3TR.js";import{i as z}from"./chunk-V2T7QEPV.js";import{S as ae,b as _}from"./chunk-HBYVYLBN.js";import{randomUUID as Y}from"crypto";I();q();import{randomUUID as se}from"node:crypto";var B=x(),P=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;localTrajectories=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async startTrajectory(e,t){let i=`trajectory-${se()}`;if(this.claudeFlowAvailable)try{let{execFileSync:n}=await import("child_process"),r=["--no-install",B,"hooks","intelligence","trajectory-start","--task",e];t&&r.push("--agent",t);let o=n("npx",r,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}).match(/trajectoryId[:\s]+["']?([^"'\s,}]+)/i);if(o?.[1])return o[1]}catch(n){console.debug("[TrajectoryBridge] Claude Flow trajectory start failed:",n instanceof Error?n.message:n)}return this.localTrajectories.set(i,{id:i,task:e,agent:t,steps:[],startedAt:Date.now()}),i}async recordStep(e,t,i,n){if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),o=["--no-install",B,"hooks","intelligence","trajectory-step","--trajectory-id",e,"--action",t];i&&o.push("--result",i),n!==void 0&&o.push("--quality",String(n)),a("npx",o,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot});return}catch(a){console.debug("[TrajectoryBridge] Claude Flow trajectory step failed:",a instanceof Error?a.message:a)}let r=this.localTrajectories.get(e);r&&r.steps.push({id:`step-${r.steps.length+1}`,action:t,result:i,quality:n,timestamp:Date.now()})}async endTrajectory(e,t,i){if(this.claudeFlowAvailable)try{let{execFileSync:r}=await import("child_process"),a=["--no-install",B,"hooks","intelligence","trajectory-end","--trajectory-id",e,"--success",String(t)];i&&a.push("--feedback",i),r("npx",a,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch{}let n=this.localTrajectories.get(e);if(n)return n.success=t,n.feedback=i,n.completedAt=Date.now(),await this.persistTrajectory(n),n}getTrajectory(e){return this.localTrajectories.get(e)}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async persistTrajectory(e){try{let{getUnifiedMemory:t}=await import("./unified-memory-6PHUOZRH.js"),i=t();i.isInitialized()||await i.initialize();let n=i.getDatabase();try{n.prepare("PRAGMA table_info(qe_trajectories)").all().some(s=>s.name==="feedback")||n.exec("ALTER TABLE qe_trajectories ADD COLUMN feedback TEXT")}catch{}let r=new Date(e.startedAt).toISOString(),a=e.completedAt?new Date(e.completedAt).toISOString():null;n.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.6");process.exit(0)}
2
+ import{a as U,b as G}from"./chunk-7TON6JSG.js";import{h as N}from"./chunk-XRH2D6JV.js";import{a as W}from"./chunk-5VGQABM3.js";import{e as F}from"./chunk-NNIAUDHF.js";import{b as v,c as x}from"./chunk-PLYGIUFO.js";import{a as re}from"./chunk-GA7PUAMT.js";import{c as O}from"./chunk-F66FYZQF.js";import{b as k,d as q}from"./chunk-2VUXU22M.js";import{b,c as E}from"./chunk-JDADNBWS.js";import{a as y,c as I}from"./chunk-6UPQD42K.js";import{i as z}from"./chunk-XF2TKGSC.js";import{S as ae,b as _}from"./chunk-7NYCYSGW.js";import{randomUUID as Y}from"crypto";I();q();import{randomUUID as se}from"node:crypto";var B=x(),P=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;localTrajectories=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async startTrajectory(e,t){let i=`trajectory-${se()}`;if(this.claudeFlowAvailable)try{let{execFileSync:n}=await import("child_process"),r=["--no-install",B,"hooks","intelligence","trajectory-start","--task",e];t&&r.push("--agent",t);let o=n("npx",r,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}).match(/trajectoryId[:\s]+["']?([^"'\s,}]+)/i);if(o?.[1])return o[1]}catch(n){console.debug("[TrajectoryBridge] Claude Flow trajectory start failed:",n instanceof Error?n.message:n)}return this.localTrajectories.set(i,{id:i,task:e,agent:t,steps:[],startedAt:Date.now()}),i}async recordStep(e,t,i,n){if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),o=["--no-install",B,"hooks","intelligence","trajectory-step","--trajectory-id",e,"--action",t];i&&o.push("--result",i),n!==void 0&&o.push("--quality",String(n)),a("npx",o,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot});return}catch(a){console.debug("[TrajectoryBridge] Claude Flow trajectory step failed:",a instanceof Error?a.message:a)}let r=this.localTrajectories.get(e);r&&r.steps.push({id:`step-${r.steps.length+1}`,action:t,result:i,quality:n,timestamp:Date.now()})}async endTrajectory(e,t,i){if(this.claudeFlowAvailable)try{let{execFileSync:r}=await import("child_process"),a=["--no-install",B,"hooks","intelligence","trajectory-end","--trajectory-id",e,"--success",String(t)];i&&a.push("--feedback",i),r("npx",a,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch{}let n=this.localTrajectories.get(e);if(n)return n.success=t,n.feedback=i,n.completedAt=Date.now(),await this.persistTrajectory(n),n}getTrajectory(e){return this.localTrajectories.get(e)}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async persistTrajectory(e){try{let{getUnifiedMemory:t}=await import("./unified-memory-Q55MJWAM.js"),i=t();i.isInitialized()||await i.initialize();let n=i.getDatabase();try{n.prepare("PRAGMA table_info(qe_trajectories)").all().some(s=>s.name==="feedback")||n.exec("ALTER TABLE qe_trajectories ADD COLUMN feedback TEXT")}catch{}let r=new Date(e.startedAt).toISOString(),a=e.completedAt?new Date(e.completedAt).toISOString():null;n.prepare(`
3
3
  INSERT OR REPLACE INTO qe_trajectories
4
4
  (id, task, agent, domain, started_at, ended_at, success, steps_json, feedback)
5
5
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -9,4 +9,4 @@ Steps:
9
9
  ${e.steps.map((r,a)=>`${a+1}. ${r.action}${r.result?` \u2192 ${r.result}`:""}`).join(`
10
10
  `)}
11
11
 
12
- Duration: ${e.durationMs}ms`;return{patternType:t,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:this.extractTags(e),testType:this.detectTestType(e.task)},template:{type:"workflow",content:n,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),n=["unit","integration","e2e","api","mock","coverage","security"];for(let r of n)i.some(a=>a.includes(r))&&t.push(r);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){T.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function Z(l,e,t,i){return new Q(l,e,t,i)}var ue={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:F},L=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...ue,...t}}memory;eventBus;config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await U(G),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=W(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=N(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-FQOBQ6S5.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=Z(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-47A2AXUS.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-47A2AXUS.js"),{getUnifiedPersistence:n}=await import("./unified-persistence-QBGHDCCO.js"),r=n();if(r.isInitialized()){let a=r.getDatabase(),o=i(a),s=t(o);this.experienceCapture.setWitnessChain(s)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}try{let{getUnifiedPersistence:e}=await import("./unified-persistence-QBGHDCCO.js"),t=e();if(t.isInitialized()){let{PatternNullStore:i}=await import("./pattern-null-store-4WN5O2PF.js"),n=new i(t.getDatabase());this.experienceCapture.setNullRecorder(r=>n.recordNull(r))}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Null recorder wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-NOTQVBLP.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-LGHT3FN4.js"),i=t(),n=this.patternStore,r=await n.getStats();this._domainTransferInterval=setInterval(async()=>{try{r=await n.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let o=r.byDomain?.[a]??0,s=r.totalPatterns??0;return{domain:a,successRate:s>0?o/s:.5,avgConfidence:r.avgConfidence??.5,patternCount:o,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=J({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain,contextFingerprint:e.domain?`${e.domain}:router`:void 0});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let n=this.enhanceRoutingWithPatterns(i.value,t.value);return b(n)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return b([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,contextFingerprint:t.contextFingerprint,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),b([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(n=>n.pattern.id),avgSimilarity:t.length>0?t.reduce((n,r)=>n+r.similarity,0)/t.length:0};try{let n=`pattern-usage:search:${Date.now()}-${Y().slice(0,8)}`;await this.memory.set(n,i,{persist:!0,ttl:10080*60})}catch(n){console.debug("[AQELearningEngine] Failed to track pattern search:",y(n))}}enhanceRoutingWithPatterns(e,t){let i=t.filter(s=>s.similarity>=.5&&s.pattern.qualityScore>=.3);if(i.length===0)return e;let n=i.map(s=>{let u=s.pattern;return`[Pattern: ${u.name}] ${u.description} (confidence: ${(u.confidence*100).toFixed(0)}%, similarity: ${(s.similarity*100).toFixed(0)}%)`}),r=[...e.guidance,"--- Relevant Patterns ---",...n],a=[...e.patterns,...i.map(s=>s.pattern)],o=i.length>0?`; Found ${i.length} relevant pattern(s) with avg similarity ${(i.reduce((s,u)=>s+u.similarity,0)/i.length*100).toFixed(0)}%`:"";return{...e,patterns:a,guidance:r,reasoning:e.reasoning+o,confidence:Math.min(1,e.confidence+i.length*.02)}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let r of i)if(r.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let n=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let r of n)if(r.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let n=`task-${Date.now()}-${Y().slice(0,8)}`,r=n;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{r=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(d){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(d))}let a=`${i??"unknown"}:${t??"unknown"}`,o;try{let d=await this.searchPatternsForTask(e,{domain:i,contextFingerprint:a});d.success&&d.value.length>0&&(o=d.value.map(g=>g.pattern.id))}catch{}let s;this.experienceCapture&&(s=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:r!==n?r:void 0,appliedPatterns:o}));let u={id:s||r,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(u.id,u),u.id}async recordStep(e,t,i,n){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,n)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:n});let r=this.activeTasks.get(e);r&&r.steps.push({action:t,result:i,quality:n,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(r){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(r))}let n=this.activeTasks.get(e);if(n)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(n),n}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(n){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",n instanceof Error?n.message:n)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((n,r)=>n+(r.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),o=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],s=["node_modules/**","dist/**","coverage/**",".git/**"],u=await i.default(o,{cwd:e,ignore:s,onlyFiles:!0}),d=new Set,g=new Set;for(let m of u.slice(0,100))(m.endsWith(".ts")||m.endsWith(".tsx"))&&d.add("typescript"),(m.endsWith(".js")||m.endsWith(".jsx"))&&d.add("javascript"),m.endsWith(".py")&&d.add("python"),m.endsWith(".go")&&d.add("go"),m.endsWith(".rs")&&d.add("rust");let w=a(e,"package.json");if(n(w))try{let m=k(r(w,"utf-8")),p={...m.dependencies,...m.devDependencies};p.react&&g.add("react"),p.vue&&g.add("vue"),p.vitest&&g.add("vitest"),p.jest&&g.add("jest"),p.playwright&&g.add("playwright")}catch(m){console.debug("[AQELearningEngine] package.json parse failed:",m instanceof Error?m.message:m)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(d),frameworks:Array.from(g),patterns:[],complexity:u.length>500?3:u.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},de={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},ee=class{config;constructor(e){this.config={...de,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),n=e.slice(t),r=[],a=Date.now(),o=h(i.map(c=>c.tokenMetrics.costUsd)),s=h(n.map(c=>c.tokenMetrics.costUsd)),u=h(i.map(c=>c.tokenMetrics.savingsUsd)),d=h(n.map(c=>c.tokenMetrics.savingsUsd));if(s>o*1.1&&d<=u*1.05){let c=Math.min(1,(s-o)/(o||1));r.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((s/(o||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:A(c),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let g=h(i.map(c=>c.qualityMetrics.gatePassRate)),w=h(n.map(c=>c.qualityMetrics.gatePassRate));Math.abs(w-g)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&r.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:A(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let p=h(i.map(c=>c.learningMetrics.patternCount)),f=h(n.map(c=>c.learningMetrics.patternCount)),te=h(i.map(c=>c.learningMetrics.averageConfidence)),$=h(n.map(c=>c.learningMetrics.averageConfidence)),ie=Math.abs(f-p),ne=Math.abs($-te);ie<1&&ne<.02&&r.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${$.toFixed(2)}) have stagnated`,confidence:A(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let C=h(i.map(c=>c.performanceMetrics.p95LatencyMs)),j=h(n.map(c=>c.performanceMetrics.p95LatencyMs));if(j>C*1.2&&C>0){let c=Math.min(1,(j-C)/(C||1));r.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${C.toFixed(0)}ms to ${j.toFixed(0)}ms`,confidence:A(c),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return r}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(l){return l.length===0?0:l.reduce((e,t)=>e+t,0)/l.length}function A(l){return Math.max(0,Math.min(1,l))}function pe(l,e,t){return new L(l,e,t)}function et(l,e,t){return pe(l,{projectRoot:e},t)}export{ue as a,L as b,de as c,ee as d,pe as e,et as f};
12
+ Duration: ${e.durationMs}ms`;return{patternType:t,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:this.extractTags(e),testType:this.detectTestType(e.task)},template:{type:"workflow",content:n,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),n=["unit","integration","e2e","api","mock","coverage","security"];for(let r of n)i.some(a=>a.includes(r))&&t.push(r);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){T.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function Z(l,e,t,i){return new Q(l,e,t,i)}var ue={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:F},L=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...ue,...t}}memory;eventBus;config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await U(G),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=W(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=N(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-UOU6ORBJ.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=Z(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-UV7BOO6T.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-UV7BOO6T.js"),{getUnifiedPersistence:n}=await import("./unified-persistence-IIB5MR67.js"),r=n();if(r.isInitialized()){let a=r.getDatabase(),o=i(a),s=t(o);this.experienceCapture.setWitnessChain(s)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}try{let{getUnifiedPersistence:e}=await import("./unified-persistence-IIB5MR67.js"),t=e();if(t.isInitialized()){let{PatternNullStore:i}=await import("./pattern-null-store-AQWPHLRW.js"),n=new i(t.getDatabase());this.experienceCapture.setNullRecorder(r=>n.recordNull(r))}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Null recorder wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-D3JGPHXY.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-E3I2LMCB.js"),i=t(),n=this.patternStore,r=await n.getStats();this._domainTransferInterval=setInterval(async()=>{try{r=await n.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let o=r.byDomain?.[a]??0,s=r.totalPatterns??0;return{domain:a,successRate:s>0?o/s:.5,avgConfidence:r.avgConfidence??.5,patternCount:o,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=J({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain,contextFingerprint:e.domain?`${e.domain}:router`:void 0});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let n=this.enhanceRoutingWithPatterns(i.value,t.value);return b(n)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return b([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,contextFingerprint:t.contextFingerprint,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),b([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(n=>n.pattern.id),avgSimilarity:t.length>0?t.reduce((n,r)=>n+r.similarity,0)/t.length:0};try{let n=`pattern-usage:search:${Date.now()}-${Y().slice(0,8)}`;await this.memory.set(n,i,{persist:!0,ttl:10080*60})}catch(n){console.debug("[AQELearningEngine] Failed to track pattern search:",y(n))}}enhanceRoutingWithPatterns(e,t){let i=t.filter(s=>s.similarity>=.5&&s.pattern.qualityScore>=.3);if(i.length===0)return e;let n=i.map(s=>{let u=s.pattern;return`[Pattern: ${u.name}] ${u.description} (confidence: ${(u.confidence*100).toFixed(0)}%, similarity: ${(s.similarity*100).toFixed(0)}%)`}),r=[...e.guidance,"--- Relevant Patterns ---",...n],a=[...e.patterns,...i.map(s=>s.pattern)],o=i.length>0?`; Found ${i.length} relevant pattern(s) with avg similarity ${(i.reduce((s,u)=>s+u.similarity,0)/i.length*100).toFixed(0)}%`:"";return{...e,patterns:a,guidance:r,reasoning:e.reasoning+o,confidence:Math.min(1,e.confidence+i.length*.02)}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let r of i)if(r.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let n=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let r of n)if(r.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let n=`task-${Date.now()}-${Y().slice(0,8)}`,r=n;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{r=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(d){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(d))}let a=`${i??"unknown"}:${t??"unknown"}`,o;try{let d=await this.searchPatternsForTask(e,{domain:i,contextFingerprint:a});d.success&&d.value.length>0&&(o=d.value.map(g=>g.pattern.id))}catch{}let s;this.experienceCapture&&(s=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:r!==n?r:void 0,appliedPatterns:o}));let u={id:s||r,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(u.id,u),u.id}async recordStep(e,t,i,n){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,n)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:n});let r=this.activeTasks.get(e);r&&r.steps.push({action:t,result:i,quality:n,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(r){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(r))}let n=this.activeTasks.get(e);if(n)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(n),n}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(n){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",n instanceof Error?n.message:n)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((n,r)=>n+(r.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),o=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],s=["node_modules/**","dist/**","coverage/**",".git/**"],u=await i.default(o,{cwd:e,ignore:s,onlyFiles:!0}),d=new Set,g=new Set;for(let m of u.slice(0,100))(m.endsWith(".ts")||m.endsWith(".tsx"))&&d.add("typescript"),(m.endsWith(".js")||m.endsWith(".jsx"))&&d.add("javascript"),m.endsWith(".py")&&d.add("python"),m.endsWith(".go")&&d.add("go"),m.endsWith(".rs")&&d.add("rust");let w=a(e,"package.json");if(n(w))try{let m=k(r(w,"utf-8")),p={...m.dependencies,...m.devDependencies};p.react&&g.add("react"),p.vue&&g.add("vue"),p.vitest&&g.add("vitest"),p.jest&&g.add("jest"),p.playwright&&g.add("playwright")}catch(m){console.debug("[AQELearningEngine] package.json parse failed:",m instanceof Error?m.message:m)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(d),frameworks:Array.from(g),patterns:[],complexity:u.length>500?3:u.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},de={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},ee=class{config;constructor(e){this.config={...de,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),n=e.slice(t),r=[],a=Date.now(),o=h(i.map(c=>c.tokenMetrics.costUsd)),s=h(n.map(c=>c.tokenMetrics.costUsd)),u=h(i.map(c=>c.tokenMetrics.savingsUsd)),d=h(n.map(c=>c.tokenMetrics.savingsUsd));if(s>o*1.1&&d<=u*1.05){let c=Math.min(1,(s-o)/(o||1));r.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((s/(o||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:A(c),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let g=h(i.map(c=>c.qualityMetrics.gatePassRate)),w=h(n.map(c=>c.qualityMetrics.gatePassRate));Math.abs(w-g)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&r.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:A(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let p=h(i.map(c=>c.learningMetrics.patternCount)),f=h(n.map(c=>c.learningMetrics.patternCount)),te=h(i.map(c=>c.learningMetrics.averageConfidence)),$=h(n.map(c=>c.learningMetrics.averageConfidence)),ie=Math.abs(f-p),ne=Math.abs($-te);ie<1&&ne<.02&&r.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${$.toFixed(2)}) have stagnated`,confidence:A(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let C=h(i.map(c=>c.performanceMetrics.p95LatencyMs)),j=h(n.map(c=>c.performanceMetrics.p95LatencyMs));if(j>C*1.2&&C>0){let c=Math.min(1,(j-C)/(C||1));r.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${C.toFixed(0)}ms to ${j.toFixed(0)}ms`,confidence:A(c),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return r}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(l){return l.length===0?0:l.reduce((e,t)=>e+t,0)/l.length}function A(l){return Math.max(0,Math.min(1,l))}function pe(l,e,t){return new L(l,e,t)}function et(l,e,t){return pe(l,{projectRoot:e},t)}export{ue as a,L as b,de as c,ee as d,pe as e,et as f};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.5");process.exit(0)}
2
- import{a as S,c as ne}from"./chunk-6ZCAZ3TR.js";import{b as L,d as B}from"./chunk-AAGOBPIJ.js";B();ne();B();import*as I from"node:http";import*as O from"node:https";import{createHash as re}from"node:crypto";import{URL as W}from"node:url";var T={model:"Xenova/all-MiniLM-L6-v2",expectedDim:384,connectTimeoutMs:5e3,requestTimeoutMs:3e4,failureThreshold:3,failureWindowMs:6e4},ie="AQE embedder endpoint identity canary v1",oe="/v1/embeddings";function X(n){if(n.startsWith("unix:"))return n;try{let e=new W(n);return e.username||e.password?(e.username="",e.password="",e.toString().replace(/\/$/,"")):n}catch{return n}}function se(n){if(n.startsWith("unix:")){let r=n.slice(5);if(!r.startsWith("/"))throw new Error(`unix endpoint must be an absolute path: ${n}`);return{transport:"unix",socketPath:r,safeUrl:n}}let e=new W(n);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`unsupported embedder endpoint protocol: ${e.protocol}`);return(e.username||e.password)&&(console.warn("[EmbedderEndpointClient] endpoint URL contained userinfo; stripping. Use AQE_EMBEDDER_TOKEN env var for credentials."),e.username="",e.password=""),{transport:e.protocol==="https:"?"https":"http",host:e.hostname,port:e.port?Number(e.port):e.protocol==="https:"?443:80,protocol:e.protocol,safeUrl:e.toString().replace(/\/$/,"")}}var $=class{constructor(e,t,r=()=>{}){this.threshold=e;this.windowMs=t;this.onRecover=r}threshold;windowMs;onRecover;failures=[];trippedAt=null;recordSuccess(){this.failures=[],this.trippedAt=null}recordFailure(){let e=Date.now();this.failures=this.failures.filter(t=>e-t<this.windowMs),this.failures.push(e),this.failures.length>=this.threshold&&(this.trippedAt=e)}isOpen(){return this.trippedAt===null?!1:Date.now()-this.trippedAt>=this.windowMs?(this.failures=[],this.trippedAt=null,this.onRecover(),!1):!0}getState(){return{open:this.isOpen(),failures:this.failures.length,trippedAt:this.trippedAt}}},P=class{parsed;agent;breaker;opts;cachedIdentity=null;probeInFlight=null;constructor(e){if(this.opts={endpoint:e.endpoint,token:e.token,model:e.model??T.model,expectedDim:e.expectedDim??T.expectedDim,connectTimeoutMs:e.connectTimeoutMs??T.connectTimeoutMs,requestTimeoutMs:e.requestTimeoutMs??T.requestTimeoutMs,failureThreshold:e.failureThreshold??T.failureThreshold,failureWindowMs:e.failureWindowMs??T.failureWindowMs,tlsOptions:e.tlsOptions},this.parsed=se(e.endpoint),this.parsed.transport==="https"){let t=e.tlsOptions??{};this.agent=new O.Agent({keepAlive:!0,ca:t.ca,cert:t.cert,key:t.key,rejectUnauthorized:t.rejectUnauthorized!==!1,servername:t.servername})}else this.agent=new I.Agent({keepAlive:!0});this.breaker=new $(this.opts.failureThreshold,this.opts.failureWindowMs,()=>{this.cachedIdentity=null})}getSafeEndpoint(){return this.parsed.safeUrl}async embed(e){if(e.length===0)return[];if(this.breaker.isOpen())throw new Error(`[EmbedderEndpointClient] circuit breaker open for ${this.parsed.safeUrl} \u2014 fast-failing`);this.cachedIdentity===null&&await this.ensureProbed();try{let t=await this.postEmbeddings(e),r=this.decodeAndNormalize(t,e.length);return this.breaker.recordSuccess(),r}catch(t){throw this.breaker.recordFailure(),t}}async probe(){return this.probeInFlight?this.probeInFlight:(this.probeInFlight=this.doProbe().finally(()=>{this.probeInFlight=null}),this.probeInFlight)}async ensureProbed(){return this.cachedIdentity?this.cachedIdentity:this.probe()}async doProbe(){let e;try{let s=await this.postEmbeddings([ie]);e=this.decodeAndNormalize(s,1)[0],this.breaker.recordSuccess()}catch(s){throw this.breaker.recordFailure(),s}if(!e||e.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch: expected ${this.opts.expectedDim}, got ${e?.length??0} from ${this.parsed.safeUrl}`);let t=Buffer.alloc(e.length*2);for(let s=0;s<e.length;s++){let i=Math.max(-32768,Math.min(32767,Math.round(e[s]*32767)));t.writeInt16LE(i,s*2)}let r=re("sha256").update(t).digest("hex").slice(0,16);return this.cachedIdentity={dim:e.length,fingerprint:r,endpoint:this.parsed.safeUrl},this.cachedIdentity}getCachedIdentity(){return this.cachedIdentity}getBreakerState(){return this.breaker.getState()}close(){this.agent.destroy()}decodeAndNormalize(e,t){if(!e||typeof e!="object"||!Array.isArray(e.data))throw new Error("[EmbedderEndpointClient] response missing data array");let r=e.data;if(r.length!==t)throw new Error(`[EmbedderEndpointClient] response count mismatch: expected ${t}, got ${r.length}`);let s=r.map((i,o)=>({idx:typeof i.index=="number"?i.index:o,embedding:i.embedding}));return s.sort((i,o)=>i.idx-o.idx),s.map(({embedding:i},o)=>{if(typeof i=="string")throw new Error(`[EmbedderEndpointClient] received base64 embedding at position ${o} \u2014 server ignored encoding_format=float. Configure the server to return float arrays.`);if(!Array.isArray(i))throw new Error(`[EmbedderEndpointClient] missing embedding at position ${o}`);if(i.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch at position ${o}: expected ${this.opts.expectedDim}, got ${i.length}`);return L(i)})}postEmbeddings(e){let t=JSON.stringify({model:this.opts.model,input:e,encoding_format:"float"});return this.request(oe,t)}request(e,t){let r={"content-type":"application/json","content-length":Buffer.byteLength(t),accept:"application/json"};this.opts.token&&(r.authorization=`Bearer ${this.opts.token}`);let s={method:"POST",path:e,headers:r,agent:this.agent},i,o;this.parsed.transport==="unix"?(i={...s,socketPath:this.parsed.socketPath},o=I.request):(i={...s,host:this.parsed.host,port:this.parsed.port,protocol:this.parsed.protocol},o=this.parsed.transport==="https"?O.request:I.request);let d=this.parsed.safeUrl,l=this.opts.connectTimeoutMs,C=this.opts.requestTimeoutMs;return new Promise((b,D)=>{let E=!1,M=a=>{E||(E=!0,b(a))},f=a=>{E||(E=!0,D(a))},y=o(i,a=>{let m=[];a.on("data",u=>m.push(Buffer.from(u))),a.on("end",()=>{let u=Buffer.concat(m).toString("utf-8");if(!a.statusCode||a.statusCode<200||a.statusCode>=300){f(new Error(`[EmbedderEndpointClient] HTTP ${a.statusCode} from ${d}: ${u.slice(0,200)}`));return}try{let g=JSON.parse(u);M(g)}catch(g){f(new Error(`[EmbedderEndpointClient] invalid JSON from ${d}: ${g.message}`))}}),a.on("error",u=>f(u))});y.on("socket",a=>{a.setTimeout(l);let m=()=>{a.setTimeout(C)};a.connecting?a.once("connect",m):m(),a.on("timeout",()=>{let u=a.connecting?"connect":"request",g=a.connecting?l:C,A=new Error(`[EmbedderEndpointClient] ${u} timeout after ${g}ms`);f(A),y.destroy(A)})}),y.on("error",a=>f(a)),y.write(t),y.end()})}};import{join as H}from"node:path";import{existsSync as ae,mkdirSync as de}from"node:fs";import{createRequire as le}from"node:module";var pe=le(import.meta.url);function ce(){let n=process.env.AQE_MEMORY_PATH;return n&&n.length>0?n:H(process.cwd(),".agentic-qe","memory.db")}var j="_system",G="embedder_identity:",v=null,_=!1;function K(){if(v)return v;if(_)return null;try{let n=pe("better-sqlite3"),e=ce(),t=H(e,"..");ae(t)||de(t,{recursive:!0});let r=new n(e);return r.pragma("journal_mode = WAL"),r.pragma("busy_timeout = 5000"),r.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.6");process.exit(0)}
2
+ import{a as S,c as ne}from"./chunk-6UPQD42K.js";import{b as L,d as B}from"./chunk-OS56PKRO.js";B();ne();B();import*as x from"node:http";import*as R from"node:https";import{createHash as re}from"node:crypto";import{URL as W}from"node:url";var T={model:"Xenova/all-MiniLM-L6-v2",expectedDim:384,connectTimeoutMs:5e3,requestTimeoutMs:3e4,failureThreshold:3,failureWindowMs:6e4},ie="AQE embedder endpoint identity canary v1",oe="/v1/embeddings";function X(n){if(n.startsWith("unix:"))return n;try{let e=new W(n);return e.username||e.password?(e.username="",e.password="",e.toString().replace(/\/$/,"")):n}catch{return n}}function se(n){if(n.startsWith("unix:")){let r=n.slice(5);if(!r.startsWith("/"))throw new Error(`unix endpoint must be an absolute path: ${n}`);return{transport:"unix",socketPath:r,safeUrl:n}}let e=new W(n);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`unsupported embedder endpoint protocol: ${e.protocol}`);return(e.username||e.password)&&(console.warn("[EmbedderEndpointClient] endpoint URL contained userinfo; stripping. Use AQE_EMBEDDER_TOKEN env var for credentials."),e.username="",e.password=""),{transport:e.protocol==="https:"?"https":"http",host:e.hostname,port:e.port?Number(e.port):e.protocol==="https:"?443:80,protocol:e.protocol,safeUrl:e.toString().replace(/\/$/,"")}}var $=class{constructor(e,t,r=()=>{}){this.threshold=e;this.windowMs=t;this.onRecover=r}threshold;windowMs;onRecover;failures=[];trippedAt=null;recordSuccess(){this.failures=[],this.trippedAt=null}recordFailure(){let e=Date.now();this.failures=this.failures.filter(t=>e-t<this.windowMs),this.failures.push(e),this.failures.length>=this.threshold&&(this.trippedAt=e)}isOpen(){return this.trippedAt===null?!1:Date.now()-this.trippedAt>=this.windowMs?(this.failures=[],this.trippedAt=null,this.onRecover(),!1):!0}getState(){return{open:this.isOpen(),failures:this.failures.length,trippedAt:this.trippedAt}}},P=class{parsed;agent;breaker;opts;cachedIdentity=null;probeInFlight=null;constructor(e){if(this.opts={endpoint:e.endpoint,token:e.token,model:e.model??T.model,expectedDim:e.expectedDim??T.expectedDim,connectTimeoutMs:e.connectTimeoutMs??T.connectTimeoutMs,requestTimeoutMs:e.requestTimeoutMs??T.requestTimeoutMs,failureThreshold:e.failureThreshold??T.failureThreshold,failureWindowMs:e.failureWindowMs??T.failureWindowMs,tlsOptions:e.tlsOptions},this.parsed=se(e.endpoint),this.parsed.transport==="https"){let t=e.tlsOptions??{};this.agent=new R.Agent({keepAlive:!0,ca:t.ca,cert:t.cert,key:t.key,rejectUnauthorized:t.rejectUnauthorized!==!1,servername:t.servername})}else this.agent=new x.Agent({keepAlive:!0});this.breaker=new $(this.opts.failureThreshold,this.opts.failureWindowMs,()=>{this.cachedIdentity=null})}getSafeEndpoint(){return this.parsed.safeUrl}async embed(e){if(e.length===0)return[];if(this.breaker.isOpen())throw new Error(`[EmbedderEndpointClient] circuit breaker open for ${this.parsed.safeUrl} \u2014 fast-failing`);this.cachedIdentity===null&&await this.ensureProbed();try{let t=await this.postEmbeddings(e),r=this.decodeAndNormalize(t,e.length);return this.breaker.recordSuccess(),r}catch(t){throw this.breaker.recordFailure(),t}}async probe(){return this.probeInFlight?this.probeInFlight:(this.probeInFlight=this.doProbe().finally(()=>{this.probeInFlight=null}),this.probeInFlight)}async ensureProbed(){return this.cachedIdentity?this.cachedIdentity:this.probe()}async doProbe(){let e;try{let s=await this.postEmbeddings([ie]);e=this.decodeAndNormalize(s,1)[0],this.breaker.recordSuccess()}catch(s){throw this.breaker.recordFailure(),s}if(!e||e.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch: expected ${this.opts.expectedDim}, got ${e?.length??0} from ${this.parsed.safeUrl}`);let t=Buffer.alloc(e.length*2);for(let s=0;s<e.length;s++){let i=Math.max(-32768,Math.min(32767,Math.round(e[s]*32767)));t.writeInt16LE(i,s*2)}let r=re("sha256").update(t).digest("hex").slice(0,16);return this.cachedIdentity={dim:e.length,fingerprint:r,endpoint:this.parsed.safeUrl},this.cachedIdentity}getCachedIdentity(){return this.cachedIdentity}getBreakerState(){return this.breaker.getState()}close(){this.agent.destroy()}decodeAndNormalize(e,t){if(!e||typeof e!="object"||!Array.isArray(e.data))throw new Error("[EmbedderEndpointClient] response missing data array");let r=e.data;if(r.length!==t)throw new Error(`[EmbedderEndpointClient] response count mismatch: expected ${t}, got ${r.length}`);let s=r.map((i,o)=>({idx:typeof i.index=="number"?i.index:o,embedding:i.embedding}));return s.sort((i,o)=>i.idx-o.idx),s.map(({embedding:i},o)=>{if(typeof i=="string")throw new Error(`[EmbedderEndpointClient] received base64 embedding at position ${o} \u2014 server ignored encoding_format=float. Configure the server to return float arrays.`);if(!Array.isArray(i))throw new Error(`[EmbedderEndpointClient] missing embedding at position ${o}`);if(i.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch at position ${o}: expected ${this.opts.expectedDim}, got ${i.length}`);return L(i)})}postEmbeddings(e){let t=JSON.stringify({model:this.opts.model,input:e,encoding_format:"float"});return this.request(oe,t)}request(e,t){let r={"content-type":"application/json","content-length":Buffer.byteLength(t),accept:"application/json"};this.opts.token&&(r.authorization=`Bearer ${this.opts.token}`);let s={method:"POST",path:e,headers:r,agent:this.agent},i,o;this.parsed.transport==="unix"?(i={...s,socketPath:this.parsed.socketPath},o=x.request):(i={...s,host:this.parsed.host,port:this.parsed.port,protocol:this.parsed.protocol},o=this.parsed.transport==="https"?R.request:x.request);let d=this.parsed.safeUrl,l=this.opts.connectTimeoutMs,C=this.opts.requestTimeoutMs;return new Promise((b,N)=>{let E=!1,M=a=>{E||(E=!0,b(a))},f=a=>{E||(E=!0,N(a))},y=o(i,a=>{let m=[];a.on("data",u=>m.push(Buffer.from(u))),a.on("end",()=>{let u=Buffer.concat(m).toString("utf-8");if(!a.statusCode||a.statusCode<200||a.statusCode>=300){f(new Error(`[EmbedderEndpointClient] HTTP ${a.statusCode} from ${d}: ${u.slice(0,200)}`));return}try{let g=JSON.parse(u);M(g)}catch(g){f(new Error(`[EmbedderEndpointClient] invalid JSON from ${d}: ${g.message}`))}}),a.on("error",u=>f(u))});y.on("socket",a=>{a.setTimeout(l);let m=()=>{a.setTimeout(C)};a.connecting?a.once("connect",m):m(),a.on("timeout",()=>{let u=a.connecting?"connect":"request",g=a.connecting?l:C,A=new Error(`[EmbedderEndpointClient] ${u} timeout after ${g}ms`);f(A),y.destroy(A)})}),y.on("error",a=>f(a)),y.write(t),y.end()})}};import{join as H}from"node:path";import{existsSync as ae,mkdirSync as de}from"node:fs";import{createRequire as le}from"node:module";var pe=le(import.meta.url);function ce(){let n=process.env.AQE_MEMORY_PATH;return n&&n.length>0?n:H(process.cwd(),".agentic-qe","memory.db")}var j="_system",K="embedder_identity:",v=null,_=!1;function G(){if(v)return v;if(_)return null;try{let n=pe("better-sqlite3"),e=ce(),t=H(e,"..");ae(t)||de(t,{recursive:!0});let r=new n(e);return r.pragma("journal_mode = WAL"),r.pragma("busy_timeout = 5000"),r.exec(`
3
3
  CREATE TABLE IF NOT EXISTS kv_store (
4
4
  key TEXT NOT NULL,
5
5
  namespace TEXT NOT NULL,
@@ -9,4 +9,4 @@ import{a as S,c as ne}from"./chunk-6ZCAZ3TR.js";import{b as L,d as B}from"./chun
9
9
  PRIMARY KEY (namespace, key)
10
10
  );
11
11
  CREATE INDEX IF NOT EXISTS idx_kv_namespace ON kv_store(namespace);
12
- `),v=r,r}catch{return _=!0,null}}function Q(n){let e=K();if(!e)return null;try{let t=e.prepare("SELECT value FROM kv_store WHERE namespace = ? AND key = ?").get(j,G+n);if(!t)return null;let r=JSON.parse(t.value);return!r.fingerprint||typeof r.dim!="number"?null:{fingerprint:r.fingerprint,dim:r.dim,endpoint:r.endpoint}}catch{return null}}function J(n){let e=K();if(!e)return;let t={fingerprint:n.fingerprint,dim:n.dim,endpoint:n.endpoint,updatedAt:Date.now()};e.prepare("INSERT OR REPLACE INTO kv_store (key, namespace, value) VALUES (?, ?, ?)").run(G+n.endpoint,j,JSON.stringify(t))}function Y(){if(v)try{v.close()}catch{}v=null,_=!1}var z=null,h=null,x=null,k=!1,R="",w=null,c=null,F={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},p=new Map,V=36e5;function q(n){return c?`endpoint:${c.fingerprint}:${n}`:`inproc:${n}`}function Z(n){let e=n.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function ee(n={}){if(k)throw new Error(`Transformer initialization previously failed: ${R}`);if(x)return x;let e={...F,...n};return x=(async()=>{try{if(e.endpoint){let i=X(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${i}`),w=new P({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:N()}),c=await w.probe(),console.log(`[RealEmbeddings] Endpoint identity: dim=${c.dim} fingerprint=${c.fingerprint}`);try{let o=Q(c.endpoint);o&&o.fingerprint!==c.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${o.fingerprint} dim=${o.dim}, current fingerprint=${c.fingerprint} dim=${c.dim}. Vectors written before this change may no longer be comparable.`),J(c)}catch(o){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${S(o)}`)}h=ue(w);return}let t;try{t=await import("./transformers-QL3AG25C.js")}catch{throw new Error('In-process embeddings require the optional package "@huggingface/transformers", which is not installed. Either run `npm install @huggingface/transformers`, or configure an embedding endpoint (EmbeddingConfig.endpoint / AQE_EMBEDDING_ENDPOINT) so no local model is loaded.')}z=t.pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let r=performance.now();h=await z("feature-extraction",e.modelName,{quantized:e.quantized});let s=performance.now()-r;console.log(`[RealEmbeddings] Model loaded in ${s.toFixed(0)}ms`)}catch(t){throw k=!0,R=S(t),new Error(`Failed to initialize transformer model: ${R}`)}})(),x}function ue(n){return async e=>{let t=Array.isArray(e)?e:[e],r=await n.embed(t),s=r[0]?.length??N(),i=new Float32Array(t.length*s);for(let o=0;o<r.length;o++)i.set(r[o],o*s);return{data:i,dims:[t.length,s]}}}async function xe(n,e={}){let t={...F,...e};if(Z(n))return new Array(N()).fill(0);if(h||await ee(e),!h)throw new Error("Embedding model failed to initialize");let r=q(n);if(t.enableCache){let l=p.get(r);if(l&&Date.now()-l.timestamp<V)return l.embedding}let s=performance.now(),i=await h(n,{pooling:"mean",normalize:!0}),o=Array.from(i.data),d=performance.now()-s;if(d>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${d.toFixed(1)}ms for "${n.slice(0,50)}..."`),t.enableCache){if(p.size>=t.maxCacheSize){let l=p.keys().next().value;l&&p.delete(l)}p.set(r,{embedding:o,timestamp:Date.now()})}return o}async function Ce(n,e={}){let t={...F,...e},r=[],s=[],i=new Array(n.length).fill(null),o=[];for(let d=0;d<n.length;d++)Z(n[d])?i[d]=new Array(N()).fill(0):o.push(d);if(o.length===0)return i;if(h||await ee(e),!h)throw new Error("Embedding model failed to initialize");if(t.enableCache)for(let d of o){let l=p.get(q(n[d]));l&&Date.now()-l.timestamp<V?i[d]=l.embedding:(r.push(n[d]),s.push(d))}else for(let d of o)r.push(n[d]),s.push(d);if(r.length>0){let d=performance.now(),l=32;for(let b=0;b<r.length;b+=l){let D=Math.min(b+l,r.length),E=r.slice(b,D),M=await h(E,{pooling:"mean",normalize:!0}),f=M.dims||[E.length,384],y=f[0],a=f[1];for(let m=0;m<y;m++){let u=m*a,g=Array.from(M.data.slice(u,u+a)),A=b+m,te=s[A];if(i[te]=g,t.enableCache){if(p.size>=t.maxCacheSize){let U=p.keys().next().value;U&&p.delete(U)}p.set(q(r[A]),{embedding:g,timestamp:Date.now()})}}}let C=performance.now()-d;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${C.toFixed(0)}ms`)}return i.filter(d=>d!==null)}function Me(){p.clear(),console.log("[RealEmbeddings] Cache cleared")}function Pe(){return{size:p.size,hitRate:0}}function Oe(){return!k&&h!==null}function N(){return 384}function Re(){z=null,h=null,x=null,k=!1,R="",p.clear(),w&&w.close(),w=null,c=null,Y()}function ke(){return w!==null}function Ne(){return c}export{F as a,xe as b,Ce as c,Me as d,Pe as e,Oe as f,N as g,Re as h,ke as i,Ne as j};
12
+ `),v=r,r}catch{return _=!0,null}}function Q(n){let e=G();if(!e)return null;try{let t=e.prepare("SELECT value FROM kv_store WHERE namespace = ? AND key = ?").get(j,K+n);if(!t)return null;let r=JSON.parse(t.value);return!r.fingerprint||typeof r.dim!="number"?null:{fingerprint:r.fingerprint,dim:r.dim,endpoint:r.endpoint}}catch{return null}}function J(n){let e=G();if(!e)return;let t={fingerprint:n.fingerprint,dim:n.dim,endpoint:n.endpoint,updatedAt:Date.now()};e.prepare("INSERT OR REPLACE INTO kv_store (key, namespace, value) VALUES (?, ?, ?)").run(K+n.endpoint,j,JSON.stringify(t))}function Y(){if(v)try{v.close()}catch{}v=null,_=!1}var z=null,h=null,I=null,k=!1,O="",w=null,c=null,F={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},p=new Map,V=36e5;function q(n){return c?`endpoint:${c.fingerprint}:${n}`:`inproc:${n}`}function Z(n){let e=n.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function ee(n={}){if(k)throw new Error(`Transformer initialization previously failed: ${O}`);if(I)return I;let e={...F,...n};return I=(async()=>{try{if(e.endpoint){let i=X(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${i}`),w=new P({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:D()}),c=await w.probe(),console.log(`[RealEmbeddings] Endpoint identity: dim=${c.dim} fingerprint=${c.fingerprint}`);try{let o=Q(c.endpoint);o&&o.fingerprint!==c.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${o.fingerprint} dim=${o.dim}, current fingerprint=${c.fingerprint} dim=${c.dim}. Vectors written before this change may no longer be comparable.`),J(c)}catch(o){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${S(o)}`)}h=ue(w);return}let t;try{t=await import("./transformers-A5REG7OI.js")}catch{throw new Error('In-process embeddings require the optional package "@huggingface/transformers", which is not installed. Either run `npm install @huggingface/transformers`, or configure an embedding endpoint (EmbeddingConfig.endpoint / AQE_EMBEDDER_ENDPOINT) so no local model is loaded.')}z=t.pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let r=performance.now();h=await z("feature-extraction",e.modelName,{quantized:e.quantized});let s=performance.now()-r;console.log(`[RealEmbeddings] Model loaded in ${s.toFixed(0)}ms`)}catch(t){throw k=!0,O=S(t),new Error(`Failed to initialize transformer model: ${O}`)}})(),I}function ue(n){return async e=>{let t=Array.isArray(e)?e:[e],r=await n.embed(t),s=r[0]?.length??D(),i=new Float32Array(t.length*s);for(let o=0;o<r.length;o++)i.set(r[o],o*s);return{data:i,dims:[t.length,s]}}}async function Ie(n,e={}){let t={...F,...e};if(Z(n))return new Array(D()).fill(0);if(h||await ee(e),!h)throw new Error("Embedding model failed to initialize");let r=q(n);if(t.enableCache){let l=p.get(r);if(l&&Date.now()-l.timestamp<V)return l.embedding}let s=performance.now(),i=await h(n,{pooling:"mean",normalize:!0}),o=Array.from(i.data),d=performance.now()-s;if(d>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${d.toFixed(1)}ms for "${n.slice(0,50)}..."`),t.enableCache){if(p.size>=t.maxCacheSize){let l=p.keys().next().value;l&&p.delete(l)}p.set(r,{embedding:o,timestamp:Date.now()})}return o}async function Ce(n,e={}){let t={...F,...e},r=[],s=[],i=new Array(n.length).fill(null),o=[];for(let d=0;d<n.length;d++)Z(n[d])?i[d]=new Array(D()).fill(0):o.push(d);if(o.length===0)return i;if(h||await ee(e),!h)throw new Error("Embedding model failed to initialize");if(t.enableCache)for(let d of o){let l=p.get(q(n[d]));l&&Date.now()-l.timestamp<V?i[d]=l.embedding:(r.push(n[d]),s.push(d))}else for(let d of o)r.push(n[d]),s.push(d);if(r.length>0){let d=performance.now(),l=32;for(let b=0;b<r.length;b+=l){let N=Math.min(b+l,r.length),E=r.slice(b,N),M=await h(E,{pooling:"mean",normalize:!0}),f=M.dims||[E.length,384],y=f[0],a=f[1];for(let m=0;m<y;m++){let u=m*a,g=Array.from(M.data.slice(u,u+a)),A=b+m,te=s[A];if(i[te]=g,t.enableCache){if(p.size>=t.maxCacheSize){let U=p.keys().next().value;U&&p.delete(U)}p.set(q(r[A]),{embedding:g,timestamp:Date.now()})}}}let C=performance.now()-d;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${C.toFixed(0)}ms`)}return i.filter(d=>d!==null)}function Me(){p.clear(),console.log("[RealEmbeddings] Cache cleared")}function Pe(){return{size:p.size,hitRate:0}}function Re(){return!k&&h!==null}function D(){return 384}function Oe(){z=null,h=null,I=null,k=!1,O="",p.clear(),w&&w.close(),w=null,c=null,Y()}function ke(){return w!==null}function De(){return c}export{F as a,Ie as b,Ce as c,Me as d,Pe as e,Re as f,D as g,Oe as h,ke as i,De as j};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.5");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.6");process.exit(0)}
2
2
  var i={domain:"test-generation",bestPractices:["Follow Arrange-Act-Assert (AAA) pattern for clear test structure","One logical assertion per test - test one behavior at a time","Use descriptive test names: should_returnValue_when_condition","Mock external dependencies to isolate unit under test","Test edge cases and boundary conditions, not just happy paths","Keep tests deterministic - avoid time-dependent assertions","Use test data builders or factories for complex objects","Prefer integration tests for workflows, unit tests for logic","Maintain test independence - no shared mutable state between tests","Write failing test first (TDD Red) before implementation"],antiPatterns:[{name:"God Test",description:"A single test that verifies too many behaviors",reason:"Hard to diagnose failures, brittle, slow to run",alternative:"Split into focused tests, each verifying one behavior",detection:"expect.*expect.*expect.*expect.*expect"},{name:"Mystery Guest",description:"Test relies on external data files or state not visible in test",reason:"Tests are hard to understand and maintain",alternative:"Make test data explicit within the test or use fixtures"},{name:"Eager Test",description:"Test that verifies more than needed for the current behavior",reason:"Creates unnecessary coupling, breaks easily",alternative:"Only assert what is necessary for this specific test case"},{name:"Flaky Assertion",description:"Assertions that depend on timing, order, or external state",reason:"Creates unreliable test suite, erodes trust",alternative:"Use deterministic assertions, mock time/random",detection:"setTimeout|Date\\.now|Math\\.random"},{name:"Test Code Duplication",description:"Same setup or assertion code repeated across tests",reason:"Maintenance burden, inconsistency risk",alternative:"Extract to beforeEach, helpers, or fixtures"}],frameworkGuidance:{jest:["Use describe blocks to group related tests","Prefer toEqual for deep equality, toBe for primitives","Use jest.mock() at module level for consistent mocking","Use jest.spyOn for partial mocking of objects","Enable --coverage to track test coverage"],vitest:["Use vi.mock() for module mocking","Prefer vi.fn() over jest.fn() syntax","Use vitest/ui for interactive test debugging","Enable browser mode for component tests","Use inline snapshots for small expected values"],mocha:["Use beforeEach/afterEach for setup/teardown","Combine with chai for assertions","Use sinon for spies, stubs, and mocks","Set appropriate timeouts for async tests"],pytest:["Use fixtures for reusable test setup","Use parametrize for data-driven tests","Use conftest.py for shared fixtures","Use pytest.raises for exception testing","Use pytest-cov for coverage reporting"],junit:["Use @BeforeEach and @AfterEach for setup/teardown","Use @DisplayName for readable test names","Use @ParameterizedTest for data-driven tests","Use Mockito for mocking dependencies"],testng:["Use @BeforeMethod and @AfterMethod appropriately","Use @DataProvider for parameterized tests","Configure test groups for selective execution"],playwright:["Use page.locator() for resilient element selection","Use expect(locator) for auto-waiting assertions","Use page.waitForLoadState for navigation","Use test.describe for grouping tests","Use fixtures for reusable browser contexts"],cypress:["Use cy.intercept() for API mocking","Avoid conditional testing - use deterministic state","Use data-cy attributes for stable selectors","Use cy.within() for scoped queries","Prefer cy.contains() for text-based selection"],selenium:["Use explicit waits over implicit waits","Use Page Object Model for maintainability","Handle stale element references with retry logic","Clean up browser state between tests"]},languageGuidance:{typescript:["Use type assertions in tests for better IDE support","Create typed test fixtures and builders","Use satisfies operator for test data validation","Mock types with ts-mockito or typed mocking libs"],javascript:["Use JSDoc comments for test documentation","Consider TypeScript for larger test suites","Use ESLint with testing plugins"],python:["Use type hints in test functions","Use dataclasses for test data","Follow PEP 8 naming: test_should_do_something"],java:["Use AssertJ for fluent assertions","Use Lombok for test data classes","Follow naming: shouldDoSomething_whenCondition"],go:["Use table-driven tests for multiple cases","Use testify for assertions and mocking","Place tests in _test.go files"],rust:["Use #[test] attribute for test functions","Use assert!, assert_eq!, assert_ne! macros","Place unit tests in same file with #[cfg(test)]"],csharp:["Use xUnit or NUnit for testing","Use FluentAssertions for readable assertions","Use Moq for mocking interfaces"],kotlin:["Use kotest for BDD-style testing","Use MockK for Kotlin-first mocking","Use data classes for test fixtures"]},examples:[{title:"Unit Test Template (TypeScript + Vitest)",description:"Standard AAA pattern for unit tests",content:`describe('UserService', () => {
3
3
  describe('createUser', () => {
4
4
  it('should create user with valid data', async () => {
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.5");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.6");process.exit(0)}
2
2
  import{writeFileSync as p,readFileSync as m}from"node:fs";import{resolve as f,dirname as c,join as d}from"node:path";import{mkdirSync as g}from"node:fs";import{fileURLToPath as h}from"node:url";function $(){try{let e=typeof __dirname<"u"?__dirname:c(h(import.meta.url));for(let t=0;t<5;t++){let n=d(e,"package.json");try{let r=JSON.parse(m(n,"utf-8"));if(r.version)return r.version}catch{}e=c(e)}}catch{}return"unknown"}var T=["-F, --format <format>","Output format (text|json|sarif|junit|markdown)","text"],x=["-o, --output <path>","Write output to file instead of stdout"];function C(e,t,n){if(t){let r=f(t);g(c(r),{recursive:!0}),p(r,e,"utf-8"),n&&console.log(n),console.log(`Output written to: ${r}`)}else console.log(e)}function R(e){return JSON.stringify(e,null,2)}var v="https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json";function w(e){let t=i=>{switch(i.toLowerCase()){case"critical":case"high":return"error";case"medium":return"warning";case"low":case"info":return"note";default:return"warning"}},n=new Map,r=[];for(let i of e.vulnerabilities){let o=i.ruleId||`AQE/${i.type.replace(/\s+/g,"-").toLowerCase()}`;n.has(o)||n.set(o,{id:o,name:i.type,shortDescription:i.type,...i.cweId?{helpUri:`https://cwe.mitre.org/data/definitions/${i.cweId.replace("CWE-","")}.html`}:{}}),r.push({ruleId:o,level:t(i.severity),message:{text:i.message},locations:[{physicalLocation:{artifactLocation:{uri:i.file,uriBaseId:"%SRCROOT%"},region:{startLine:i.line,startColumn:1}}}],...i.cweId?{taxa:[{id:i.cweId,toolComponent:{name:"CWE"}}]}:{}})}let s={$schema:v,version:"2.1.0",runs:[{tool:{driver:{name:"agentic-qe",version:$(),informationUri:"https://github.com/proffesor-for-testing/agentic-qe",rules:Array.from(n.values()).map(i=>({id:i.id,name:i.name,shortDescription:{text:i.shortDescription},...i.helpUri?{helpUri:i.helpUri}:{},defaultConfiguration:{level:"warning"}}))}},results:r,invocations:[{executionSuccessful:!0,commandLine:`aqe security --sast --format sarif -t ${e.target}`}]}]};return JSON.stringify(s,null,2)}function a(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function I(e){let t=e.tests||[],n=e.passed+e.failed+e.skipped,r=(e.duration/1e3).toFixed(3),s=`<?xml version="1.0" encoding="UTF-8"?>
3
3
  `;if(s+=`<testsuites tests="${n}" failures="${e.failed}" errors="0" time="${r}">
4
4
  `,s+=` <testsuite name="aqe-test-run" tests="${n}" failures="${e.failed}" errors="0" skipped="${e.skipped}" time="${r}" id="${a(e.runId)}">
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.5");process.exit(0)}
2
- import{c}from"./chunk-WSSFH23M.js";function u(r){switch(r.toUpperCase()){case"DEBUG":return 0;case"INFO":return 1;case"WARN":case"WARNING":return 2;case"ERROR":return 3;case"SILENT":case"NONE":case"OFF":return 4;default:return 1}}var f,l=c(()=>{"use strict";f={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR",4:"SILENT"}});var a,s,g,d=c(()=>{"use strict";l();a={includeTimestamp:!0,includeLevel:!0,timestampFormat:"short",prettyPrint:!1,maxContextDepth:3},s=class r{domain;level;config;inheritedContext;constructor(e,n=1,o={},t={}){this.domain=e,this.level=n,this.config={...a,...o},this.inheritedContext=t}debug(e,n){this.level<=0&&this.output(0,e,n)}info(e,n){this.level<=1&&this.output(1,e,n)}warn(e,n){this.level<=2&&this.output(2,e,n)}error(e,n,o){if(this.level<=3){let t={...o};if(n){t.errorName=n.name,t.errorMessage=n.message,n.stack&&(t.stack=n.stack);let i=n;i.cause!==void 0&&(t.cause=String(i.cause))}this.output(3,e,t)}}isEnabled(e){return this.level<=e}getDomain(){return this.domain}child(e){return new r(this.domain,this.level,this.config,{...this.inheritedContext,...e})}output(e,n,o){let t=this.format(e,n,o);switch(e){case 0:console.debug(t);break;case 1:console.info(t);break;case 2:console.warn(t);break;case 3:console.error(t);break}}format(e,n,o){let t=[];this.config.includeTimestamp&&t.push(this.formatTimestamp()),this.config.includeLevel&&t.push(this.formatLevel(e)),t.push(`[${this.domain}]`),t.push(n);let i=this.mergeContext(o);return i&&Object.keys(i).length>0&&t.push(this.formatContext(i)),t.join(" ")}formatTimestamp(){let e=new Date;if(this.config.timestampFormat==="iso")return`[${e.toISOString()}]`;let n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),t=String(e.getSeconds()).padStart(2,"0"),i=String(e.getMilliseconds()).padStart(3,"0");return`[${n}:${o}:${t}.${i}]`}formatLevel(e){return`[${f[e].padEnd(5)}]`}mergeContext(e){if(!(!e&&Object.keys(this.inheritedContext).length===0))return{...this.inheritedContext,...e}}formatContext(e){try{return this.config.prettyPrint?`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.6");process.exit(0)}
2
+ import{c}from"./chunk-ISOTSVI7.js";function u(r){switch(r.toUpperCase()){case"DEBUG":return 0;case"INFO":return 1;case"WARN":case"WARNING":return 2;case"ERROR":return 3;case"SILENT":case"NONE":case"OFF":return 4;default:return 1}}var f,l=c(()=>{"use strict";f={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR",4:"SILENT"}});var a,s,g,d=c(()=>{"use strict";l();a={includeTimestamp:!0,includeLevel:!0,timestampFormat:"short",prettyPrint:!1,maxContextDepth:3},s=class r{domain;level;config;inheritedContext;constructor(e,n=1,o={},t={}){this.domain=e,this.level=n,this.config={...a,...o},this.inheritedContext=t}debug(e,n){this.level<=0&&this.output(0,e,n)}info(e,n){this.level<=1&&this.output(1,e,n)}warn(e,n){this.level<=2&&this.output(2,e,n)}error(e,n,o){if(this.level<=3){let t={...o};if(n){t.errorName=n.name,t.errorMessage=n.message,n.stack&&(t.stack=n.stack);let i=n;i.cause!==void 0&&(t.cause=String(i.cause))}this.output(3,e,t)}}isEnabled(e){return this.level<=e}getDomain(){return this.domain}child(e){return new r(this.domain,this.level,this.config,{...this.inheritedContext,...e})}output(e,n,o){let t=this.format(e,n,o);switch(e){case 0:console.debug(t);break;case 1:console.info(t);break;case 2:console.warn(t);break;case 3:console.error(t);break}}format(e,n,o){let t=[];this.config.includeTimestamp&&t.push(this.formatTimestamp()),this.config.includeLevel&&t.push(this.formatLevel(e)),t.push(`[${this.domain}]`),t.push(n);let i=this.mergeContext(o);return i&&Object.keys(i).length>0&&t.push(this.formatContext(i)),t.join(" ")}formatTimestamp(){let e=new Date;if(this.config.timestampFormat==="iso")return`[${e.toISOString()}]`;let n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),t=String(e.getSeconds()).padStart(2,"0"),i=String(e.getMilliseconds()).padStart(3,"0");return`[${n}:${o}:${t}.${i}]`}formatLevel(e){return`[${f[e].padEnd(5)}]`}mergeContext(e){if(!(!e&&Object.keys(this.inheritedContext).length===0))return{...this.inheritedContext,...e}}formatContext(e){try{return this.config.prettyPrint?`
3
3
  `+JSON.stringify(e,this.createReplacer(),2):JSON.stringify(e,this.createReplacer())}catch{return"[unserializable context]"}}createReplacer(){let e=new WeakSet,n=0;return(o,t)=>{if(typeof t=="object"&&t!==null){if(n>=this.config.maxContextDepth)return"[object]";if(e.has(t))return"[circular]";e.add(t),n++}return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:typeof t=="bigint"?t.toString():typeof t=="function"?"[function]":typeof t=="symbol"?t.toString():t}}},g=class{domain;constructor(e="null"){this.domain=e}debug(e,n){}info(e,n){}warn(e,n){}error(e,n,o){}isEnabled(e){return!1}getDomain(){return this.domain}child(e){return this}}});function F(r,e){return L.create(r,e)}var v,L,m=c(()=>{"use strict";l();d();v={defaultLevel:1,domainLevels:new Map,consoleConfig:a,silent:!1},L=class{static config={...v};static customProvider=null;static instances=new Map;static setLevel(e){this.config.defaultLevel=e,this.instances.clear()}static setLevelFromString(e){this.setLevel(u(e))}static getLevel(){return this.config.defaultLevel}static setDomainLevel(e,n){this.config.domainLevels.set(e,n),this.instances.delete(e)}static getDomainLevel(e){return this.config.domainLevels.get(e)??this.config.defaultLevel}static clearDomainLevel(e){this.config.domainLevels.delete(e),this.instances.delete(e)}static configure(e){this.config.consoleConfig={...this.config.consoleConfig,...e},this.instances.clear()}static setSilent(e){this.config.silent=e,this.instances.clear()}static isSilent(){return this.config.silent}static setProvider(e){this.customProvider=e,this.instances.clear()}static create(e,n){if(!n&&this.instances.has(e))return this.instances.get(e);let o=this.getDomainLevel(e),t;return this.config.silent?t=new g(e):this.customProvider?t=this.customProvider(e,o,n):t=new s(e,o,this.config.consoleConfig,n),n||this.instances.set(e,t),t}static getLogger(e,n){return this.create(e,n)}static reset(){this.config={defaultLevel:1,domainLevels:new Map,consoleConfig:{...a},silent:!1},this.customProvider=null,this.instances.clear()}static initFromEnv(){let e=process.env.LOG_LEVEL;e&&this.setLevelFromString(e);let n=process.env.LOG_TIMESTAMP;n!==void 0&&this.configure({includeTimestamp:n.toLowerCase()==="true"});let o=process.env.LOG_PRETTY;o!==void 0&&this.configure({prettyPrint:o.toLowerCase()==="true"})}static getStats(){return{cachedLoggers:this.instances.size,domains:Array.from(this.instances.keys()),domainOverrides:this.config.domainLevels.size,currentLevel:this.config.defaultLevel,silent:this.config.silent}}}});export{l as a,d as b,L as c,F as d,m as e};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.5");process.exit(0)}
2
- import{b as m,c as y}from"./chunk-7M4X6WTF.js";import{e as S,f as A}from"./chunk-64GTU5LR.js";import{a as R,b as g,c as v}from"./chunk-HMNBNGNO.js";import{a as p,g as b}from"./chunk-WSSFH23M.js";y();var s=null,f=!1;function w(t){s=t,f=t!==null}var E=(()=>{let t=process.env.AQE_RVF_SIZE_GUARD_BYTES,r=t?Number(t):NaN;return Number.isFinite(r)&&r>0?r:256*1024*1024})(),C=(()=>{let t=process.env.AQE_RVF_DEAD_RATIO_THRESHOLD,r=t?Number(t):NaN;return Number.isFinite(r)&&r>0&&r<=1?r:.3})();function _(t=".agentic-qe",r=384){if(f)return s;f=!0;try{let{isRvfNativeAvailable:e,createRvfStore:o,openRvfStore:i}=(A(),b(S));if(!e())return console.warn("[RVF] Native bindings unavailable \u2014 agent branching and dream COW disabled. Install @ruvector/rvf-node to enable."),null;let l=p("path"),c=l.isAbsolute(t)?t:l.join(process.env.AQE_PROJECT_ROOT??m(),t),u=l.join(c,"patterns.rvf");return s=$(i,o,u,r),N(s,u),s}catch(e){return console.warn("[RVF] Shared adapter init failed:",e instanceof Error?e.message:e),null}}function $(t,r,e,o){let i=()=>{try{return{adapter:t(e),err:null}}catch(n){return{adapter:null,err:n}}},l=n=>{let a=n instanceof Error?n.message:String(n);return a.includes("LockHeld")||a.includes("0x0300")},{adapter:c,err:u}=i();if(!c&&l(u))try{let n=p("fs"),a=`${e}.lock`;n.existsSync(a)&&g(e)?console.warn(`[RVF] ${e} is locked by a live process (pid ${R(e)}) \u2014 not breaking the lock; degrading to SQLite for this run.`):n.existsSync(a)&&(n.unlinkSync(a),console.warn(`[RVF] Removed stale lock file at ${a} (prior process exited without closing). Retrying open. If you see this repeatedly under live concurrency, file an issue.`),{adapter:c,err:u}=i())}catch(n){process.env.DEBUG&&console.debug("[RVF] stale-lock recovery failed:",n instanceof Error?n.message:n)}if(c){let n=c.dimension();if(n===o)return c;console.warn(`[RVF] patterns.rvf dimension mismatch: file=${n} requested=${o} \u2014 closing and degrading. Delete the .rvf file to recreate at the requested dim.`);try{c.close()}catch{}throw new Error(`RVF dimension mismatch (file=${n}, requested=${o})`)}try{return r(e,o)}catch(n){try{let a=t(e);if(a.dimension()!==o){try{a.close()}catch{}throw new Error(`RVF dimension mismatch after race (file=${a.dimension()}, requested=${o})`)}return a}catch{if(v(e,n instanceof Error?n.message:String(n)))return r(e,o);throw n instanceof Error?n:new Error(String(n))}}}function h(t,r){if(r?.force)return{shouldCompact:!0,trigger:"force"};let e=r?.sizeGuardBytes??E,o=r?.deadRatioThreshold??C;return t.fileSizeBytes>=e?{shouldCompact:!0,trigger:"size-guard"}:(t.deadSpaceRatio??0)>=o?{shouldCompact:!0,trigger:"dead-ratio"}:{shouldCompact:!1,trigger:"none"}}function k(t){if(!s)return null;let r;try{r=s.status()}catch{return null}let e=h(r,t);if(!e.shouldCompact)return null;let o=r.fileSizeBytes,i;try{i=s.compact()}catch{return null}return i?((i.bytesReclaimed>0||i.segmentsCompacted>0)&&console.log(`[RVF] compacted patterns.rvf: reclaimed ${d(i.bytesReclaimed)} (${i.segmentsCompacted} segments, fileSize ${d(o)} \u2192 ${d(Math.max(0,o-i.bytesReclaimed))}, trigger: ${e.trigger})`),i):null}function N(t,r){try{let e=t.status(),o=h(e);if(!o.shouldCompact)return null;let i=t.compact();return i&&(i.bytesReclaimed>0||i.segmentsCompacted>0)&&console.log(`[RVF] boot-time compact (${r}): reclaimed ${d(i.bytesReclaimed)} from ${i.segmentsCompacted} segments (trigger: ${o.trigger})`),i}catch(e){return process.env.DEBUG&&console.debug("[RVF] boot-time compact guard skipped:",e instanceof Error?e.message:e),null}}function d(t){if(!Number.isFinite(t)||t<0)return`${t}B`;let r=["B","KB","MB","GB","TB"],e=0,o=t;for(;o>=1024&&e<r.length-1;)o/=1024,e++;return`${o.toFixed(e===0?0:1)}${r[e]}`}function T(){if(s){try{s.close()}catch{}s=null}f=!1}export{w as a,_ as b,h as c,k as d,N as e,T as f};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.6");process.exit(0)}
2
+ import{b as m,c as y}from"./chunk-SZO6JIFM.js";import{e as S,f as A}from"./chunk-KMCI3RGD.js";import{a as R,b as g,c as v}from"./chunk-PGDDPZ7W.js";import{a as p,g as b}from"./chunk-ISOTSVI7.js";y();var s=null,f=!1;function w(t){s=t,f=t!==null}var E=(()=>{let t=process.env.AQE_RVF_SIZE_GUARD_BYTES,r=t?Number(t):NaN;return Number.isFinite(r)&&r>0?r:256*1024*1024})(),C=(()=>{let t=process.env.AQE_RVF_DEAD_RATIO_THRESHOLD,r=t?Number(t):NaN;return Number.isFinite(r)&&r>0&&r<=1?r:.3})();function _(t=".agentic-qe",r=384){if(f)return s;f=!0;try{let{isRvfNativeAvailable:e,createRvfStore:o,openRvfStore:i}=(A(),b(S));if(!e())return console.warn("[RVF] Native bindings unavailable \u2014 agent branching and dream COW disabled. Install @ruvector/rvf-node to enable."),null;let l=p("path"),c=l.isAbsolute(t)?t:l.join(process.env.AQE_PROJECT_ROOT??m(),t),u=l.join(c,"patterns.rvf");return s=$(i,o,u,r),N(s,u),s}catch(e){return console.warn("[RVF] Shared adapter init failed:",e instanceof Error?e.message:e),null}}function $(t,r,e,o){let i=()=>{try{return{adapter:t(e),err:null}}catch(n){return{adapter:null,err:n}}},l=n=>{let a=n instanceof Error?n.message:String(n);return a.includes("LockHeld")||a.includes("0x0300")},{adapter:c,err:u}=i();if(!c&&l(u))try{let n=p("fs"),a=`${e}.lock`;n.existsSync(a)&&g(e)?console.warn(`[RVF] ${e} is locked by a live process (pid ${R(e)}) \u2014 not breaking the lock; degrading to SQLite for this run.`):n.existsSync(a)&&(n.unlinkSync(a),console.warn(`[RVF] Removed stale lock file at ${a} (prior process exited without closing). Retrying open. If you see this repeatedly under live concurrency, file an issue.`),{adapter:c,err:u}=i())}catch(n){process.env.DEBUG&&console.debug("[RVF] stale-lock recovery failed:",n instanceof Error?n.message:n)}if(c){let n=c.dimension();if(n===o)return c;console.warn(`[RVF] patterns.rvf dimension mismatch: file=${n} requested=${o} \u2014 closing and degrading. Delete the .rvf file to recreate at the requested dim.`);try{c.close()}catch{}throw new Error(`RVF dimension mismatch (file=${n}, requested=${o})`)}try{return r(e,o)}catch(n){try{let a=t(e);if(a.dimension()!==o){try{a.close()}catch{}throw new Error(`RVF dimension mismatch after race (file=${a.dimension()}, requested=${o})`)}return a}catch{if(v(e,n instanceof Error?n.message:String(n)))return r(e,o);throw n instanceof Error?n:new Error(String(n))}}}function h(t,r){if(r?.force)return{shouldCompact:!0,trigger:"force"};let e=r?.sizeGuardBytes??E,o=r?.deadRatioThreshold??C;return t.fileSizeBytes>=e?{shouldCompact:!0,trigger:"size-guard"}:(t.deadSpaceRatio??0)>=o?{shouldCompact:!0,trigger:"dead-ratio"}:{shouldCompact:!1,trigger:"none"}}function k(t){if(!s)return null;let r;try{r=s.status()}catch{return null}let e=h(r,t);if(!e.shouldCompact)return null;let o=r.fileSizeBytes,i;try{i=s.compact()}catch{return null}return i?((i.bytesReclaimed>0||i.segmentsCompacted>0)&&console.log(`[RVF] compacted patterns.rvf: reclaimed ${d(i.bytesReclaimed)} (${i.segmentsCompacted} segments, fileSize ${d(o)} \u2192 ${d(Math.max(0,o-i.bytesReclaimed))}, trigger: ${e.trigger})`),i):null}function N(t,r){try{let e=t.status(),o=h(e);if(!o.shouldCompact)return null;let i=t.compact();return i&&(i.bytesReclaimed>0||i.segmentsCompacted>0)&&console.log(`[RVF] boot-time compact (${r}): reclaimed ${d(i.bytesReclaimed)} from ${i.segmentsCompacted} segments (trigger: ${o.trigger})`),i}catch(e){return process.env.DEBUG&&console.debug("[RVF] boot-time compact guard skipped:",e instanceof Error?e.message:e),null}}function d(t){if(!Number.isFinite(t)||t<0)return`${t}B`;let r=["B","KB","MB","GB","TB"],e=0,o=t;for(;o>=1024&&e<r.length-1;)o/=1024,e++;return`${o.toFixed(e===0?0:1)}${r[e]}`}function T(){if(s){try{s.close()}catch{}s=null}f=!1}export{w as a,_ as b,h as c,k as d,N as e,T as f};