agentic-qe 3.15.14 → 3.15.16

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 (513) hide show
  1. package/.claude/agents/v3/templates/qx-report-template.html +1 -1
  2. package/.claude/skills/skills-manifest.json +1 -1
  3. package/CHANGELOG.md +136 -0
  4. package/assets/agents/v3/templates/qx-report-template.html +1 -1
  5. package/assets/skills/skills-manifest.json +1 -1
  6. package/dist/audit/witness-chain.d.ts +7 -0
  7. package/dist/audit/witness-chain.js +10 -0
  8. package/dist/cli/bundle.js +6 -6
  9. package/dist/cli/chunks/adapter-6CQ2PIP5.js +2 -0
  10. package/dist/cli/chunks/agent-booster-wasm-45NWEKVS.js +2 -0
  11. package/dist/cli/chunks/{agent-handler-P3IY7XEE.js → agent-handler-LVHMYFEF.js} +2 -2
  12. package/dist/cli/chunks/{agent-memory-branch-WWKC2H3G.js → agent-memory-branch-YDWOJFEQ.js} +2 -2
  13. package/dist/cli/chunks/aqe-learning-engine-73RR52VS.js +2 -0
  14. package/dist/cli/chunks/{arena-EIV5OALF.js → arena-CZKHXDDS.js} +2 -2
  15. package/dist/cli/chunks/{arena-4BMFF6BS.js → arena-ELDZH3CZ.js} +4 -4
  16. package/dist/cli/chunks/{audit-DNTI453H.js → audit-5MT4T47Z.js} +3 -3
  17. package/dist/cli/chunks/base-SMCMMVGP.js +2 -0
  18. package/dist/cli/chunks/{better-sqlite3-TQBQGNC6.js → better-sqlite3-6TGYPC2B.js} +2 -2
  19. package/dist/cli/chunks/{brain-handler-HY57CNAO.js → brain-handler-HQWZFO52.js} +3 -3
  20. package/dist/cli/chunks/{branch-enumerator-THPMZPHQ.js → branch-enumerator-WVILM4SO.js} +2 -2
  21. package/dist/cli/chunks/{browser-O6JJOZCK.js → browser-RX5ALU3H.js} +2 -2
  22. package/dist/cli/chunks/browser-workflow-A2MEZ66K.js +2 -0
  23. package/dist/cli/chunks/{chunk-CIINJHOX.js → chunk-24OX5TQJ.js} +1 -1
  24. package/dist/cli/chunks/{chunk-6P4Q4RTC.js → chunk-24QHCVX6.js} +1 -1
  25. package/dist/cli/chunks/{chunk-U6IOQKCT.js → chunk-2H4XH6FT.js} +2 -2
  26. package/dist/cli/chunks/{chunk-OGEIHS76.js → chunk-2YZ4G6NW.js} +1 -1
  27. package/dist/cli/chunks/chunk-32BPDLRZ.js +27 -0
  28. package/dist/cli/chunks/{chunk-5PLBQZ5J.js → chunk-32GN3JKR.js} +1 -1
  29. package/dist/cli/chunks/{chunk-AJVLVF7V.js → chunk-3HD7E6HN.js} +2 -2
  30. package/dist/cli/chunks/{chunk-X7CUI7KH.js → chunk-4D4DENG6.js} +2 -2
  31. package/dist/cli/chunks/{chunk-E2JLAW3U.js → chunk-4LQFBY5L.js} +6 -6
  32. package/dist/cli/chunks/{chunk-E3QIQMMN.js → chunk-4NFQLP6R.js} +1 -1
  33. package/dist/cli/chunks/{chunk-7Y3LXH57.js → chunk-525CFDUE.js} +2 -2
  34. package/dist/cli/chunks/chunk-5B5QPCNU.js +65 -0
  35. package/dist/cli/chunks/{chunk-X6Q2N5S5.js → chunk-5JZRZI4S.js} +2 -2
  36. package/dist/cli/chunks/{chunk-MB4UKUBV.js → chunk-5LAVKGLH.js} +2 -2
  37. package/dist/cli/chunks/chunk-5NNNEWLS.js +755 -0
  38. package/dist/cli/chunks/{chunk-NKOLILT7.js → chunk-5PBLPQ5T.js} +2 -2
  39. package/dist/cli/chunks/chunk-5QO3R3TU.js +6 -0
  40. package/dist/cli/chunks/{chunk-7T6L3LFN.js → chunk-5SPCGMBB.js} +2 -2
  41. package/dist/cli/chunks/{chunk-2QLE6NDW.js → chunk-5V3TI2LG.js} +1 -1
  42. package/dist/cli/chunks/{chunk-A2T56XVL.js → chunk-5VZL4UVN.js} +2 -2
  43. package/dist/cli/chunks/{chunk-TWOV3I3A.js → chunk-63GMRQ25.js} +1 -1
  44. package/dist/cli/chunks/{chunk-YGOSSVY5.js → chunk-63ZKI4PX.js} +6 -6
  45. package/dist/cli/chunks/{chunk-FHPNWHY7.js → chunk-67Z5R7RJ.js} +2 -2
  46. package/dist/cli/chunks/{chunk-PCQZIAXB.js → chunk-6DPYNAOK.js} +2 -2
  47. package/dist/cli/chunks/{chunk-WCM6WE7G.js → chunk-6ICX3FEG.js} +3 -3
  48. package/dist/cli/chunks/{chunk-JB7R77SH.js → chunk-6XXZDV2C.js} +2 -2
  49. package/dist/cli/chunks/{chunk-FJOIBZUB.js → chunk-6ZBXSOX6.js} +2 -2
  50. package/dist/cli/chunks/{chunk-WZQADC5R.js → chunk-72XSEQMW.js} +2 -2
  51. package/dist/cli/chunks/{chunk-AYLEH2UF.js → chunk-7TE5ONQQ.js} +1 -1
  52. package/dist/cli/chunks/{chunk-7QUSNBAA.js → chunk-A5GBXCP5.js} +2 -2
  53. package/dist/cli/chunks/{chunk-7724KXM2.js → chunk-AAMLQ2LF.js} +3 -3
  54. package/dist/cli/chunks/chunk-AG2EWGXS.js +21 -0
  55. package/dist/cli/chunks/{chunk-2UZBLC5H.js → chunk-AGRV5B3T.js} +2 -2
  56. package/dist/cli/chunks/{chunk-V6SE2ZU2.js → chunk-AJMJNQMP.js} +1 -1
  57. package/dist/cli/chunks/{chunk-2HPNGK7A.js → chunk-AR67RJPY.js} +2 -2
  58. package/dist/cli/chunks/{chunk-G7HGUQAE.js → chunk-ASEOFRIG.js} +2 -2
  59. package/dist/cli/chunks/{chunk-7TH4PJSU.js → chunk-BEKDKVQT.js} +2 -2
  60. package/dist/cli/chunks/{chunk-M5JEA6ZY.js → chunk-BY5OF7OH.js} +2 -2
  61. package/dist/cli/chunks/{chunk-OLUOVNUF.js → chunk-C5FP5GW3.js} +2 -2
  62. package/dist/cli/chunks/{chunk-R5RRWLRI.js → chunk-C6D5AHBO.js} +2 -2
  63. package/dist/cli/chunks/{chunk-K7GFYFBO.js → chunk-CAKMOVZ6.js} +2 -2
  64. package/dist/cli/chunks/{chunk-6NIGSY5L.js → chunk-CEYSYSK5.js} +2 -2
  65. package/dist/cli/chunks/{chunk-U4TML2VD.js → chunk-CGGUM2YJ.js} +2 -2
  66. package/dist/cli/chunks/{chunk-YE54T2NQ.js → chunk-CJSHWQXP.js} +2 -2
  67. package/dist/cli/chunks/{chunk-7SQTLUEN.js → chunk-CRPIYUTJ.js} +2 -2
  68. package/dist/cli/chunks/{chunk-65EE2EST.js → chunk-D6COXLYE.js} +2 -2
  69. package/dist/cli/chunks/{chunk-4WLIOPHX.js → chunk-DTMAS2GB.js} +2 -2
  70. package/dist/cli/chunks/{chunk-E7QTWGPI.js → chunk-DVYHMDFR.js} +470 -411
  71. package/dist/cli/chunks/chunk-DXD6K2ZP.js +3 -0
  72. package/dist/cli/chunks/{chunk-HSDWPQQY.js → chunk-E3D4GPLP.js} +3 -3
  73. package/dist/cli/chunks/{chunk-JJHLGGPP.js → chunk-EA4YQVKS.js} +1 -1
  74. package/dist/cli/chunks/{chunk-EIEEST4T.js → chunk-EGYE5UPQ.js} +2 -2
  75. package/dist/cli/chunks/{chunk-O756AOUX.js → chunk-EK7OLYOZ.js} +2 -2
  76. package/dist/cli/chunks/{chunk-57DRT6UA.js → chunk-F742SZAX.js} +2 -2
  77. package/dist/cli/chunks/{chunk-6OI5SK7M.js → chunk-FBDVGRSC.js} +1 -1
  78. package/dist/cli/chunks/{chunk-H3C5FJRH.js → chunk-FDDC72IA.js} +2 -2
  79. package/dist/cli/chunks/{chunk-IQRPR4KB.js → chunk-FL64OUBA.js} +2 -2
  80. package/dist/cli/chunks/{chunk-BNG4J3CE.js → chunk-FLNAW7C4.js} +2 -2
  81. package/dist/cli/chunks/{chunk-C3OIBFAA.js → chunk-G5RHFBAY.js} +2 -2
  82. package/dist/cli/chunks/{chunk-NPCXGX7N.js → chunk-GAHNO6JJ.js} +2 -2
  83. package/dist/cli/chunks/{chunk-PNRPVQGI.js → chunk-GFWHUQSF.js} +2 -2
  84. package/dist/cli/chunks/{chunk-OCN53CCK.js → chunk-GJYHWYXR.js} +2 -2
  85. package/dist/cli/chunks/{chunk-5Z4MO2F3.js → chunk-GQ6TUIKY.js} +1 -1
  86. package/dist/cli/chunks/{chunk-N736GLWZ.js → chunk-GSKMOPL7.js} +2 -2
  87. package/dist/cli/chunks/{chunk-43XHGWYH.js → chunk-HCH4Y6XX.js} +2 -2
  88. package/dist/cli/chunks/{chunk-QP6GL3O5.js → chunk-HGWXF45W.js} +1 -1
  89. package/dist/cli/chunks/{chunk-PGN4TARY.js → chunk-HJ6ZGVTB.js} +2 -2
  90. package/dist/cli/chunks/{chunk-M2TG7VDK.js → chunk-HLUXXCHF.js} +1 -1
  91. package/dist/cli/chunks/{chunk-UMHFTQTR.js → chunk-HVRRLYX6.js} +4 -4
  92. package/dist/cli/chunks/{chunk-L7PC675Y.js → chunk-I7MQIM2U.js} +1 -1
  93. package/dist/cli/chunks/{chunk-JSSU4RIK.js → chunk-IESR7TNB.js} +2 -2
  94. package/dist/cli/chunks/{chunk-H4LYXLAT.js → chunk-IHRXZZQM.js} +1 -1
  95. package/dist/cli/chunks/{chunk-HV43NX4A.js → chunk-IOKYCMTJ.js} +6 -6
  96. package/dist/cli/chunks/{chunk-NZQYJCO6.js → chunk-IOQ6ZQ5W.js} +1 -1
  97. package/dist/cli/chunks/{chunk-JO26SG47.js → chunk-IOYG4VFL.js} +2 -2
  98. package/dist/cli/chunks/{chunk-6O63ZTVX.js → chunk-IUBJVHNB.js} +2 -2
  99. package/dist/cli/chunks/{chunk-XSPMLJCQ.js → chunk-J442IZLE.js} +1 -1
  100. package/dist/cli/chunks/{chunk-LTGQJYYO.js → chunk-J4ELZNLY.js} +2 -2
  101. package/dist/cli/chunks/chunk-J7I6PABJ.js +153 -0
  102. package/dist/cli/chunks/chunk-JDIYMZCQ.js +2 -0
  103. package/dist/cli/chunks/{chunk-TOJF3ZG4.js → chunk-JHQCRRJI.js} +2 -2
  104. package/dist/cli/chunks/{chunk-QUZ745UQ.js → chunk-JQ3DYUMS.js} +2 -2
  105. package/dist/cli/chunks/{chunk-P2TPH3TC.js → chunk-KITOPKRG.js} +2 -2
  106. package/dist/cli/chunks/{chunk-QNQE3EOH.js → chunk-KKU2QGSJ.js} +2 -2
  107. package/dist/cli/chunks/chunk-KL7OKSU2.js +4 -0
  108. package/dist/cli/chunks/{chunk-L5VSLPMW.js → chunk-KNSRL6NO.js} +2 -2
  109. package/dist/cli/chunks/{chunk-INGXD5IX.js → chunk-KPRCB5LT.js} +2 -2
  110. package/dist/cli/chunks/{chunk-GY4P7KAI.js → chunk-KQYJ4VQ5.js} +1 -1
  111. package/dist/cli/chunks/{chunk-Z2S7DNFP.js → chunk-KU2AUFGX.js} +2 -2
  112. package/dist/cli/chunks/{chunk-O5CEL447.js → chunk-KVF4NXGQ.js} +2 -2
  113. package/dist/cli/chunks/{chunk-2IJO3657.js → chunk-KXCLACFG.js} +2 -2
  114. package/dist/cli/chunks/{chunk-ZJGFQK27.js → chunk-L2DWPVNJ.js} +1 -1
  115. package/dist/cli/chunks/{chunk-E7OR6V3V.js → chunk-L6QSTQME.js} +2 -2
  116. package/dist/cli/chunks/{chunk-RE6JTSDM.js → chunk-LE4QJREF.js} +1 -1
  117. package/dist/cli/chunks/{chunk-DSQESXL4.js → chunk-LKTTUHLF.js} +2 -2
  118. package/dist/cli/chunks/{chunk-YGC5QKQ4.js → chunk-LQLPB2T6.js} +2 -2
  119. package/dist/cli/chunks/{chunk-VGZOPQQY.js → chunk-LRSX2FJM.js} +1 -1
  120. package/dist/cli/chunks/chunk-M4FRQ4TE.js +12 -0
  121. package/dist/cli/chunks/chunk-M7WJCTG3.js +2 -0
  122. package/dist/cli/chunks/{chunk-56NSE3LJ.js → chunk-MAFQV4U4.js} +2 -2
  123. package/dist/cli/chunks/{chunk-MKYOE7NE.js → chunk-MD43XRX5.js} +1 -1
  124. package/dist/cli/chunks/{chunk-3TF27MG5.js → chunk-MI5MFHRA.js} +2 -2
  125. package/dist/cli/chunks/{chunk-JK6PMLQQ.js → chunk-MO55CVMT.js} +32 -32
  126. package/dist/cli/chunks/{chunk-X6NJOT3V.js → chunk-N7HL5PHH.js} +1 -1
  127. package/dist/cli/chunks/chunk-NAEWCFQT.js +14 -0
  128. package/dist/cli/chunks/{chunk-WUGXXNK4.js → chunk-NDJ7P2EP.js} +1 -1
  129. package/dist/cli/chunks/{chunk-D5GB5PUU.js → chunk-NO3IV5Q5.js} +1 -1
  130. package/dist/cli/chunks/{chunk-3XACRXBY.js → chunk-NQXXI77K.js} +2 -2
  131. package/dist/cli/chunks/{chunk-EC65UZ77.js → chunk-NVEWF4JV.js} +1 -1
  132. package/dist/cli/chunks/{chunk-JI67T6Q2.js → chunk-NZU4ACBZ.js} +2 -2
  133. package/dist/cli/chunks/chunk-O5W3FIO6.js +63 -0
  134. package/dist/cli/chunks/{chunk-YEFTK4HD.js → chunk-OAEE6JWQ.js} +2 -2
  135. package/dist/cli/chunks/{chunk-JAOCHPYX.js → chunk-OCV2XEWQ.js} +2 -2
  136. package/dist/cli/chunks/{chunk-IDBA5GK2.js → chunk-P3EYRILV.js} +2 -2
  137. package/dist/cli/chunks/{chunk-4RPBODN5.js → chunk-PEQDY4BO.js} +2 -2
  138. package/dist/cli/chunks/{chunk-CPPYZYXC.js → chunk-PF7RBAYL.js} +2 -2
  139. package/dist/cli/chunks/{chunk-WCPSR4MJ.js → chunk-PHT5N7SC.js} +2 -2
  140. package/dist/cli/chunks/{chunk-O2AAYJUV.js → chunk-PINSJCM3.js} +1 -1
  141. package/dist/cli/chunks/{chunk-HEDGFKC5.js → chunk-PPUZWYUG.js} +2 -2
  142. package/dist/cli/chunks/{chunk-XMCSKYDE.js → chunk-QPEOLAAS.js} +1 -1
  143. package/dist/cli/chunks/{chunk-7MUO4DEH.js → chunk-QQWBWEJS.js} +18 -18
  144. package/dist/cli/chunks/{chunk-UFP7SN5V.js → chunk-QVDCVD5D.js} +2 -2
  145. package/dist/cli/chunks/{chunk-NHEG2DLN.js → chunk-RJIEG3NA.js} +2 -2
  146. package/dist/cli/chunks/{chunk-KJ5A54ZH.js → chunk-RV74I3YO.js} +2 -2
  147. package/dist/cli/chunks/{chunk-UDSB3XCG.js → chunk-S75SOOZL.js} +2 -2
  148. package/dist/cli/chunks/{chunk-BPDAQB3F.js → chunk-SASBO5Y5.js} +2 -2
  149. package/dist/cli/chunks/{chunk-VJBJRFUO.js → chunk-SDLWKRVL.js} +9 -9
  150. package/dist/cli/chunks/{chunk-J6ASX536.js → chunk-SHKOCGNK.js} +2 -2
  151. package/dist/cli/chunks/{chunk-J35JWDJE.js → chunk-SI6DPU5D.js} +1 -1
  152. package/dist/cli/chunks/{chunk-V3MGY76S.js → chunk-SJ6Y4725.js} +2 -2
  153. package/dist/cli/chunks/{chunk-FTYRPEJS.js → chunk-SR52XP5F.js} +1 -1
  154. package/dist/cli/chunks/{chunk-ZUE524JL.js → chunk-SSUAAX3F.js} +2 -2
  155. package/dist/cli/chunks/{chunk-VG32EEUG.js → chunk-SSYAQZXA.js} +2 -2
  156. package/dist/cli/chunks/{chunk-HTVGHHX2.js → chunk-SUDMM5SO.js} +2 -2
  157. package/dist/cli/chunks/{chunk-K2SMP4OD.js → chunk-TIUKLYAI.js} +1 -1
  158. package/dist/cli/chunks/{chunk-VCVRZD4Y.js → chunk-TVGI32MB.js} +33 -33
  159. package/dist/cli/chunks/{chunk-CAZM63TP.js → chunk-U2A7NHZA.js} +2 -2
  160. package/dist/cli/chunks/{chunk-WBC6WB32.js → chunk-UE5ZOZR2.js} +2 -2
  161. package/dist/cli/chunks/{chunk-BQJ7CV53.js → chunk-UHEOGZLX.js} +12 -12
  162. package/dist/cli/chunks/chunk-UNGBRZDK.js +12 -0
  163. package/dist/cli/chunks/{chunk-XN3KCKAM.js → chunk-V5NHZV7S.js} +2 -2
  164. package/dist/cli/chunks/{chunk-UNYTHZDZ.js → chunk-VJCIEHEF.js} +1 -1
  165. package/dist/cli/chunks/{chunk-5Y7UFHJD.js → chunk-VMDFFTCK.js} +1 -1
  166. package/dist/cli/chunks/chunk-VSIKHWZ4.js +29 -0
  167. package/dist/cli/chunks/{chunk-UPWLMIDY.js → chunk-VWPM27GU.js} +2 -2
  168. package/dist/cli/chunks/{chunk-USAKCGHC.js → chunk-VXFLJNCA.js} +2 -2
  169. package/dist/cli/chunks/{chunk-WKI46WWN.js → chunk-W5HQUIML.js} +2 -2
  170. package/dist/cli/chunks/{chunk-Z54G2YOL.js → chunk-WP4RETKG.js} +2 -2
  171. package/dist/cli/chunks/{chunk-IRPNEXOU.js → chunk-XIIQ5QTT.js} +2 -2
  172. package/dist/cli/chunks/{chunk-O32BFQV4.js → chunk-XIQW7EFL.js} +2 -2
  173. package/dist/cli/chunks/{chunk-TW6Z6W4X.js → chunk-XWUWX7BV.js} +13 -13
  174. package/dist/cli/chunks/{chunk-57FX3GP6.js → chunk-Y4PFUMOU.js} +1 -1
  175. package/dist/cli/chunks/chunk-YAPLJR7K.js +2 -0
  176. package/dist/cli/chunks/{chunk-4T7XV5KQ.js → chunk-YLMNVLDK.js} +1 -1
  177. package/dist/cli/chunks/{chunk-TSP6SU5V.js → chunk-YNMJEDN5.js} +2 -2
  178. package/dist/cli/chunks/{chunk-PWQWKYBG.js → chunk-YPBSUGMI.js} +1 -1
  179. package/dist/cli/chunks/{chunk-QP2HLKTS.js → chunk-YRAX7SFJ.js} +2 -2
  180. package/dist/cli/chunks/{chunk-O3ERGUXH.js → chunk-YTHTQPWR.js} +1 -1
  181. package/dist/cli/chunks/{chunk-MR2OPUSA.js → chunk-YU2BDRSD.js} +1 -1
  182. package/dist/cli/chunks/chunk-ZB3LEFYG.js +2 -0
  183. package/dist/cli/chunks/{chunk-2W5MQDHM.js → chunk-ZFL436FN.js} +2 -2
  184. package/dist/cli/chunks/{chunk-7MISCSL5.js → chunk-ZJH5MU2I.js} +2 -2
  185. package/dist/cli/chunks/{chunk-52KOPIMI.js → chunk-ZQ2XW3IP.js} +2 -2
  186. package/dist/cli/chunks/chunk-ZR2TKVXQ.js +14 -0
  187. package/dist/cli/chunks/{ci-UMA2SMNW.js → ci-MFUR4CWV.js} +2 -2
  188. package/dist/cli/chunks/{ci-config-UQSILJFQ.js → ci-config-PNDLQ6XV.js} +2 -2
  189. package/dist/cli/chunks/{ci-output-U6YZLLKH.js → ci-output-PFZ4M7NC.js} +2 -2
  190. package/dist/cli/chunks/{circuit-breaker-ATYQP6X2.js → circuit-breaker-5HH6NLZN.js} +2 -2
  191. package/dist/cli/chunks/{claude-flow-setup-6YHFD7AN.js → claude-flow-setup-QCKYLGLC.js} +2 -2
  192. package/dist/cli/chunks/client-MHQRTZM4.js +2 -0
  193. package/dist/cli/chunks/{cline-installer-EPE7IOZE.js → cline-installer-EASVPFXR.js} +2 -2
  194. package/dist/cli/chunks/{code-NUEJ4XYO.js → code-UJXDVYRK.js} +4 -3
  195. package/dist/cli/chunks/{code-index-extractor-D4DBT6OL.js → code-index-extractor-BZJ3UDP4.js} +2 -2
  196. package/dist/cli/chunks/{codex-installer-633SM4LR.js → codex-installer-XSQZUVOZ.js} +4 -4
  197. package/dist/cli/chunks/{completions-WUKVIW3L.js → completions-OWOOJFI2.js} +2 -2
  198. package/dist/cli/chunks/{complexity-analyzer-F73ACR5H.js → complexity-analyzer-KP5TOHDT.js} +2 -2
  199. package/dist/cli/chunks/{continuedev-installer-QH42TKMS.js → continuedev-installer-IFKQXLHM.js} +2 -2
  200. package/dist/cli/chunks/{copilot-installer-Y3XC7BTT.js → copilot-installer-IGJ6KGQY.js} +2 -2
  201. package/dist/cli/chunks/core-handlers-UAK3LLJE.js +2 -0
  202. package/dist/cli/chunks/{cost-tracker-57QPV7E3.js → cost-tracker-MMDDNKZB.js} +2 -2
  203. package/dist/cli/chunks/{coverage-IBCHMBCR.js → coverage-LUH2B7NT.js} +3 -3
  204. package/dist/cli/chunks/cross-domain-router-WTRZQPNQ.js +2 -0
  205. package/dist/cli/chunks/{cursor-installer-F4UYQHIN.js → cursor-installer-4YLM5GWM.js} +2 -2
  206. package/dist/cli/chunks/daemon-CAVZ7OFV.js +18 -0
  207. package/dist/cli/chunks/{daemon-XR4Q6YZF.js → daemon-MZKVM4CJ.js} +3 -3
  208. package/dist/cli/chunks/{dag-attention-scheduler-ZR5ZD3TW.js → dag-attention-scheduler-X4CYW665.js} +2 -2
  209. package/dist/cli/chunks/{detect-GEGYURLL.js → detect-7BM2XINO.js} +2 -2
  210. package/dist/cli/chunks/{dist-node-JU3KT2JO.js → dist-node-Y5APLEYB.js} +2 -2
  211. package/dist/cli/chunks/{domain-handler-7QI3FJGE.js → domain-handler-X3ZRJNAH.js} +2 -2
  212. package/dist/cli/chunks/{domain-plugins-O2YRM2PD.js → domain-plugins-2UW5KQJB.js} +2 -2
  213. package/dist/cli/chunks/{domain-transfer-7J3S2OS6.js → domain-transfer-35W4CIBV.js} +2 -2
  214. package/dist/cli/chunks/dream-EJY24JN6.js +2 -0
  215. package/dist/cli/chunks/embed-and-insert-pattern-COG4C7ZI.js +3 -0
  216. package/dist/cli/chunks/embedding-space-SBM2MZD2.js +2 -0
  217. package/dist/cli/chunks/{eval-RVMCIUOR.js → eval-4QA2SROK.js} +2 -2
  218. package/dist/cli/chunks/experience-capture-middleware-Z6BF6KYM.js +40 -0
  219. package/dist/cli/chunks/{fast-paths-QUKPKWKZ.js → fast-paths-FIORX6GN.js} +2 -2
  220. package/dist/cli/chunks/{feature-flags-K7JXNKJI.js → feature-flags-6LYI2T4G.js} +2 -2
  221. package/dist/cli/chunks/{feature-flags-5JCSKL2P.js → feature-flags-ZOO7LMIC.js} +2 -2
  222. package/dist/cli/chunks/file-discovery-UZSFSS4V.js +2 -0
  223. package/dist/cli/chunks/{fleet-II4Q6HXK.js → fleet-7WF53H4F.js} +3 -3
  224. package/dist/cli/chunks/{gnn-wrapper-M7VO2EMS.js → gnn-wrapper-KJ6B7BRM.js} +2 -2
  225. package/dist/cli/chunks/{heartbeat-handler-ND5CY26N.js → heartbeat-handler-DEKKMOVW.js} +4 -4
  226. package/dist/cli/chunks/heartbeat-scheduler-NVR356I7.js +2 -0
  227. package/dist/cli/chunks/hnsw-adapter-LFMPLUJU.js +2 -0
  228. package/dist/cli/chunks/hnsw-index-POCPMVJH.js +2 -0
  229. package/dist/cli/chunks/{hnsw-legacy-bridge-N3AUUUU7.js → hnsw-legacy-bridge-L27WS27N.js} +2 -2
  230. package/dist/cli/chunks/{hnswlib-node-NZY3E5EN.js → hnswlib-node-4YOQC6L4.js} +2 -2
  231. package/dist/cli/chunks/{hooks-QVJDTII5.js → hooks-TAOKV4EJ.js} +23 -22
  232. package/dist/cli/chunks/hybrid-backend-4STAO7CV.js +2 -0
  233. package/dist/cli/chunks/{hypergraph-engine-ZRY6MTDV.js → hypergraph-engine-BODRJLHL.js} +2 -2
  234. package/dist/cli/chunks/{hypergraph-handler-56DO4XZQ.js → hypergraph-handler-RKMYJNTU.js} +3 -3
  235. package/dist/cli/chunks/impact-analyzer-3VIIISBQ.js +2 -0
  236. package/dist/cli/chunks/{init-guard-DTF4EVUY.js → init-guard-MXHSLSB2.js} +2 -2
  237. package/dist/cli/chunks/{init-handler-M6CNQHMX.js → init-handler-HUE57IFW.js} +6 -6
  238. package/dist/cli/chunks/init-wizard-PL6QN6RQ.js +2 -0
  239. package/dist/cli/chunks/kernel-CCDWT7KS.js +2 -0
  240. package/dist/cli/chunks/{kilocode-installer-IJN7XKBH.js → kilocode-installer-S333IKYQ.js} +2 -2
  241. package/dist/cli/chunks/{kiro-installer-UKKPGPDC.js → kiro-installer-WM5DLQWC.js} +2 -2
  242. package/dist/cli/chunks/knowledge-graph-KFOMEN3H.js +2 -0
  243. package/dist/cli/chunks/{learning-W2HETWQ4.js → learning-LNHMQLH5.js} +3 -3
  244. package/dist/cli/chunks/{llm-router-Y546K4VX.js → llm-router-EWFXYZZR.js} +4 -4
  245. package/dist/cli/chunks/llm-router-service-7NBE2EX6.js +2 -0
  246. package/dist/cli/chunks/{load-MKAB2AXE.js → load-FGYGWVDK.js} +2 -2
  247. package/dist/cli/chunks/load-test-UNZUWY3F.js +2 -0
  248. package/dist/cli/chunks/{mcp-AZKUS6K3.js → mcp-2FHNAAOM.js} +2 -2
  249. package/dist/cli/chunks/{memory-ZDOQN2KU.js → memory-DZMQ73AB.js} +5 -5
  250. package/dist/cli/chunks/memory-backend-DFGKWA2Q.js +2 -0
  251. package/dist/cli/chunks/memory-handlers-MP426XRJ.js +2 -0
  252. package/dist/cli/chunks/{multi-model-executor-WWVXDHG4.js → multi-model-executor-6F2UAEUW.js} +2 -2
  253. package/dist/cli/chunks/{opencode-installer-YUJNXXWS.js → opencode-installer-XY3BGOTZ.js} +2 -2
  254. package/dist/cli/chunks/{orchestrator-Z6PWPLRE.js → orchestrator-B4CNKUOS.js} +17 -17
  255. package/dist/cli/chunks/pattern-null-store-SSVF5TE5.js +2 -0
  256. package/dist/cli/chunks/{pattern-usage-recorder-TPWPX32U.js → pattern-usage-recorder-R4GUFNMD.js} +2 -2
  257. package/dist/cli/chunks/{pipeline-4BBGTE4M.js → pipeline-FG5RKVRO.js} +2 -2
  258. package/dist/cli/chunks/{platform-5GSHXCV5.js → platform-3BT4KEVJ.js} +2 -2
  259. package/dist/cli/chunks/{plugin-OFDVF5HS.js → plugin-WI4RIN7O.js} +2 -2
  260. package/dist/cli/chunks/{prime-radiant-advanced-wasm-NC6MUYGJ.js → prime-radiant-advanced-wasm-7ECDNQFS.js} +2 -2
  261. package/dist/cli/chunks/project-root-BEANNYWU.js +2 -0
  262. package/dist/cli/chunks/protocol-executor-FQVIHXZ7.js +2 -0
  263. package/dist/cli/chunks/{protocol-handler-MPOAAEPA.js → protocol-handler-WNODKPGW.js} +2 -2
  264. package/dist/cli/chunks/{prove-CDKMAIVM.js → prove-5RHAEPYZ.js} +2 -2
  265. package/dist/cli/chunks/qe-reasoning-bank-5TFYSE24.js +2 -0
  266. package/dist/cli/chunks/{quality-ZH4F7R7R.js → quality-WPHR7BGQ.js} +2 -2
  267. package/dist/cli/chunks/{quality-gate-IDRMW6OE.js → quality-gate-4RKTEZMX.js} +3 -3
  268. package/dist/cli/chunks/queen-coordinator-Y2OUL7IN.js +2 -0
  269. package/dist/cli/chunks/real-embeddings-OXLYU7JW.js +2 -0
  270. package/dist/cli/chunks/{ref-validation-Z5GCGVXK.js → ref-validation-TPAWHOHH.js} +2 -2
  271. package/dist/cli/chunks/{roocode-installer-IZ2S7PH2.js → roocode-installer-7AVHFNDI.js} +2 -2
  272. package/dist/cli/chunks/router-EP34O3KB.js +2 -0
  273. package/dist/cli/chunks/routing-feedback-FJCRKXNG.js +2 -0
  274. package/dist/cli/chunks/{routing-handler-NAX35VUW.js → routing-handler-YKEDVJSH.js} +2 -2
  275. package/dist/cli/chunks/{ruvector-commands-5YW2SOFF.js → ruvector-commands-JUAMM354.js} +2 -2
  276. package/dist/cli/chunks/rvf-dual-writer-ILITJSFG.js +2 -0
  277. package/dist/cli/chunks/rvf-migration-adapter-XF6W4C2N.js +2 -0
  278. package/dist/cli/chunks/rvf-migration-coordinator-CMKG56AR.js +2 -0
  279. package/dist/cli/chunks/rvf-native-adapter-7YFW6S4Y.js +2 -0
  280. package/dist/cli/chunks/{rvf-store-integrity-IPGCAT6C.js → rvf-store-integrity-VJDUIRTX.js} +2 -2
  281. package/dist/cli/chunks/safe-db-TCAU4FUT.js +2 -0
  282. package/dist/cli/chunks/schedule-NB5KV435.js +2 -0
  283. package/dist/cli/chunks/scheduler-JKXGKVK6.js +2 -0
  284. package/dist/cli/chunks/{security-3IH4BO5Z.js → security-ORDN3RD2.js} +3 -3
  285. package/dist/cli/chunks/{shared-rvf-adapter-ABY7PAY2.js → shared-rvf-adapter-CF4BCIO7.js} +2 -2
  286. package/dist/cli/chunks/{shared-rvf-dual-writer-6KENLN2W.js → shared-rvf-dual-writer-C32UBR6D.js} +2 -2
  287. package/dist/cli/chunks/sqlite-persistence-IXCNZRTW.js +2 -0
  288. package/dist/cli/chunks/{standalone-memory-RLFAUGOW.js → standalone-memory-OXRJYZXN.js} +2 -2
  289. package/dist/cli/chunks/{status-handler-FCOZBPE5.js → status-handler-BCX5D4HY.js} +2 -2
  290. package/dist/cli/chunks/{structural-health-4RDA5UUM.js → structural-health-LFG7RUU6.js} +2 -2
  291. package/dist/cli/chunks/sync-OSF7C2NL.js +2 -0
  292. package/dist/cli/chunks/{sync-KGEEXXCC.js → sync-YJEE2K2L.js} +2 -2
  293. package/dist/cli/chunks/task-handler-6LXKPTXJ.js +64 -0
  294. package/dist/cli/chunks/{task-handlers-6H7L2UT4.js → task-handlers-CILP36I7.js} +4 -4
  295. package/dist/cli/chunks/{test-S7IG6EIX.js → test-SD457QJ6.js} +4 -4
  296. package/dist/cli/chunks/test-runner-process-VKD65QQU.js +2 -0
  297. package/dist/cli/chunks/{test-scheduling-7XYXI4L2.js → test-scheduling-ISI2O4Q5.js} +3 -3
  298. package/dist/cli/chunks/token-bootstrap-VUELSBOS.js +2 -0
  299. package/dist/cli/chunks/{token-usage-Y2YTPOFE.js → token-usage-XOC5KG7S.js} +2 -2
  300. package/dist/cli/chunks/{transformers-UCJ3HHHC.js → transformers-LSLQAARK.js} +2 -2
  301. package/dist/cli/chunks/tree-sitter-wasm-parser-YAIPHRIL.js +2 -0
  302. package/dist/cli/chunks/{types-6CMFPETH.js → types-5BLCGLCR.js} +2 -2
  303. package/dist/cli/chunks/unified-memory-GI76TXFV.js +2 -0
  304. package/dist/cli/chunks/unified-memory-hnsw-GXJ5BTZO.js +2 -0
  305. package/dist/cli/chunks/unified-persistence-OP7FDQPD.js +2 -0
  306. package/dist/cli/chunks/{upgrade-K25DN6WU.js → upgrade-RQJYLK3J.js} +2 -2
  307. package/dist/cli/chunks/{validate-T4V3TBY3.js → validate-QBHWXXCK.js} +2 -2
  308. package/dist/cli/chunks/{validate-swarm-XSRC576T.js → validate-swarm-IKXBKFB5.js} +2 -2
  309. package/dist/cli/chunks/visual-security-GZ2MOKWB.js +2 -0
  310. package/dist/cli/chunks/{web-tree-sitter-YOZXHRTN.js → web-tree-sitter-ZF6FIE5R.js} +2 -2
  311. package/dist/cli/chunks/{windsurf-installer-ITPU2IYL.js → windsurf-installer-HQGDZT5D.js} +2 -2
  312. package/dist/cli/chunks/witness-chain-DCHCAMSQ.js +2 -0
  313. package/dist/cli/chunks/witness-chain-P3XXXA62.js +2 -0
  314. package/dist/cli/chunks/witness-chain-repair-PUX2NFDL.js +2 -0
  315. package/dist/cli/chunks/{witness-chain-verifier-DTDSVKOG.js → witness-chain-verifier-PX2OQ6XT.js} +2 -2
  316. package/dist/cli/chunks/{witness-key-manager-EWACWGAW.js → witness-key-manager-RXYQNFJB.js} +2 -2
  317. package/dist/cli/chunks/{workflow-ZIQ4FV42.js → workflow-FBKCA4H6.js} +4 -4
  318. package/dist/cli/chunks/workflow-orchestrator-P2APAJAA.js +2 -0
  319. package/dist/cli/chunks/wrappers-TWSKBTWD.js +2 -0
  320. package/dist/cli/commands/code.js +4 -0
  321. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +10 -2
  322. package/dist/cli/handlers/task-handler.d.ts +5 -0
  323. package/dist/cli/handlers/task-handler.js +21 -1
  324. package/dist/cli/utils/task-result.d.ts +11 -0
  325. package/dist/cli/utils/task-result.js +39 -0
  326. package/dist/coordination/handlers/test-execution-handlers.js +92 -58
  327. package/dist/coordination/mincut/mincut-persistence.js +29 -25
  328. package/dist/domains/code-intelligence/coordinator.d.ts +4 -0
  329. package/dist/domains/code-intelligence/coordinator.js +46 -13
  330. package/dist/domains/code-intelligence/interfaces.d.ts +10 -1
  331. package/dist/domains/code-intelligence/services/semantic-analyzer.d.ts +32 -7
  332. package/dist/domains/code-intelligence/services/semantic-analyzer.js +112 -53
  333. package/dist/domains/learning-optimization/services/learning-coordinator.js +1 -1
  334. package/dist/domains/quality-assessment/coordinator.js +2 -1
  335. package/dist/domains/test-execution/coordinator.js +10 -5
  336. package/dist/domains/test-execution/interfaces.d.ts +12 -0
  337. package/dist/domains/test-execution/plugin.js +6 -2
  338. package/dist/domains/test-execution/services/retry-handler.d.ts +2 -0
  339. package/dist/domains/test-execution/services/retry-handler.js +14 -9
  340. package/dist/domains/test-execution/services/test-executor.d.ts +1 -0
  341. package/dist/domains/test-execution/services/test-executor.js +28 -9
  342. package/dist/domains/visual-accessibility/coordinator.d.ts +15 -7
  343. package/dist/domains/visual-accessibility/coordinator.js +15 -7
  344. package/dist/domains/visual-accessibility/interfaces.d.ts +27 -3
  345. package/dist/domains/visual-accessibility/services/accessibility-contrast.d.ts +39 -0
  346. package/dist/domains/visual-accessibility/services/accessibility-contrast.js +93 -0
  347. package/dist/domains/visual-accessibility/services/accessibility-tester-browser.d.ts +18 -3
  348. package/dist/domains/visual-accessibility/services/accessibility-tester-browser.js +50 -40
  349. package/dist/domains/visual-accessibility/services/accessibility-tester-checks.d.ts +27 -0
  350. package/dist/domains/visual-accessibility/services/accessibility-tester-checks.js +137 -0
  351. package/dist/domains/visual-accessibility/services/accessibility-tester.d.ts +5 -0
  352. package/dist/domains/visual-accessibility/services/accessibility-tester.js +43 -24
  353. package/dist/domains/visual-accessibility/services/browser-swarm-coordinator.d.ts +2 -3
  354. package/dist/domains/visual-accessibility/services/browser-swarm-coordinator.js +8 -14
  355. package/dist/feedback/coverage-learner.js +13 -9
  356. package/dist/feedback/test-outcome-tracker.js +13 -9
  357. package/dist/governance/witness-chain.d.ts +5 -0
  358. package/dist/governance/witness-chain.js +22 -6
  359. package/dist/init/init-wizard-hooks.d.ts +1 -1
  360. package/dist/init/init-wizard-hooks.js +7 -8
  361. package/dist/init/phases/08-mcp.js +9 -0
  362. package/dist/init/settings-merge.d.ts +13 -0
  363. package/dist/init/settings-merge.js +49 -2
  364. package/dist/integrations/agent-booster-wasm/agent_booster_wasm.js +849 -0
  365. package/dist/integrations/agent-booster-wasm/agent_booster_wasm_bg.wasm +0 -0
  366. package/dist/integrations/agent-booster-wasm/index.d.ts +8 -0
  367. package/dist/integrations/agent-booster-wasm/index.js +25 -2
  368. package/dist/integrations/agent-booster-wasm/package.json +16 -0
  369. package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.d.ts +22 -0
  370. package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.js +115 -45
  371. package/dist/integrations/agentic-flow/reasoning-bank/pattern-evolution.d.ts +6 -0
  372. package/dist/integrations/agentic-flow/reasoning-bank/pattern-evolution.js +51 -33
  373. package/dist/integrations/agentic-flow/reasoning-bank/trajectory-tracker.js +17 -9
  374. package/dist/integrations/embeddings/cache/EmbeddingCache.d.ts +8 -0
  375. package/dist/integrations/embeddings/cache/EmbeddingCache.js +24 -10
  376. package/dist/integrations/ruvector/delta-tracker.d.ts +11 -0
  377. package/dist/integrations/ruvector/delta-tracker.js +16 -0
  378. package/dist/integrations/ruvector/sona-persistence.d.ts +10 -0
  379. package/dist/integrations/ruvector/sona-persistence.js +49 -24
  380. package/dist/kernel/unified-memory.d.ts +24 -0
  381. package/dist/kernel/unified-memory.js +63 -8
  382. package/dist/learning/aqe-learning-engine.js +1 -1
  383. package/dist/learning/dream/dream-engine.d.ts +3 -2
  384. package/dist/learning/dream/dream-engine.js +42 -24
  385. package/dist/learning/dream/dream-lock-retry.d.ts +38 -0
  386. package/dist/learning/dream/dream-lock-retry.js +66 -0
  387. package/dist/learning/dream/speculative-dreamer.js +1 -1
  388. package/dist/learning/embed-and-insert-pattern.js +4 -2
  389. package/dist/learning/embedder-endpoint-client.d.ts +31 -0
  390. package/dist/learning/embedder-endpoint-client.js +103 -10
  391. package/dist/learning/embedding-space.d.ts +12 -0
  392. package/dist/learning/embedding-space.js +17 -0
  393. package/dist/learning/experience-capture-middleware.js +25 -13
  394. package/dist/learning/experience-capture.js +1 -1
  395. package/dist/learning/experience-consolidation.d.ts +18 -0
  396. package/dist/learning/experience-consolidation.js +55 -8
  397. package/dist/learning/experience-space-verification.d.ts +71 -0
  398. package/dist/learning/experience-space-verification.js +147 -0
  399. package/dist/learning/pattern-lifecycle.d.ts +40 -4
  400. package/dist/learning/pattern-lifecycle.js +153 -76
  401. package/dist/learning/pattern-null-store.d.ts +5 -0
  402. package/dist/learning/pattern-null-store.js +8 -0
  403. package/dist/learning/pattern-promotion.js +6 -3
  404. package/dist/learning/pattern-store.d.ts +6 -0
  405. package/dist/learning/pattern-store.js +19 -6
  406. package/dist/learning/qe-reasoning-bank.js +2 -2
  407. package/dist/learning/real-embeddings.js +3 -1
  408. package/dist/learning/real-qe-reasoning-bank.d.ts +5 -0
  409. package/dist/learning/real-qe-reasoning-bank.js +77 -47
  410. package/dist/learning/rvf-pattern-store.js +6 -2
  411. package/dist/learning/sqlite-persistence.d.ts +6 -0
  412. package/dist/learning/sqlite-persistence.js +10 -0
  413. package/dist/mcp/bundle.js +642 -571
  414. package/dist/mcp/entry.js +4 -0
  415. package/dist/mcp/handlers/domain-handler-configs.js +2 -0
  416. package/dist/mcp/handlers/trajectory-judge.js +1 -1
  417. package/dist/mcp/protocol-server.js +1 -0
  418. package/dist/mcp/tools/visual-accessibility/index.js +8 -2
  419. package/dist/mcp/types.d.ts +6 -0
  420. package/dist/optimization/session-cache.d.ts +17 -1
  421. package/dist/optimization/session-cache.js +40 -36
  422. package/dist/planning/goap-planner.d.ts +6 -0
  423. package/dist/planning/goap-planner.js +35 -19
  424. package/dist/planning/plan-executor.js +24 -15
  425. package/dist/routing/co-execution-repository.js +12 -9
  426. package/dist/routing/routing-feedback.d.ts +8 -0
  427. package/dist/routing/routing-feedback.js +46 -24
  428. package/dist/routing/routing-outcomes-migration.js +7 -2
  429. package/dist/shared/llm/spend-ledger.d.ts +9 -0
  430. package/dist/shared/llm/spend-ledger.js +64 -39
  431. package/dist/shared/sqlite-lock-wait.d.ts +27 -0
  432. package/dist/shared/sqlite-lock-wait.js +37 -0
  433. package/dist/shared/sqlite-write-queue.d.ts +28 -0
  434. package/dist/shared/sqlite-write-queue.js +38 -0
  435. package/dist/shared/test-runner-project.d.ts +69 -0
  436. package/dist/shared/test-runner-project.js +186 -0
  437. package/dist/skills/security-visual-testing/index.d.ts +3 -1
  438. package/dist/skills/security-visual-testing/index.js +49 -35
  439. package/dist/skills/security-visual-testing/types.d.ts +19 -3
  440. package/dist/workers/workers/heartbeat-scheduler.js +5 -5
  441. package/dist/workers/workers/learning-consolidation.js +8 -7
  442. package/package.json +4 -2
  443. package/dist/cli/chunks/adapter-23KA2YW7.js +0 -2
  444. package/dist/cli/chunks/agent-booster-wasm-2DLAEZK6.js +0 -2
  445. package/dist/cli/chunks/aqe-learning-engine-MUICAXW5.js +0 -2
  446. package/dist/cli/chunks/base-XPWGYDKD.js +0 -2
  447. package/dist/cli/chunks/browser-workflow-UMQVBVGK.js +0 -2
  448. package/dist/cli/chunks/chunk-3FITMWWJ.js +0 -21
  449. package/dist/cli/chunks/chunk-ARRBXCII.js +0 -4
  450. package/dist/cli/chunks/chunk-BBYJBZHG.js +0 -14
  451. package/dist/cli/chunks/chunk-BM3EJLMV.js +0 -153
  452. package/dist/cli/chunks/chunk-D3ZZ2NLL.js +0 -62
  453. package/dist/cli/chunks/chunk-DLTB5KCR.js +0 -2
  454. package/dist/cli/chunks/chunk-DRLSJJIC.js +0 -6
  455. package/dist/cli/chunks/chunk-HAYKLXCT.js +0 -744
  456. package/dist/cli/chunks/chunk-HHBF2BZC.js +0 -65
  457. package/dist/cli/chunks/chunk-K7RT6ITZ.js +0 -2
  458. package/dist/cli/chunks/chunk-L752CNG3.js +0 -13
  459. package/dist/cli/chunks/chunk-MQXWG55U.js +0 -12
  460. package/dist/cli/chunks/chunk-WM2QRIRD.js +0 -14
  461. package/dist/cli/chunks/chunk-WRC3HLUY.js +0 -29
  462. package/dist/cli/chunks/chunk-XTZGAG6P.js +0 -27
  463. package/dist/cli/chunks/chunk-YKQWIXUY.js +0 -2
  464. package/dist/cli/chunks/client-E43GWLQH.js +0 -2
  465. package/dist/cli/chunks/core-handlers-R5A3SQDY.js +0 -2
  466. package/dist/cli/chunks/cross-domain-router-LLYVPZF6.js +0 -2
  467. package/dist/cli/chunks/daemon-BYYPIJ7G.js +0 -18
  468. package/dist/cli/chunks/dream-6C4NURSE.js +0 -2
  469. package/dist/cli/chunks/embed-and-insert-pattern-URES5Q6J.js +0 -3
  470. package/dist/cli/chunks/experience-capture-middleware-SYJQSBKE.js +0 -40
  471. package/dist/cli/chunks/file-discovery-J5IE5KP7.js +0 -2
  472. package/dist/cli/chunks/heartbeat-scheduler-FC5PBTMN.js +0 -2
  473. package/dist/cli/chunks/hnsw-adapter-47UIVOBG.js +0 -2
  474. package/dist/cli/chunks/hnsw-index-3AKVLOZQ.js +0 -2
  475. package/dist/cli/chunks/hybrid-backend-YAOSNX47.js +0 -2
  476. package/dist/cli/chunks/impact-analyzer-4FMJXM4M.js +0 -2
  477. package/dist/cli/chunks/init-wizard-RTLCRWDT.js +0 -2
  478. package/dist/cli/chunks/kernel-2OWIGGGT.js +0 -2
  479. package/dist/cli/chunks/knowledge-graph-25XXKDJN.js +0 -2
  480. package/dist/cli/chunks/llm-router-service-G3EIN4UB.js +0 -2
  481. package/dist/cli/chunks/load-test-D6QYNIVT.js +0 -2
  482. package/dist/cli/chunks/memory-backend-LDFFZMEQ.js +0 -2
  483. package/dist/cli/chunks/memory-handlers-3SQVY7FE.js +0 -2
  484. package/dist/cli/chunks/pattern-null-store-KDVRM7PW.js +0 -2
  485. package/dist/cli/chunks/project-root-DDGBWDP6.js +0 -2
  486. package/dist/cli/chunks/protocol-executor-KBOLLCWA.js +0 -2
  487. package/dist/cli/chunks/qe-reasoning-bank-GRXBT7FC.js +0 -2
  488. package/dist/cli/chunks/queen-coordinator-L2QWMJ5Q.js +0 -2
  489. package/dist/cli/chunks/real-embeddings-I2UVNNB3.js +0 -2
  490. package/dist/cli/chunks/router-FT5WJPUH.js +0 -2
  491. package/dist/cli/chunks/routing-feedback-EO2MKOUX.js +0 -2
  492. package/dist/cli/chunks/rvf-dual-writer-WHBFQJVU.js +0 -2
  493. package/dist/cli/chunks/rvf-migration-adapter-YT3APF2I.js +0 -2
  494. package/dist/cli/chunks/rvf-migration-coordinator-VUIZHTVG.js +0 -2
  495. package/dist/cli/chunks/rvf-native-adapter-37PUFKQD.js +0 -2
  496. package/dist/cli/chunks/safe-db-TDZKUOZJ.js +0 -2
  497. package/dist/cli/chunks/schedule-CRKTRY2A.js +0 -2
  498. package/dist/cli/chunks/scheduler-6ZBDVQWN.js +0 -2
  499. package/dist/cli/chunks/sqlite-persistence-FFJQAIKW.js +0 -2
  500. package/dist/cli/chunks/sync-54LUAUTK.js +0 -2
  501. package/dist/cli/chunks/task-handler-K3OXHYKU.js +0 -62
  502. package/dist/cli/chunks/test-runner-process-OTQDAJLN.js +0 -2
  503. package/dist/cli/chunks/token-bootstrap-3QMABE45.js +0 -2
  504. package/dist/cli/chunks/tree-sitter-wasm-parser-D6JTTHTP.js +0 -2
  505. package/dist/cli/chunks/unified-memory-QARWQKJ2.js +0 -2
  506. package/dist/cli/chunks/unified-memory-hnsw-LHY3DXCP.js +0 -2
  507. package/dist/cli/chunks/unified-persistence-WEYYGLHM.js +0 -2
  508. package/dist/cli/chunks/visual-security-O4ALMCXQ.js +0 -2
  509. package/dist/cli/chunks/witness-chain-B3YW5NMS.js +0 -2
  510. package/dist/cli/chunks/witness-chain-PIYR72HJ.js +0 -2
  511. package/dist/cli/chunks/witness-chain-repair-YUG7E3UX.js +0 -2
  512. package/dist/cli/chunks/workflow-orchestrator-3ZN2BCGY.js +0 -2
  513. package/dist/cli/chunks/wrappers-PW2O27LL.js +0 -2
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.14");process.exit(0)}
2
- import{c as p}from"./chunk-6O63ZTVX.js";import*as u from"fs";import*as m from"path";var y=["coverage/coverage-final.json","coverage/coverage-summary.json",".coverage/coverage-final.json"];function F(r){for(let o of y){let s=m.join(r,o);if(u.existsSync(s))try{let t=u.readFileSync(s,"utf-8"),c=JSON.parse(t);if(c.total&&c.total.lines)return x(c,r);let n=new Map;for(let e of p(t).files)n.set(e.path,e);return n.size>0?n:null}catch{continue}}return null}function x(r,o){let s=new Map;for(let[t,c]of Object.entries(r)){if(t==="total")continue;let n=c;s.set(t,{path:t,lines:{covered:n.lines.covered,total:n.lines.total},branches:{covered:n.branches.covered,total:n.branches.total},functions:{covered:n.functions.covered,total:n.functions.total},statements:{covered:n.statements.covered,total:n.statements.total},uncoveredLines:[],uncoveredBranches:[]})}return s.size>0?s:null}function S(r,o){let t=o.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
2
+ import{c as p}from"./chunk-IUBJVHNB.js";import*as u from"fs";import*as m from"path";var y=["coverage/coverage-final.json","coverage/coverage-summary.json",".coverage/coverage-final.json"];function F(r){for(let o of y){let s=m.join(r,o);if(u.existsSync(s))try{let t=u.readFileSync(s,"utf-8"),c=JSON.parse(t);if(c.total&&c.total.lines)return x(c,r);let n=new Map;for(let e of p(t).files)n.set(e.path,e);return n.size>0?n:null}catch{continue}}return null}function x(r,o){let s=new Map;for(let[t,c]of Object.entries(r)){if(t==="total")continue;let n=c;s.set(t,{path:t,lines:{covered:n.lines.covered,total:n.lines.total},branches:{covered:n.branches.covered,total:n.branches.total},functions:{covered:n.functions.covered,total:n.functions.total},statements:{covered:n.statements.covered,total:n.statements.total},uncoveredLines:[],uncoveredBranches:[]})}return s.size>0?s:null}function S(r,o){let t=o.split(`
3
3
  `).length,n=[r.replace(".ts",".test.ts").replace("/src/","/tests/"),r.replace(".ts",".spec.ts").replace("/src/","/tests/"),r.replace(".ts",".test.ts"),r.replace("/src/","/test/").replace(".ts",".test.ts")].some(f=>u.existsSync(f)),e=(o.match(/\bexport\b/g)||[]).length,a=(o.match(/\b(function|=>)\b/g)||[]).length,i=(o.match(/\b(if|switch|case|\?\?|\|\|)\b/g)||[]).length,l;if(n){let f=Math.min(i*.005,.15),b=Math.min(t*1e-4,.1);l=.85-f-b}else l=.2+(e>5?.1:0);l=Math.max(.05,Math.min(.95,l));let v=Math.floor(t*l),g=Math.max(a,1),d=Math.max(i,1),C=Math.floor(v*.7),M=Math.floor(g*l*.9),h=Array.from({length:t-v},(f,b)=>b+v+1);return{path:r,lines:{covered:v,total:t},branches:{covered:Math.min(C,d),total:d},functions:{covered:Math.min(M,g),total:g},statements:{covered:v,total:t},uncoveredLines:h,uncoveredBranches:h.slice(0,Math.floor(h.length/2))}}function L(r){let o=e=>r.reduce((a,i)=>a+e(i),0),s=(e,a)=>a>0?Math.round(e/a*100):0,t=o(e=>e.lines.total),c=o(e=>e.lines.covered),n=o(e=>e.statements.total);return{line:s(c,t),branch:s(o(e=>e.branches.covered),o(e=>e.branches.total)),function:s(o(e=>e.functions.covered),o(e=>e.functions.total)),statement:n>0?s(o(e=>e.statements.covered),n):s(c,t),files:r.length}}function B(r,o){let s=o||process.cwd(),t=F(s),c=[],n=[],e=!1;if(t&&t.size>0){e=!0;for(let a of r){let i=m.resolve(a),l=t.get(i)||t.get(a)||t.get(m.relative(s,i));l?c.push({...l,path:a}):n.push(a)}}else for(let a of r){let i=u.existsSync(a)?u.readFileSync(a,"utf-8"):"";c.push(S(a,i))}return{files:c,summary:L(c),instrumented:e,...n.length>0?{unmeasuredFiles:n}:{}}}export{L as a,B as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.14");process.exit(0)}
2
- import{b as i}from"./chunk-V6SE2ZU2.js";function d(){return Object.create(null)}function o(e,n){return Object.hasOwn(e,n)?e[n]:void 0}function u(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}function s(e,n,t=1){let r=(o(e,n)??0)+t;return u(e,n,r),r}var c=i(()=>{"use strict"});export{d as a,o as b,u as c,s as d,c as e};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
2
+ import{b as i}from"./chunk-AJMJNQMP.js";function d(){return Object.create(null)}function o(e,n){return Object.hasOwn(e,n)?e[n]:void 0}function u(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}function s(e,n,t=1){let r=(o(e,n)??0)+t;return u(e,n,r),r}var c=i(()=>{"use strict"});export{d as a,o as b,u as c,s as d,c as e};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.14");process.exit(0)}
2
- import{b as c,d as f,e as g,f as X}from"./chunk-JK6PMLQQ.js";import{createHash as I}from"crypto";import{existsSync as O,readFileSync as b,writeFileSync as D,openSync as F,writeSync as y,closeSync as S}from"fs";X();var U=[`CREATE TABLE IF NOT EXISTS qe_patterns (
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
2
+ import{g as c,i as f,j as g,k as X}from"./chunk-MO55CVMT.js";import{createHash as I}from"crypto";import{existsSync as O,readFileSync as b,writeFileSync as D,openSync as F,writeSync as y,closeSync as S}from"fs";X();var U=[`CREATE TABLE IF NOT EXISTS qe_patterns (
3
3
  id TEXT PRIMARY KEY, pattern_type TEXT NOT NULL, qe_domain TEXT NOT NULL,
4
4
  domain TEXT NOT NULL, name TEXT NOT NULL, description TEXT,
5
5
  confidence REAL DEFAULT 0.5, usage_count INTEGER DEFAULT 0,
@@ -1,10 +1,10 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.14");process.exit(0)}
2
- import{c as E,d as I}from"./chunk-ZUE524JL.js";import{a as b}from"./chunk-FTYRPEJS.js";import{b as de}from"./chunk-6P4Q4RTC.js";import{a as ue,b as ge}from"./chunk-J35JWDJE.js";import{e as le,f as ce}from"./chunk-JJHLGGPP.js";import{b as S,d as oe}from"./chunk-XN3KCKAM.js";import{b as ae,c as L,e as Ee}from"./chunk-UDSB3XCG.js";import{a as se}from"./chunk-RE6JTSDM.js";import{a as k,e as F}from"./chunk-L5VSLPMW.js";var Ie={M:16,efConstruction:200,efSearch:100},$={enabled:!0,pretrainedPatterns:!0,hnswConfig:Ie,promotionThreshold:le,qualityThreshold:ce,embeddingModel:"auto"},M={mode:"hybrid",confidenceThreshold:.7,feedbackEnabled:!0,cacheEnabled:!0,cacheTTLMs:300*1e3},Q={enabled:["pattern-consolidator","coverage-gap-scanner","flaky-test-detector","routing-accuracy-monitor"],intervals:{"pattern-consolidator":1800*1e3,"coverage-gap-scanner":3600*1e3,"flaky-test-detector":7200*1e3,"routing-accuracy-monitor":900*1e3},maxConcurrent:4,daemonAutoStart:!0},V={claudeCode:!0,preCommit:!1,ciIntegration:!1},G={install:!0,installV2:!0,installV3:!0,overwrite:!1},W={enabled:!0,parameters:["hnsw.efSearch","routing.confidenceThreshold","pattern.promotionThreshold","testGen.complexityLimit"],tuningIntervalMs:10080*60*1e3,evaluationPeriodMs:5e3};var _=se.filter(r=>r!=="coordination");function B(){return"3.15.14"}function lt(r,e){return{version:B(),project:{name:r,root:e,type:"single"},learning:structuredClone($),routing:structuredClone(M),workers:structuredClone(Q),hooks:structuredClone(V),skills:structuredClone(G),autoTuning:structuredClone(W),domains:{enabled:[..._],disabled:[]},agents:{maxConcurrent:15,defaultTimeout:6e4}}}oe();import{readFileSync as w,existsSync as p,statSync as _e,readdirSync as qe}from"fs";import{join as d,basename as pe,extname as me,relative as U}from"path";var Te=[{name:"jest",detect:r=>{let e=["jest.config.js","jest.config.ts","jest.config.mjs","jest.config.cjs"];for(let n of e)if(p(d(r,n)))return{name:"jest",version:x(r,"jest"),configFile:n,confidence:1};let t=A(r);return t?.jest?{name:"jest",version:x(r,"jest"),configFile:"package.json",confidence:.9}:t?.devDependencies?.jest||t?.dependencies?.jest?{name:"jest",version:t.devDependencies?.jest||t.dependencies?.jest,confidence:.7}:null}},{name:"vitest",detect:r=>{let e=["vitest.config.ts","vitest.config.js","vitest.config.mts","vite.config.ts"];for(let n of e)if(p(d(r,n)))return{name:"vitest",version:x(r,"vitest"),configFile:n,confidence:1};let t=A(r);return t?.devDependencies?.vitest||t?.dependencies?.vitest?{name:"vitest",version:t.devDependencies?.vitest,confidence:.8}:null}},{name:"mocha",detect:r=>{let e=[".mocharc.js",".mocharc.json",".mocharc.yaml",".mocharc.yml"];for(let n of e)if(p(d(r,n)))return{name:"mocha",version:x(r,"mocha"),configFile:n,confidence:1};let t=A(r);return t?.devDependencies?.mocha?{name:"mocha",version:t.devDependencies?.mocha,confidence:.8}:null}},{name:"pytest",detect:r=>{let e=["pytest.ini","pyproject.toml","setup.cfg"];for(let n of e){let i=d(r,n);if(p(i))try{let s=w(i,"utf-8");if(s.includes("[pytest]")||s.includes("[tool.pytest]"))return{name:"pytest",configFile:n,confidence:1}}catch(s){console.debug("[ProjectAnalyzer] Config read failed:",s instanceof Error?s.message:s)}}let t=d(r,"requirements.txt");if(p(t))try{if(w(t,"utf-8").includes("pytest"))return{name:"pytest",configFile:"requirements.txt",confidence:.8}}catch(n){console.debug("[ProjectAnalyzer] requirements.txt read failed:",n instanceof Error?n.message:n)}return null}},{name:"playwright",detect:r=>{let e=["playwright.config.ts","playwright.config.js"];for(let n of e)if(p(d(r,n)))return{name:"playwright",version:x(r,"@playwright/test"),configFile:n,confidence:1};let t=A(r);return t?.devDependencies?.["@playwright/test"]?{name:"playwright",version:t.devDependencies["@playwright/test"],confidence:.8}:null}},{name:"cypress",detect:r=>{let e=["cypress.config.ts","cypress.config.js","cypress.json"];for(let t of e)if(p(d(r,t)))return{name:"cypress",version:x(r,"cypress"),configFile:t,confidence:1};return p(d(r,"cypress"))?{name:"cypress",configFile:"cypress/",confidence:.9}:null}}],Pe=[{name:"typescript",extensions:[".ts",".tsx",".mts",".cts"]},{name:"javascript",extensions:[".js",".jsx",".mjs",".cjs"]},{name:"python",extensions:[".py",".pyw"]},{name:"java",extensions:[".java"]},{name:"go",extensions:[".go"]},{name:"rust",extensions:[".rs"]},{name:"csharp",extensions:[".cs"]},{name:"ruby",extensions:[".rb"]},{name:"php",extensions:[".php"]},{name:"kotlin",extensions:[".kt",".kts"]},{name:"swift",extensions:[".swift"]}];function A(r){let e=d(r,"package.json");if(!p(e))return null;try{return S(w(e,"utf-8"))}catch{return null}}function x(r,e){let t=A(r);if(t)return t.devDependencies?.[e]||t.dependencies?.[e]}var Ne=["node_modules",".git","dist","build","coverage",".next","__pycache__",".agentic-qe",".claude",".agents",".codex",".opencode",".kiro",".cursor",".roo",".kilocode",".windsurf",".continue",".clinerules",".swarm",".claude-flow",".hive-mind"];function z(r,e,t={}){let{maxDepth:n=10,exclude:i=Ne}=t;function s(o,a){if(a>n)return;let c;try{c=qe(o)}catch{return}for(let u of c){if(i.includes(u))continue;let l=d(o,u),j;try{j=_e(l)}catch{continue}j.isDirectory()?s(l,a+1):j.isFile()&&e(l)}}s(r,0)}var H=class{projectRoot;constructor(e){this.projectRoot=e}async analyze(){let e=Date.now(),[t,n,i,s,o]=await Promise.all([this.detectFrameworks(),this.detectLanguages(),this.detectExistingTests(),this.analyzeComplexity(),this.measureCoverage()]);return{projectName:A(this.projectRoot)?.name||pe(this.projectRoot),projectRoot:this.projectRoot,projectType:this.detectProjectType(),frameworks:t,languages:n,existingTests:i,codeComplexity:s,coverage:o,packageManager:this.detectPackageManager(),hasTypeScript:p(d(this.projectRoot,"tsconfig.json")),hasCIConfig:this.detectCIConfig(),ciProvider:this.detectCIProvider(),analysisTimestamp:new Date,analysisDurationMs:Date.now()-e}}async detectFrameworks(){let e=[];for(let t of Te){let n=t.detect(this.projectRoot);n&&e.push(n)}return e.sort((t,n)=>n.confidence-t.confidence)}async detectLanguages(){let e=new Map,t=0;z(this.projectRoot,i=>{let s=me(i).toLowerCase();if(s){for(let o of Pe)if(o.extensions.includes(s)){let a=e.get(o.name)||{count:0,extensions:new Set};a.count++,a.extensions.add(s),e.set(o.name,a),t++;break}}});let n=[];for(let[i,s]of e)n.push({name:i,percentage:t>0?Math.round(s.count/t*100):0,fileCount:s.count,extensions:Array.from(s.extensions)});return n.sort((i,s)=>s.fileCount-i.fileCount)}async detectExistingTests(){let e={totalCount:0,byFramework:{},byType:{unit:0,integration:0,e2e:0,unknown:0},directories:[]},t=new Set,n=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/_test\.[jt]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/,/.*Test\.java$/];return z(this.projectRoot,i=>{let s=pe(i);if(n.some(a=>a.test(s))){e.totalCount++;let a=U(this.projectRoot,i).toLowerCase();a.includes("e2e")||a.includes("cypress")||a.includes("playwright")?e.byType.e2e++:a.includes("integration")||a.includes("int-test")?e.byType.integration++:a.includes("unit")||a.includes("__tests__")||a.includes("test/")?e.byType.unit++:e.byType.unknown++;let c=U(this.projectRoot,d(i,".."));t.add(c)}}),e.directories=Array.from(t).slice(0,10),e}async analyzeComplexity(){let e=[],t=[],n=0,i=0;z(this.projectRoot,a=>{let c=me(a);if([".ts",".tsx",".js",".jsx",".py",".java",".go"].includes(c))try{let u=w(a,"utf-8"),l=this.calculateFileComplexity(u,c);t.push(...l.functionComplexities),l.maxComplexity>n&&(n=l.maxComplexity),i++,l.maxComplexity>10&&e.push(U(this.projectRoot,a))}catch(u){console.debug("[ProjectAnalyzer] Complexity analysis read failed:",u instanceof Error?u.message:u)}});let s=t.reduce((a,c)=>a+c,0),o=t.length>0?s/t.length:0;return{averageCyclomatic:Math.round(o*10)/10,maxCyclomatic:n,totalFiles:i,complexFiles:e.slice(0,20),recommendation:o<5?"simple":o<15?"medium":"complex"}}calculateFileComplexity(e,t){let n=this.stripCommentsAndStrings(e,t),i=this.calculateComplexity(n);return{functionComplexities:[i],maxComplexity:i}}removeDelimitedBlocks(e,t,n){let i="",s=0;for(;s<e.length;){let o=e.indexOf(t,s);if(o===-1){i+=e.slice(s);break}i+=e.slice(s,o);let a=e.indexOf(n,o+t.length);if(a===-1)break;s=a+n.length}return i}stripCommentsAndStrings(e,t){let n=e;return[".ts",".tsx",".js",".jsx",".java",".go"].includes(t)?(n=n.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
2
+ import{c as I,d as _}from"./chunk-SSUAAX3F.js";import{a as b}from"./chunk-SR52XP5F.js";import{b as me}from"./chunk-24QHCVX6.js";import{a as de,b as pe}from"./chunk-SI6DPU5D.js";import{e as ue,f as ge}from"./chunk-EA4YQVKS.js";import{b as S,d as le}from"./chunk-V5NHZV7S.js";import{b as ce,c as $,e as qe}from"./chunk-S75SOOZL.js";import{a as ae}from"./chunk-LE4QJREF.js";import{a as k,e as L}from"./chunk-KNSRL6NO.js";var Te={M:16,efConstruction:200,efSearch:100},M={enabled:!0,pretrainedPatterns:!0,hnswConfig:Te,promotionThreshold:ue,qualityThreshold:ge,embeddingModel:"auto"},Q={mode:"hybrid",confidenceThreshold:.7,feedbackEnabled:!0,cacheEnabled:!0,cacheTTLMs:300*1e3},V={enabled:["pattern-consolidator","coverage-gap-scanner","flaky-test-detector","routing-accuracy-monitor"],intervals:{"pattern-consolidator":1800*1e3,"coverage-gap-scanner":3600*1e3,"flaky-test-detector":7200*1e3,"routing-accuracy-monitor":900*1e3},maxConcurrent:4,daemonAutoStart:!0},G={claudeCode:!0,preCommit:!1,ciIntegration:!1},W={install:!0,installV2:!0,installV3:!0,overwrite:!1},B={enabled:!0,parameters:["hnsw.efSearch","routing.confidenceThreshold","pattern.promotionThreshold","testGen.complexityLimit"],tuningIntervalMs:10080*60*1e3,evaluationPeriodMs:5e3};var q=ae.filter(r=>r!=="coordination");function U(){return"3.15.16"}function gt(r,e){return{version:U(),project:{name:r,root:e,type:"single"},learning:structuredClone(M),routing:structuredClone(Q),workers:structuredClone(V),hooks:structuredClone(G),skills:structuredClone(W),autoTuning:structuredClone(B),domains:{enabled:[...q],disabled:[]},agents:{maxConcurrent:15,defaultTimeout:6e4}}}le();import{readFileSync as w,existsSync as p,statSync as Pe,readdirSync as Ne}from"fs";import{join as d,basename as fe,extname as ye,relative as z}from"path";var Oe=[{name:"jest",detect:r=>{let e=["jest.config.js","jest.config.ts","jest.config.mjs","jest.config.cjs"];for(let n of e)if(p(d(r,n)))return{name:"jest",version:x(r,"jest"),configFile:n,confidence:1};let t=A(r);return t?.jest?{name:"jest",version:x(r,"jest"),configFile:"package.json",confidence:.9}:t?.devDependencies?.jest||t?.dependencies?.jest?{name:"jest",version:t.devDependencies?.jest||t.dependencies?.jest,confidence:.7}:null}},{name:"vitest",detect:r=>{let e=["vitest.config.ts","vitest.config.js","vitest.config.mts","vite.config.ts"];for(let n of e)if(p(d(r,n)))return{name:"vitest",version:x(r,"vitest"),configFile:n,confidence:1};let t=A(r);return t?.devDependencies?.vitest||t?.dependencies?.vitest?{name:"vitest",version:t.devDependencies?.vitest,confidence:.8}:null}},{name:"mocha",detect:r=>{let e=[".mocharc.js",".mocharc.json",".mocharc.yaml",".mocharc.yml"];for(let n of e)if(p(d(r,n)))return{name:"mocha",version:x(r,"mocha"),configFile:n,confidence:1};let t=A(r);return t?.devDependencies?.mocha?{name:"mocha",version:t.devDependencies?.mocha,confidence:.8}:null}},{name:"pytest",detect:r=>{let e=["pytest.ini","pyproject.toml","setup.cfg"];for(let n of e){let i=d(r,n);if(p(i))try{let s=w(i,"utf-8");if(s.includes("[pytest]")||s.includes("[tool.pytest]"))return{name:"pytest",configFile:n,confidence:1}}catch(s){console.debug("[ProjectAnalyzer] Config read failed:",s instanceof Error?s.message:s)}}let t=d(r,"requirements.txt");if(p(t))try{if(w(t,"utf-8").includes("pytest"))return{name:"pytest",configFile:"requirements.txt",confidence:.8}}catch(n){console.debug("[ProjectAnalyzer] requirements.txt read failed:",n instanceof Error?n.message:n)}return null}},{name:"playwright",detect:r=>{let e=["playwright.config.ts","playwright.config.js"];for(let n of e)if(p(d(r,n)))return{name:"playwright",version:x(r,"@playwright/test"),configFile:n,confidence:1};let t=A(r);return t?.devDependencies?.["@playwright/test"]?{name:"playwright",version:t.devDependencies["@playwright/test"],confidence:.8}:null}},{name:"cypress",detect:r=>{let e=["cypress.config.ts","cypress.config.js","cypress.json"];for(let t of e)if(p(d(r,t)))return{name:"cypress",version:x(r,"cypress"),configFile:t,confidence:1};return p(d(r,"cypress"))?{name:"cypress",configFile:"cypress/",confidence:.9}:null}}],Fe=[{name:"typescript",extensions:[".ts",".tsx",".mts",".cts"]},{name:"javascript",extensions:[".js",".jsx",".mjs",".cjs"]},{name:"python",extensions:[".py",".pyw"]},{name:"java",extensions:[".java"]},{name:"go",extensions:[".go"]},{name:"rust",extensions:[".rs"]},{name:"csharp",extensions:[".cs"]},{name:"ruby",extensions:[".rb"]},{name:"php",extensions:[".php"]},{name:"kotlin",extensions:[".kt",".kts"]},{name:"swift",extensions:[".swift"]}];function A(r){let e=d(r,"package.json");if(!p(e))return null;try{return S(w(e,"utf-8"))}catch{return null}}function x(r,e){let t=A(r);if(t)return t.devDependencies?.[e]||t.dependencies?.[e]}var Le=["node_modules",".git","dist","build","coverage",".next","__pycache__",".agentic-qe",".claude",".agents",".codex",".opencode",".kiro",".cursor",".roo",".kilocode",".windsurf",".continue",".clinerules",".swarm",".claude-flow",".hive-mind"];function H(r,e,t={}){let{maxDepth:n=10,exclude:i=Le}=t;function s(o,a){if(a>n)return;let c;try{c=Ne(o)}catch{return}for(let u of c){if(i.includes(u))continue;let l=d(o,u),j;try{j=Pe(l)}catch{continue}j.isDirectory()?s(l,a+1):j.isFile()&&e(l)}}s(r,0)}var K=class{projectRoot;constructor(e){this.projectRoot=e}async analyze(){let e=Date.now(),[t,n,i,s,o]=await Promise.all([this.detectFrameworks(),this.detectLanguages(),this.detectExistingTests(),this.analyzeComplexity(),this.measureCoverage()]);return{projectName:A(this.projectRoot)?.name||fe(this.projectRoot),projectRoot:this.projectRoot,projectType:this.detectProjectType(),frameworks:t,languages:n,existingTests:i,codeComplexity:s,coverage:o,packageManager:this.detectPackageManager(),hasTypeScript:p(d(this.projectRoot,"tsconfig.json")),hasCIConfig:this.detectCIConfig(),ciProvider:this.detectCIProvider(),analysisTimestamp:new Date,analysisDurationMs:Date.now()-e}}async detectFrameworks(){let e=[];for(let t of Oe){let n=t.detect(this.projectRoot);n&&e.push(n)}return e.sort((t,n)=>n.confidence-t.confidence)}async detectLanguages(){let e=new Map,t=0;H(this.projectRoot,i=>{let s=ye(i).toLowerCase();if(s){for(let o of Fe)if(o.extensions.includes(s)){let a=e.get(o.name)||{count:0,extensions:new Set};a.count++,a.extensions.add(s),e.set(o.name,a),t++;break}}});let n=[];for(let[i,s]of e)n.push({name:i,percentage:t>0?Math.round(s.count/t*100):0,fileCount:s.count,extensions:Array.from(s.extensions)});return n.sort((i,s)=>s.fileCount-i.fileCount)}async detectExistingTests(){let e={totalCount:0,byFramework:{},byType:{unit:0,integration:0,e2e:0,unknown:0},directories:[]},t=new Set,n=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/_test\.[jt]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/,/.*Test\.java$/];return H(this.projectRoot,i=>{let s=fe(i);if(n.some(a=>a.test(s))){e.totalCount++;let a=z(this.projectRoot,i).toLowerCase();a.includes("e2e")||a.includes("cypress")||a.includes("playwright")?e.byType.e2e++:a.includes("integration")||a.includes("int-test")?e.byType.integration++:a.includes("unit")||a.includes("__tests__")||a.includes("test/")?e.byType.unit++:e.byType.unknown++;let c=z(this.projectRoot,d(i,".."));t.add(c)}}),e.directories=Array.from(t).slice(0,10),e}async analyzeComplexity(){let e=[],t=[],n=0,i=0;H(this.projectRoot,a=>{let c=ye(a);if([".ts",".tsx",".js",".jsx",".py",".java",".go"].includes(c))try{let u=w(a,"utf-8"),l=this.calculateFileComplexity(u,c);t.push(...l.functionComplexities),l.maxComplexity>n&&(n=l.maxComplexity),i++,l.maxComplexity>10&&e.push(z(this.projectRoot,a))}catch(u){console.debug("[ProjectAnalyzer] Complexity analysis read failed:",u instanceof Error?u.message:u)}});let s=t.reduce((a,c)=>a+c,0),o=t.length>0?s/t.length:0;return{averageCyclomatic:Math.round(o*10)/10,maxCyclomatic:n,totalFiles:i,complexFiles:e.slice(0,20),recommendation:o<5?"simple":o<15?"medium":"complex"}}calculateFileComplexity(e,t){let n=this.stripCommentsAndStrings(e,t),i=this.calculateComplexity(n);return{functionComplexities:[i],maxComplexity:i}}removeDelimitedBlocks(e,t,n){let i="",s=0;for(;s<e.length;){let o=e.indexOf(t,s);if(o===-1){i+=e.slice(s);break}i+=e.slice(s,o);let a=e.indexOf(n,o+t.length);if(a===-1)break;s=a+n.length}return i}stripCommentsAndStrings(e,t){let n=e;return[".ts",".tsx",".js",".jsx",".java",".go"].includes(t)?(n=n.split(`
3
3
  `).map(i=>{let s=i.indexOf("//");return s>=0?i.slice(0,s):i}).join(`
4
4
  `),n=this.removeDelimitedBlocks(n,"/*","*/"),n=this.removeDelimitedBlocks(n,"`","`"),n=this.removeDelimitedBlocks(n,'"','"'),n=this.removeDelimitedBlocks(n,"'","'")):t===".py"&&(n=n.split(`
5
5
  `).map(i=>{let s=i.indexOf("#");return s>=0?i.slice(0,s):i}).join(`
6
- `),n=this.removeDelimitedBlocks(n,'"""','"""'),n=this.removeDelimitedBlocks(n,"'''","'''"),n=this.removeDelimitedBlocks(n,'"','"'),n=this.removeDelimitedBlocks(n,"'","'")),n}calculateComplexity(e){let t=1,n=[{pattern:/(?<![a-zA-Z])if\s*\(/g,name:"if"},{pattern:/\bfor\s*\(/g,name:"for"},{pattern:/\bwhile\s*\(/g,name:"while"},{pattern:/\bcase\s+[^:]+:/g,name:"case"},{pattern:/\bcatch\s*\(/g,name:"catch"},{pattern:/&&/g,name:"&&"},{pattern:/\|\|/g,name:"||"},{pattern:/\?[^?:]+:/g,name:"ternary"},{pattern:/\belif\s+/g,name:"elif"},{pattern:/\bexcept\s*(?:\w+)?:/g,name:"except"},{pattern:/\bfor\s+\w+\s+in\s+/g,name:"for-in"},{pattern:/\bselect\s*\{/g,name:"select"}];for(let{pattern:i}of n){let s=e.match(i);s&&(t+=s.length)}return t}async measureCoverage(){let e=["coverage/lcov-report/index.html","coverage/coverage-summary.json","coverage/clover.xml","coverage/lcov.info","htmlcov/index.html"];for(let t of e){let n=d(this.projectRoot,t);if(p(n)){if(t.endsWith(".json"))try{let s=S(w(n,"utf-8")).total||{};return{lines:s.lines?.pct||0,branches:s.branches?.pct||0,functions:s.functions?.pct||0,statements:s.statements?.pct||0,hasReport:!0,reportPath:t}}catch(i){console.debug("[ProjectAnalyzer] Coverage report parse failed:",i instanceof Error?i.message:i)}return{lines:0,branches:0,functions:0,statements:0,hasReport:!0,reportPath:t}}}return{lines:0,branches:0,functions:0,statements:0,hasReport:!1}}detectProjectType(){if(p(d(this.projectRoot,"lerna.json"))||p(d(this.projectRoot,"pnpm-workspace.yaml"))||p(d(this.projectRoot,"packages")))return"monorepo";let e=A(this.projectRoot);return e?.workspaces?"monorepo":e?.main||e?.module||e?.exports?"library":"single"}detectPackageManager(){return p(d(this.projectRoot,"bun.lockb"))?"bun":p(d(this.projectRoot,"pnpm-lock.yaml"))?"pnpm":p(d(this.projectRoot,"yarn.lock"))?"yarn":p(d(this.projectRoot,"package-lock.json"))?"npm":"unknown"}detectCIConfig(){return[".github/workflows",".gitlab-ci.yml","Jenkinsfile",".circleci/config.yml",".travis.yml","azure-pipelines.yml"].some(t=>p(d(this.projectRoot,t)))}detectCIProvider(){if(p(d(this.projectRoot,".github/workflows")))return"github-actions";if(p(d(this.projectRoot,".gitlab-ci.yml")))return"gitlab-ci";if(p(d(this.projectRoot,"Jenkinsfile")))return"jenkins";if(p(d(this.projectRoot,".circleci/config.yml")))return"circleci";if(this.detectCIConfig())return"other"}};function pt(r){return new H(r)}var fe=[{name:"typescript-vitest",condition:r=>r.hasTypeScript&&r.frameworks.some(e=>e.name==="vitest"),apply:r=>{r.learning.embeddingModel="transformer",r.routing.confidenceThreshold=.75}},{name:"large-codebase",condition:r=>r.codeComplexity.totalFiles>500,apply:r=>{r.learning.hnswConfig.M=32,r.learning.hnswConfig.efConstruction=400,r.learning.hnswConfig.efSearch=200,r.agents.maxConcurrent=15}},{name:"small-project",condition:r=>r.codeComplexity.totalFiles<50,apply:r=>{r.learning.hnswConfig.M=8,r.learning.hnswConfig.efConstruction=100,r.workers.enabled=["pattern-consolidator","routing-accuracy-monitor"],r.workers.maxConcurrent=2,r.agents.maxConcurrent=5}},{name:"high-complexity",condition:r=>r.codeComplexity.recommendation==="complex",apply:r=>{r.autoTuning.parameters.push("complexity.analysisDepth"),r.domains.enabled=[..._]}},{name:"low-coverage",condition:r=>r.coverage.hasReport&&r.coverage.lines<50,apply:r=>{r.workers.enabled.push("coverage-gap-scanner"),r.workers.intervals["coverage-gap-scanner"]=1800*1e3}},{name:"monorepo",condition:r=>r.projectType==="monorepo",apply:r=>{r.agents.maxConcurrent=15,r.workers.maxConcurrent=6,r.domains.enabled=[...new Set([...r.domains.enabled,"code-intelligence"])]}},{name:"has-e2e",condition:r=>r.frameworks.some(e=>["playwright","cypress"].includes(e.name))||r.existingTests.byType.e2e>0,apply:r=>{r.domains.enabled=[...new Set([...r.domains.enabled,"visual-accessibility","chaos-resilience"])]}},{name:"has-ci",condition:r=>r.hasCIConfig,apply:r=>{r.hooks.ciIntegration=!0,r.domains.enabled=[...new Set([...r.domains.enabled,"quality-assessment"])]}},{name:"github-actions",condition:r=>r.ciProvider==="github-actions",apply:r=>{r.hooks.ciIntegration=!0,r.hooks.claudeCode=!0}},{name:"python-project",condition:r=>r.languages.some(e=>e.name==="python"&&e.percentage>30),apply:r=>{r.routing.mode="hybrid",r.domains.enabled=[...new Set([...r.domains.enabled,"security-compliance"])]}},{name:"java-project",condition:r=>r.languages.some(e=>e.name==="java"&&e.percentage>30),apply:r=>{r.agents.defaultTimeout=12e4}},{name:"no-tests",condition:r=>r.existingTests.totalCount===0,apply:r=>{r.workers.enabled=["pattern-consolidator"]}},{name:"many-tests",condition:r=>r.existingTests.totalCount>500,apply:r=>{r.workers.enabled=[...new Set([...r.workers.enabled,"flaky-test-detector"])],r.domains.enabled=[...new Set([...r.domains.enabled,"test-execution"])]}},{name:"security-focus",condition:r=>r.codeComplexity.totalFiles>100,apply:r=>{r.domains.enabled=[...new Set([...r.domains.enabled,"security-compliance"])]}}],K=class{rules;constructor(e={}){this.rules=e.minimal?fe.filter(t=>["typescript-vitest","large-codebase","small-project"].includes(t.name)):[...fe,...e.customRules||[]]}recommend(e){let t={version:B(),project:{name:e.projectName,root:e.projectRoot,type:e.projectType==="unknown"?"single":e.projectType},learning:this.recommendLearning(e),routing:this.recommendRouting(e),workers:this.recommendWorkers(e),hooks:this.recommendHooks(e),skills:this.recommendSkills(e),autoTuning:this.recommendAutoTuning(e),domains:{enabled:this.recommendDomains(e),disabled:[]},agents:{maxConcurrent:this.recommendMaxAgents(e),defaultTimeout:6e4}},n=[];for(let i of this.rules)i.condition(e)&&(i.apply(t,e),n.push(i.name));return t.domains.enabled=[...new Set(t.domains.enabled)],t.workers.enabled=[...new Set(t.workers.enabled)],t}getApplicableRules(e){return this.rules.filter(t=>t.condition(e)).map(t=>t.name)}recommendLearning(e){let t=structuredClone($);return e.codeComplexity.totalFiles>1e3?t.hnswConfig={M:32,efConstruction:400,efSearch:200}:e.codeComplexity.totalFiles<100&&(t.hnswConfig={M:8,efConstruction:100,efSearch:50}),e.languages.some(n=>["typescript","javascript"].includes(n.name))&&(t.embeddingModel="transformer"),t}recommendRouting(e){let t=structuredClone(M);return e.codeComplexity.recommendation==="simple"?t.mode="rules":e.codeComplexity.recommendation==="complex"?t.mode="ml":t.mode="hybrid",t}recommendWorkers(e){let t=structuredClone(Q),n=new Set(["pattern-consolidator","routing-accuracy-monitor"]);return(!e.coverage.hasReport||e.coverage.lines<70)&&n.add("coverage-gap-scanner"),e.existingTests.totalCount>100&&n.add("flaky-test-detector"),t.enabled=Array.from(n),e.codeComplexity.totalFiles>500?t.maxConcurrent=6:e.codeComplexity.totalFiles<50&&(t.maxConcurrent=2),t}recommendHooks(e){let t=structuredClone(V);return t.ciIntegration=e.hasCIConfig,t.preCommit=e.existingTests.totalCount>50,t}recommendSkills(e){let t=structuredClone(G);return t.install=!0,t.installV2=!0,t.installV3=!0,t}recommendAutoTuning(e){let t=structuredClone(W);return e.codeComplexity.totalFiles<20&&(t.enabled=!1),t}recommendDomains(e){return[..._]}recommendMaxAgents(e){return e.projectType==="monorepo"?15:e.codeComplexity.totalFiles>500?12:e.codeComplexity.totalFiles>100?8:5}};function yt(r){return new K(r)}Ee();import{existsSync as ye,readFileSync as Oe,writeFileSync as Fe}from"fs";function bt(r){if(!ye(r))return null;let e=`${r}.backup`;if(ye(e))return null;try{return Fe(e,Oe(r,"utf-8"),"utf-8"),e}catch{return null}}var Le=[/\baqe\b/i,/\bagentic-qe\b/i,/\bnpx\s+agentic-qe\b/i,/\bnpx\s+@anthropics\/agentic-qe\b/i,/aqe-hook\.cjs/i,/brain-checkpoint\.cjs/i,/statusline-v3\.cjs/i];function $e(r){let e=r;return!e?.hooks||!Array.isArray(e.hooks)?!1:e.hooks.some(t=>!t.command||typeof t.command!="string"?!1:Le.some(n=>n.test(t.command)))}function At(r,e){let t={};for(let[n,i]of Object.entries(e)){let s=ae(r,n)||[],o=Array.isArray(s)?s.filter(a=>!$e(a)):[];L(t,n,[...i,...o])}for(let[n,i]of Object.entries(r))Object.hasOwn(t,n)||L(t,n,i);return t}function St(r,e,t={}){let n={...e,...r||{}};if(t.memoryBackend==="memory"){for(let i of["AQE_MEMORY_PATH","AQE_V3_REASONING_BANK"])n[i]===".agentic-qe/memory.db"&&delete n[i];n.AQE_MEMORY_BACKEND="memory",n.AQE_LEARNING_ENABLED="false",n.AQE_WORKERS_ENABLED="false"}else if(r?.AQE_MEMORY_BACKEND==="memory")for(let i of["AQE_MEMORY_BACKEND","AQE_LEARNING_ENABLED","AQE_WORKERS_ENABLED"])Object.prototype.hasOwnProperty.call(e,i)?n[i]=e[i]:delete n[i];return n}function xt(r,e={}){let t=r.domains?.enabled||[],n=e.memoryBackend==="memory";return{...n?{AQE_MEMORY_BACKEND:"memory",AQE_WORKERS_ENABLED:"false"}:{AQE_MEMORY_PATH:".agentic-qe/memory.db"},AQE_MEMORY_ENABLED:"true",AQE_LEARNING_ENABLED:n?"false":r.learning?.enabled?"true":"false",AQE_V3_MODE:"true",AQE_V3_DDD_ENABLED:"true",AQE_V3_DOMAINS:t.join(","),AQE_V3_SWARM_SIZE:String(r.agents?.maxConcurrent??15),AQE_V3_TOPOLOGY:"hierarchical",AQE_V3_SUBLINEAR_ENABLED:"true",AQE_V3_HNSW_ENABLED:r.learning?.hnswConfig?"true":"false",AQE_V3_HOOKS_ENABLED:"true",AQE_V3_AISP_ENABLED:"true",...n?{}:{AQE_V3_REASONING_BANK:".agentic-qe/memory.db"},AQE_V3_PATTERN_PROMOTION_THRESHOLD:String(r.learning?.promotionThreshold??3),AQE_V3_SUCCESS_RATE_THRESHOLD:String(r.learning?.qualityThreshold??.7)}}function he(r){let e=r?.command;return typeof e=="string"&&/statusline-v3\.cjs|Agentic QE v3/.test(e)}function ke(r,e){if(!ve(r)||!ve(e))return e;let t={...r};for(let[n,i]of Object.entries(e))t[n]=ke(t[n],i);return t}function ve(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Ct(r,e,t={}){for(let[n,i]of Object.entries(e))if(n==="_aqePermissions"){let s=r.permissions||{},o=s.allow||[],a=[...new Set([...o,...i])];r.permissions={...s,allow:a}}else if(n==="statusLine"){if(t.statusLine===!1){he(r.statusLine)&&delete r.statusLine;continue}(r.statusLine===void 0||he(r.statusLine))&&(r.statusLine=i)}else n==="includeCoAuthoredBy"?r.includeCoAuthoredBy===void 0&&(r.includeCoAuthoredBy=i):r[n]=ke(r[n],i);if(t.memoryBackend==="memory"){let n=r.v3Learning;n?.reasoningBank&&delete n.reasoningBank.dbPath}return r}function wt(r,e,t={}){let n=r.domains?.enabled||[],i=t.memoryBackend==="memory";return{aqe:{version:r.version??"3.0.0",initialized:new Date().toISOString(),hooksConfigured:!0},statusLine:{type:"command",command:`sh -c 'node "\${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/statusline-v3.cjs" 2>/dev/null || echo "\u258A Agentic QE v3"'`},_aqePermissions:["Bash(npx agentic-qe:*)","Bash(npx @anthropics/agentic-qe:*)","mcp__agentic-qe__*"],includeCoAuthoredBy:!0,v3Configuration:{domains:{total:n.length,names:n},swarm:{totalAgents:r.agents?.maxConcurrent??15,topology:"hierarchical",coordination:"queen-led"}},v3Learning:{enabled:i?!1:r.learning?.enabled??!0,reasoningBank:{...i?{}:{dbPath:".agentic-qe/memory.db"},enableHNSW:!!r.learning?.hnswConfig},patternPromotion:{threshold:r.learning?.promotionThreshold??3,successRateMin:r.learning?.qualityThreshold??.7}}}}oe();import{readFileSync as be}from"fs";import{homedir as Me}from"os";import{join as D}from"path";var Qe="agentic-qe-fleet";function Ve(r,e={}){let t=e.env??process.env,n=t.CLAUDE_CONFIG_DIR?.trim()?t.CLAUDE_CONFIG_DIR.trim():D(e.homeDir??Me(),".claude");return[{scope:"user",path:D(n,"settings.json")},{scope:"project",path:D(r,".claude","settings.json")},{scope:"local",path:D(r,".claude","settings.local.json")}]}function Ge(r){try{let e=S(be(r,"utf-8"));if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.enabledPlugins;return!t||typeof t!="object"||Array.isArray(t)?null:t}catch{return null}}function We(r){let e=r.lastIndexOf("@");return(e===-1?r:r.slice(0,e))===Qe&&e>0&&e<r.length-1}function _t(r,e={}){try{let t=new Map;for(let{scope:n,path:i}of Ve(r,e)){let s=Ge(i);if(s)for(let[o,a]of Object.entries(s))We(o)&&t.set(o,{value:a,scope:n,path:i})}for(let[n,i]of t)if(i.value===!0)return{enabled:!0,pluginKey:n,scope:i.scope,settingsPath:i.path}}catch{}return{enabled:!1}}var Be=" MCP: skipped \u2014 the agentic-qe-fleet plugin already provides the AQE MCP server (mcp__plugin_agentic-qe-fleet_agentic-qe__* tools); run `aqe init --with-mcp` to add the project entry anyway",Ue=" MCP: kept the existing project `agentic-qe` entry in .mcp.json \u2014 it duplicates the agentic-qe-fleet plugin's AQE MCP server (mcp__plugin_agentic-qe-fleet_agentic-qe__* tools); to remove it, delete the `agentic-qe` key from .mcp.json or run `claude mcp remove agentic-qe -s project`";function ze(r){try{let e=S(be(D(r,".mcp.json"),"utf-8"));if(!e||typeof e!="object")return!1;let t=e.mcpServers;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.prototype.hasOwnProperty.call(t,"agentic-qe")}catch{return!1}}function qt(r){return ze(r)?Ue:Be}F();import{existsSync as y,mkdirSync as q,readdirSync as T,statSync as J,readFileSync as He,copyFileSync as Ke,unlinkSync as Je,rmdirSync as Ye}from"fs";import{join as m}from"path";var Y=["qe-test-generation","qe-test-execution","qe-coverage-analysis","qe-quality-assessment","qe-defect-intelligence","qe-requirements-validation","qe-code-intelligence","qe-browser","pentest-validation","qe-visual-accessibility","qe-chaos-resilience","qe-learning-optimization","qe-court","qe-iterative-loop","strict-tdd","no-skip","coverage-guard","freeze-tests","security-watch","skill-stats","test-failure-investigator","coverage-drop-investigator","e2e-flow-verifier","test-metrics-dashboard"],X=["v3-core-implementation","v3-cli-modernization","v3-ddd-architecture","v3-integration-deep","v3-mcp-optimization","v3-memory-unification","v3-performance-optimization","v3-security-overhaul","v3-swarm-coordination","v3-qe-core-implementation","v3-qe-ddd-architecture","v3-qe-cli","v3-qe-memory-system","v3-qe-performance","v3-qe-security","v3-qe-mcp","v3-qe-mcp-optimization","v3-qe-memory-unification","v3-qe-integration","v3-qe-agentic-flow-integration","v3-qe-fleet-coordination","agentdb-advanced","agentdb-learning","agentdb-memory-patterns","agentdb-optimization","agentdb-vector-search","github-code-review","github-multi-repo","github-project-management","github-release-management","github-workflow-automation","flow-nexus-neural","flow-nexus-platform","flow-nexus-swarm","reasoningbank-agentdb","reasoningbank-intelligence","swarm-orchestration","swarm-advanced","sparc-methodology","hooks-automation","hive-mind-advanced","stream-chain","agentic-jujutsu","iterative-loop","performance-analysis","skill-builder","qe-agentic-flow-integration","release"],Xe=["qe-contract-testing","qe-security-compliance","aqe-v2-v3-migration"],Z=class{projectRoot;options;sourceSkillsDir;constructor(e){this.projectRoot=e.projectRoot,this.options={installV2Skills:!0,installV3Skills:!0,overwrite:!1,exclude:[],include:void 0,...e},this.sourceSkillsDir=this.findSourceSkillsDir()}findSourceSkillsDir(){let e=b(import.meta.url),t=[];e&&(t.push(m(e,"assets/skills")),t.push(m(e,".claude/skills"))),t.push(m(this.projectRoot,"node_modules/agentic-qe/assets/skills"));for(let n of t)if(y(n))return n;return t[0]}getSourceSkillsDir(){return this.sourceSkillsDir}async install(){let e={installed:[],skipped:[],removed:[],errors:[],totalCount:0,skillsDir:m(this.projectRoot,".claude","skills"),validationInstalled:!1};if(!y(this.sourceSkillsDir))return e.errors.push(`Source skills directory not found: ${this.sourceSkillsDir}`),e;let t=m(this.projectRoot,".claude","skills");y(t)||q(t,{recursive:!0});let n=this.getAvailableSkills();e.totalCount=n.length;let i=this.filterSkills(n);for(let s of i)try{let o=await this.installSkill(s,t);o?e.installed.push(o):e.skipped.push(s)}catch(o){e.errors.push(`Failed to install ${s}: ${k(o)}`)}return this.options.overwrite&&(e.removed=this.removeDeprecatedSkills(t)),e.validationInstalled=this.installValidationInfrastructure(t),await this.createSkillsIndex(t,e.installed),e}installValidationInfrastructure(e){let t=m(this.sourceSkillsDir,".validation"),n=m(e,".validation");if(!y(t))return console.debug("[SkillsInstaller] Validation infrastructure not found in source"),!1;if(y(n)&&!this.options.overwrite)return console.debug("[SkillsInstaller] Validation infrastructure already exists, skipping"),!0;try{return y(n)||q(n,{recursive:!0}),this.copyDirectoryRecursive(t,n),console.debug("[SkillsInstaller] Validation infrastructure installed successfully"),!0}catch(i){return console.error("[SkillsInstaller] Failed to install validation infrastructure:",i instanceof Error?i.message:i),!1}}removeDeprecatedSkills(e){let t=[];for(let n of Xe){let i=m(e,n);if(y(i))try{this.removeDirectoryRecursive(i),t.push(n)}catch(s){console.error(`[SkillsInstaller] Failed to remove deprecated skill ${n}:`,s instanceof Error?s.message:s)}}return t.length>0&&console.debug(`[SkillsInstaller] Removed ${t.length} deprecated skills: ${t.join(", ")}`),t}removeDirectoryRecursive(e){let t=T(e,{withFileTypes:!0});for(let n of t){let i=m(e,n.name);n.isDirectory()?this.removeDirectoryRecursive(i):Je(i)}Ye(e)}getAvailableSkills(){try{return T(this.sourceSkillsDir).filter(t=>{let n=m(this.sourceSkillsDir,t);return J(n).isDirectory()&&!t.startsWith(".")})}catch{return[]}}filterSkills(e){let t=e;return t=t.filter(n=>!X.includes(n)),this.options.include&&this.options.include.length>0&&(t=t.filter(n=>this.options.include.includes(n))),this.options.exclude&&this.options.exclude.length>0&&(t=t.filter(n=>!this.options.exclude.some(i=>n.includes(i)||n.match(new RegExp(i))))),this.options.installV3Skills||(t=t.filter(n=>!Y.includes(n))),this.options.installV2Skills||(t=t.filter(n=>Y.includes(n))),t}async installSkill(e,t){let n=m(this.sourceSkillsDir,e),i=m(t,e);if(y(i)&&!this.options.overwrite)return null;y(i)||q(i,{recursive:!0}),this.copyDirectoryRecursive(n,i);let s=this.getSkillType(e),o=this.getSkillDescription(i),a=y(m(i,"resources"));return{name:e,type:s,description:o,hasResources:a}}copyDirectoryRecursive(e,t){let n=T(e);for(let i of n){let s=m(e,i),o=m(t,i);J(s).isDirectory()?(y(o)||q(o,{recursive:!0}),this.copyDirectoryRecursive(s,o)):Ke(s,o)}}getSkillType(e){return Y.includes(e)?"v3-domain":"v2-methodology"}getSkillDescription(e){let t=m(e,"SKILL.md");if(y(t))try{let n=He(t,"utf-8"),i=n.match(/description:\s*["']?([^"'\n]+)["']?/i);if(i)return i[1].trim();let s=n.split(`
7
- `);for(let o of s){let a=o.trim();if(a&&!a.startsWith("#")&&!a.startsWith("-")&&!a.startsWith("```"))return a.slice(0,100)+(a.length>100?"...":"")}}catch(n){console.debug("[SkillsInstaller] Failed to read skill description:",n instanceof Error?n.message:n)}}async createSkillsIndex(e,t){let n=this.scanSkillsDirectory(e),i=n.filter(l=>!X.includes(l.name)),s=i.filter(l=>l.type==="v2-methodology"),o=i.filter(l=>l.type==="v3-domain"),a=n.filter(l=>X.includes(l.name)),c=y(m(e,".validation")),u=`# AQE Skills Index
6
+ `),n=this.removeDelimitedBlocks(n,'"""','"""'),n=this.removeDelimitedBlocks(n,"'''","'''"),n=this.removeDelimitedBlocks(n,'"','"'),n=this.removeDelimitedBlocks(n,"'","'")),n}calculateComplexity(e){let t=1,n=[{pattern:/(?<![a-zA-Z])if\s*\(/g,name:"if"},{pattern:/\bfor\s*\(/g,name:"for"},{pattern:/\bwhile\s*\(/g,name:"while"},{pattern:/\bcase\s+[^:]+:/g,name:"case"},{pattern:/\bcatch\s*\(/g,name:"catch"},{pattern:/&&/g,name:"&&"},{pattern:/\|\|/g,name:"||"},{pattern:/\?[^?:]+:/g,name:"ternary"},{pattern:/\belif\s+/g,name:"elif"},{pattern:/\bexcept\s*(?:\w+)?:/g,name:"except"},{pattern:/\bfor\s+\w+\s+in\s+/g,name:"for-in"},{pattern:/\bselect\s*\{/g,name:"select"}];for(let{pattern:i}of n){let s=e.match(i);s&&(t+=s.length)}return t}async measureCoverage(){let e=["coverage/lcov-report/index.html","coverage/coverage-summary.json","coverage/clover.xml","coverage/lcov.info","htmlcov/index.html"];for(let t of e){let n=d(this.projectRoot,t);if(p(n)){if(t.endsWith(".json"))try{let s=S(w(n,"utf-8")).total||{};return{lines:s.lines?.pct||0,branches:s.branches?.pct||0,functions:s.functions?.pct||0,statements:s.statements?.pct||0,hasReport:!0,reportPath:t}}catch(i){console.debug("[ProjectAnalyzer] Coverage report parse failed:",i instanceof Error?i.message:i)}return{lines:0,branches:0,functions:0,statements:0,hasReport:!0,reportPath:t}}}return{lines:0,branches:0,functions:0,statements:0,hasReport:!1}}detectProjectType(){if(p(d(this.projectRoot,"lerna.json"))||p(d(this.projectRoot,"pnpm-workspace.yaml"))||p(d(this.projectRoot,"packages")))return"monorepo";let e=A(this.projectRoot);return e?.workspaces?"monorepo":e?.main||e?.module||e?.exports?"library":"single"}detectPackageManager(){return p(d(this.projectRoot,"bun.lockb"))?"bun":p(d(this.projectRoot,"pnpm-lock.yaml"))?"pnpm":p(d(this.projectRoot,"yarn.lock"))?"yarn":p(d(this.projectRoot,"package-lock.json"))?"npm":"unknown"}detectCIConfig(){return[".github/workflows",".gitlab-ci.yml","Jenkinsfile",".circleci/config.yml",".travis.yml","azure-pipelines.yml"].some(t=>p(d(this.projectRoot,t)))}detectCIProvider(){if(p(d(this.projectRoot,".github/workflows")))return"github-actions";if(p(d(this.projectRoot,".gitlab-ci.yml")))return"gitlab-ci";if(p(d(this.projectRoot,"Jenkinsfile")))return"jenkins";if(p(d(this.projectRoot,".circleci/config.yml")))return"circleci";if(this.detectCIConfig())return"other"}};function yt(r){return new K(r)}var he=[{name:"typescript-vitest",condition:r=>r.hasTypeScript&&r.frameworks.some(e=>e.name==="vitest"),apply:r=>{r.learning.embeddingModel="transformer",r.routing.confidenceThreshold=.75}},{name:"large-codebase",condition:r=>r.codeComplexity.totalFiles>500,apply:r=>{r.learning.hnswConfig.M=32,r.learning.hnswConfig.efConstruction=400,r.learning.hnswConfig.efSearch=200,r.agents.maxConcurrent=15}},{name:"small-project",condition:r=>r.codeComplexity.totalFiles<50,apply:r=>{r.learning.hnswConfig.M=8,r.learning.hnswConfig.efConstruction=100,r.workers.enabled=["pattern-consolidator","routing-accuracy-monitor"],r.workers.maxConcurrent=2,r.agents.maxConcurrent=5}},{name:"high-complexity",condition:r=>r.codeComplexity.recommendation==="complex",apply:r=>{r.autoTuning.parameters.push("complexity.analysisDepth"),r.domains.enabled=[...q]}},{name:"low-coverage",condition:r=>r.coverage.hasReport&&r.coverage.lines<50,apply:r=>{r.workers.enabled.push("coverage-gap-scanner"),r.workers.intervals["coverage-gap-scanner"]=1800*1e3}},{name:"monorepo",condition:r=>r.projectType==="monorepo",apply:r=>{r.agents.maxConcurrent=15,r.workers.maxConcurrent=6,r.domains.enabled=[...new Set([...r.domains.enabled,"code-intelligence"])]}},{name:"has-e2e",condition:r=>r.frameworks.some(e=>["playwright","cypress"].includes(e.name))||r.existingTests.byType.e2e>0,apply:r=>{r.domains.enabled=[...new Set([...r.domains.enabled,"visual-accessibility","chaos-resilience"])]}},{name:"has-ci",condition:r=>r.hasCIConfig,apply:r=>{r.hooks.ciIntegration=!0,r.domains.enabled=[...new Set([...r.domains.enabled,"quality-assessment"])]}},{name:"github-actions",condition:r=>r.ciProvider==="github-actions",apply:r=>{r.hooks.ciIntegration=!0,r.hooks.claudeCode=!0}},{name:"python-project",condition:r=>r.languages.some(e=>e.name==="python"&&e.percentage>30),apply:r=>{r.routing.mode="hybrid",r.domains.enabled=[...new Set([...r.domains.enabled,"security-compliance"])]}},{name:"java-project",condition:r=>r.languages.some(e=>e.name==="java"&&e.percentage>30),apply:r=>{r.agents.defaultTimeout=12e4}},{name:"no-tests",condition:r=>r.existingTests.totalCount===0,apply:r=>{r.workers.enabled=["pattern-consolidator"]}},{name:"many-tests",condition:r=>r.existingTests.totalCount>500,apply:r=>{r.workers.enabled=[...new Set([...r.workers.enabled,"flaky-test-detector"])],r.domains.enabled=[...new Set([...r.domains.enabled,"test-execution"])]}},{name:"security-focus",condition:r=>r.codeComplexity.totalFiles>100,apply:r=>{r.domains.enabled=[...new Set([...r.domains.enabled,"security-compliance"])]}}],J=class{rules;constructor(e={}){this.rules=e.minimal?he.filter(t=>["typescript-vitest","large-codebase","small-project"].includes(t.name)):[...he,...e.customRules||[]]}recommend(e){let t={version:U(),project:{name:e.projectName,root:e.projectRoot,type:e.projectType==="unknown"?"single":e.projectType},learning:this.recommendLearning(e),routing:this.recommendRouting(e),workers:this.recommendWorkers(e),hooks:this.recommendHooks(e),skills:this.recommendSkills(e),autoTuning:this.recommendAutoTuning(e),domains:{enabled:this.recommendDomains(e),disabled:[]},agents:{maxConcurrent:this.recommendMaxAgents(e),defaultTimeout:6e4}},n=[];for(let i of this.rules)i.condition(e)&&(i.apply(t,e),n.push(i.name));return t.domains.enabled=[...new Set(t.domains.enabled)],t.workers.enabled=[...new Set(t.workers.enabled)],t}getApplicableRules(e){return this.rules.filter(t=>t.condition(e)).map(t=>t.name)}recommendLearning(e){let t=structuredClone(M);return e.codeComplexity.totalFiles>1e3?t.hnswConfig={M:32,efConstruction:400,efSearch:200}:e.codeComplexity.totalFiles<100&&(t.hnswConfig={M:8,efConstruction:100,efSearch:50}),e.languages.some(n=>["typescript","javascript"].includes(n.name))&&(t.embeddingModel="transformer"),t}recommendRouting(e){let t=structuredClone(Q);return e.codeComplexity.recommendation==="simple"?t.mode="rules":e.codeComplexity.recommendation==="complex"?t.mode="ml":t.mode="hybrid",t}recommendWorkers(e){let t=structuredClone(V),n=new Set(["pattern-consolidator","routing-accuracy-monitor"]);return(!e.coverage.hasReport||e.coverage.lines<70)&&n.add("coverage-gap-scanner"),e.existingTests.totalCount>100&&n.add("flaky-test-detector"),t.enabled=Array.from(n),e.codeComplexity.totalFiles>500?t.maxConcurrent=6:e.codeComplexity.totalFiles<50&&(t.maxConcurrent=2),t}recommendHooks(e){let t=structuredClone(G);return t.ciIntegration=e.hasCIConfig,t.preCommit=e.existingTests.totalCount>50,t}recommendSkills(e){let t=structuredClone(W);return t.install=!0,t.installV2=!0,t.installV3=!0,t}recommendAutoTuning(e){let t=structuredClone(B);return e.codeComplexity.totalFiles<20&&(t.enabled=!1),t}recommendDomains(e){return[...q]}recommendMaxAgents(e){return e.projectType==="monorepo"?15:e.codeComplexity.totalFiles>500?12:e.codeComplexity.totalFiles>100?8:5}};function kt(r){return new J(r)}qe();import{existsSync as Y,readFileSync as ke,writeFileSync as be}from"fs";function xt(r){if(!Y(r))return null;let e=`${r}.backup`;if(Y(e))return null;try{return be(e,ke(r,"utf-8"),"utf-8"),e}catch{return null}}var $e=[/\baqe\b/i,/\bagentic-qe\b/i,/\bnpx\s+agentic-qe\b/i,/\bnpx\s+@anthropics\/agentic-qe\b/i,/aqe-hook\.cjs/i,/brain-checkpoint\.cjs/i,/statusline-v3\.cjs/i];function Me(r){let e=r;return!e?.hooks||!Array.isArray(e.hooks)?!1:e.hooks.some(t=>!t.command||typeof t.command!="string"?!1:$e.some(n=>n.test(t.command)))}function Ct(r,e){let t={};for(let[n,i]of Object.entries(e)){let s=ce(r,n)||[],o=Array.isArray(s)?s.filter(a=>!Me(a)):[];$(t,n,[...i,...o])}for(let[n,i]of Object.entries(r))Object.hasOwn(t,n)||$(t,n,i);return t}function wt(r,e,t={}){let n={...e,...r||{}};if(t.memoryBackend==="memory"){for(let i of["AQE_MEMORY_PATH","AQE_V3_REASONING_BANK"])n[i]===".agentic-qe/memory.db"&&delete n[i];n.AQE_MEMORY_BACKEND="memory",n.AQE_LEARNING_ENABLED="false",n.AQE_WORKERS_ENABLED="false"}else if(r?.AQE_MEMORY_BACKEND==="memory")for(let i of["AQE_MEMORY_BACKEND","AQE_LEARNING_ENABLED","AQE_WORKERS_ENABLED"])Object.prototype.hasOwnProperty.call(e,i)?n[i]=e[i]:delete n[i];return n}function Dt(r,e={}){let t=r.domains?.enabled||[],n=e.memoryBackend==="memory";return{...n?{AQE_MEMORY_BACKEND:"memory",AQE_WORKERS_ENABLED:"false"}:{AQE_MEMORY_PATH:".agentic-qe/memory.db"},AQE_MEMORY_ENABLED:"true",AQE_LEARNING_ENABLED:n?"false":r.learning?.enabled?"true":"false",AQE_V3_MODE:"true",AQE_V3_DDD_ENABLED:"true",AQE_V3_DOMAINS:t.join(","),AQE_V3_SWARM_SIZE:String(r.agents?.maxConcurrent??15),AQE_V3_TOPOLOGY:"hierarchical",AQE_V3_SUBLINEAR_ENABLED:"true",AQE_V3_HNSW_ENABLED:r.learning?.hnswConfig?"true":"false",AQE_V3_HOOKS_ENABLED:"true",AQE_V3_AISP_ENABLED:"true",...n?{}:{AQE_V3_REASONING_BANK:".agentic-qe/memory.db"},AQE_V3_PATTERN_PROMOTION_THRESHOLD:String(r.learning?.promotionThreshold??3),AQE_V3_SUCCESS_RATE_THRESHOLD:String(r.learning?.qualityThreshold??.7)}}function ve(r){let e=r?.command;return typeof e=="string"&&/statusline-v3\.cjs|Agentic QE v3/.test(e)}function Ae(r,e){if(!D(r)||!D(e))return e;let t={...r};for(let[n,i]of Object.entries(e))t[n]=Ae(t[n],i);return t}function D(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}var Se=/@anthropics\/agentic-qe\b/i;function Qe(r){return r.filter(e=>typeof e!="string"||!Se.test(e))}function Ve(r){let e=[];for(let[t,n]of Object.entries(r)){let{command:i,args:s}=D(n)?n:{};[i,...Array.isArray(s)?s:[]].some(a=>typeof a=="string"&&Se.test(a))&&(delete r[t],e.push(t))}return e}function Rt(r){if(!Y(r))return[];let e;try{e=JSON.parse(ke(r,"utf-8"))}catch{return[]}if(!D(e)||!D(e.mcpServers))return[];let t=Ve(e.mcpServers);return t.length>0&&be(r,JSON.stringify(e,null,2),"utf-8"),t}function Et(r,e,t={}){for(let[n,i]of Object.entries(e))if(n==="_aqePermissions"){let s=r.permissions||{},o=Qe(s.allow||[]),a=[...new Set([...o,...i])];r.permissions={...s,allow:a}}else if(n==="statusLine"){if(t.statusLine===!1){ve(r.statusLine)&&delete r.statusLine;continue}(r.statusLine===void 0||ve(r.statusLine))&&(r.statusLine=i)}else n==="includeCoAuthoredBy"?r.includeCoAuthoredBy===void 0&&(r.includeCoAuthoredBy=i):r[n]=Ae(r[n],i);if(t.memoryBackend==="memory"){let n=r.v3Learning;n?.reasoningBank&&delete n.reasoningBank.dbPath}return r}function jt(r,e,t={}){let n=r.domains?.enabled||[],i=t.memoryBackend==="memory";return{aqe:{version:r.version??"3.0.0",initialized:new Date().toISOString(),hooksConfigured:!0},statusLine:{type:"command",command:`sh -c 'node "\${CLAUDE_PROJECT_DIR:-.}/.claude/helpers/statusline-v3.cjs" 2>/dev/null || echo "\u258A Agentic QE v3"'`},_aqePermissions:["Bash(npx agentic-qe:*)","mcp__agentic-qe__*"],includeCoAuthoredBy:!0,v3Configuration:{domains:{total:n.length,names:n},swarm:{totalAgents:r.agents?.maxConcurrent??15,topology:"hierarchical",coordination:"queen-led"}},v3Learning:{enabled:i?!1:r.learning?.enabled??!0,reasoningBank:{...i?{}:{dbPath:".agentic-qe/memory.db"},enableHNSW:!!r.learning?.hnswConfig},patternPromotion:{threshold:r.learning?.promotionThreshold??3,successRateMin:r.learning?.qualityThreshold??.7}}}}le();import{readFileSync as xe}from"fs";import{homedir as Ge}from"os";import{join as R}from"path";var We="agentic-qe-fleet";function Be(r,e={}){let t=e.env??process.env,n=t.CLAUDE_CONFIG_DIR?.trim()?t.CLAUDE_CONFIG_DIR.trim():R(e.homeDir??Ge(),".claude");return[{scope:"user",path:R(n,"settings.json")},{scope:"project",path:R(r,".claude","settings.json")},{scope:"local",path:R(r,".claude","settings.local.json")}]}function Ue(r){try{let e=S(xe(r,"utf-8"));if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.enabledPlugins;return!t||typeof t!="object"||Array.isArray(t)?null:t}catch{return null}}function ze(r){let e=r.lastIndexOf("@");return(e===-1?r:r.slice(0,e))===We&&e>0&&e<r.length-1}function Nt(r,e={}){try{let t=new Map;for(let{scope:n,path:i}of Be(r,e)){let s=Ue(i);if(s)for(let[o,a]of Object.entries(s))ze(o)&&t.set(o,{value:a,scope:n,path:i})}for(let[n,i]of t)if(i.value===!0)return{enabled:!0,pluginKey:n,scope:i.scope,settingsPath:i.path}}catch{}return{enabled:!1}}var He=" MCP: skipped \u2014 the agentic-qe-fleet plugin already provides the AQE MCP server (mcp__plugin_agentic-qe-fleet_agentic-qe__* tools); run `aqe init --with-mcp` to add the project entry anyway",Ke=" MCP: kept the existing project `agentic-qe` entry in .mcp.json \u2014 it duplicates the agentic-qe-fleet plugin's AQE MCP server (mcp__plugin_agentic-qe-fleet_agentic-qe__* tools); to remove it, delete the `agentic-qe` key from .mcp.json or run `claude mcp remove agentic-qe -s project`";function Je(r){try{let e=S(xe(R(r,".mcp.json"),"utf-8"));if(!e||typeof e!="object")return!1;let t=e.mcpServers;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.prototype.hasOwnProperty.call(t,"agentic-qe")}catch{return!1}}function Ot(r){return Je(r)?Ke:He}L();import{existsSync as y,mkdirSync as T,readdirSync as P,statSync as X,readFileSync as Ye,copyFileSync as Xe,unlinkSync as Ze,rmdirSync as et}from"fs";import{join as m}from"path";var Z=["qe-test-generation","qe-test-execution","qe-coverage-analysis","qe-quality-assessment","qe-defect-intelligence","qe-requirements-validation","qe-code-intelligence","qe-browser","pentest-validation","qe-visual-accessibility","qe-chaos-resilience","qe-learning-optimization","qe-court","qe-iterative-loop","strict-tdd","no-skip","coverage-guard","freeze-tests","security-watch","skill-stats","test-failure-investigator","coverage-drop-investigator","e2e-flow-verifier","test-metrics-dashboard"],ee=["v3-core-implementation","v3-cli-modernization","v3-ddd-architecture","v3-integration-deep","v3-mcp-optimization","v3-memory-unification","v3-performance-optimization","v3-security-overhaul","v3-swarm-coordination","v3-qe-core-implementation","v3-qe-ddd-architecture","v3-qe-cli","v3-qe-memory-system","v3-qe-performance","v3-qe-security","v3-qe-mcp","v3-qe-mcp-optimization","v3-qe-memory-unification","v3-qe-integration","v3-qe-agentic-flow-integration","v3-qe-fleet-coordination","agentdb-advanced","agentdb-learning","agentdb-memory-patterns","agentdb-optimization","agentdb-vector-search","github-code-review","github-multi-repo","github-project-management","github-release-management","github-workflow-automation","flow-nexus-neural","flow-nexus-platform","flow-nexus-swarm","reasoningbank-agentdb","reasoningbank-intelligence","swarm-orchestration","swarm-advanced","sparc-methodology","hooks-automation","hive-mind-advanced","stream-chain","agentic-jujutsu","iterative-loop","performance-analysis","skill-builder","qe-agentic-flow-integration","release"],tt=["qe-contract-testing","qe-security-compliance","aqe-v2-v3-migration"],te=class{projectRoot;options;sourceSkillsDir;constructor(e){this.projectRoot=e.projectRoot,this.options={installV2Skills:!0,installV3Skills:!0,overwrite:!1,exclude:[],include:void 0,...e},this.sourceSkillsDir=this.findSourceSkillsDir()}findSourceSkillsDir(){let e=b(import.meta.url),t=[];e&&(t.push(m(e,"assets/skills")),t.push(m(e,".claude/skills"))),t.push(m(this.projectRoot,"node_modules/agentic-qe/assets/skills"));for(let n of t)if(y(n))return n;return t[0]}getSourceSkillsDir(){return this.sourceSkillsDir}async install(){let e={installed:[],skipped:[],removed:[],errors:[],totalCount:0,skillsDir:m(this.projectRoot,".claude","skills"),validationInstalled:!1};if(!y(this.sourceSkillsDir))return e.errors.push(`Source skills directory not found: ${this.sourceSkillsDir}`),e;let t=m(this.projectRoot,".claude","skills");y(t)||T(t,{recursive:!0});let n=this.getAvailableSkills();e.totalCount=n.length;let i=this.filterSkills(n);for(let s of i)try{let o=await this.installSkill(s,t);o?e.installed.push(o):e.skipped.push(s)}catch(o){e.errors.push(`Failed to install ${s}: ${k(o)}`)}return this.options.overwrite&&(e.removed=this.removeDeprecatedSkills(t)),e.validationInstalled=this.installValidationInfrastructure(t),await this.createSkillsIndex(t,e.installed),e}installValidationInfrastructure(e){let t=m(this.sourceSkillsDir,".validation"),n=m(e,".validation");if(!y(t))return console.debug("[SkillsInstaller] Validation infrastructure not found in source"),!1;if(y(n)&&!this.options.overwrite)return console.debug("[SkillsInstaller] Validation infrastructure already exists, skipping"),!0;try{return y(n)||T(n,{recursive:!0}),this.copyDirectoryRecursive(t,n),console.debug("[SkillsInstaller] Validation infrastructure installed successfully"),!0}catch(i){return console.error("[SkillsInstaller] Failed to install validation infrastructure:",i instanceof Error?i.message:i),!1}}removeDeprecatedSkills(e){let t=[];for(let n of tt){let i=m(e,n);if(y(i))try{this.removeDirectoryRecursive(i),t.push(n)}catch(s){console.error(`[SkillsInstaller] Failed to remove deprecated skill ${n}:`,s instanceof Error?s.message:s)}}return t.length>0&&console.debug(`[SkillsInstaller] Removed ${t.length} deprecated skills: ${t.join(", ")}`),t}removeDirectoryRecursive(e){let t=P(e,{withFileTypes:!0});for(let n of t){let i=m(e,n.name);n.isDirectory()?this.removeDirectoryRecursive(i):Ze(i)}et(e)}getAvailableSkills(){try{return P(this.sourceSkillsDir).filter(t=>{let n=m(this.sourceSkillsDir,t);return X(n).isDirectory()&&!t.startsWith(".")})}catch{return[]}}filterSkills(e){let t=e;return t=t.filter(n=>!ee.includes(n)),this.options.include&&this.options.include.length>0&&(t=t.filter(n=>this.options.include.includes(n))),this.options.exclude&&this.options.exclude.length>0&&(t=t.filter(n=>!this.options.exclude.some(i=>n.includes(i)||n.match(new RegExp(i))))),this.options.installV3Skills||(t=t.filter(n=>!Z.includes(n))),this.options.installV2Skills||(t=t.filter(n=>Z.includes(n))),t}async installSkill(e,t){let n=m(this.sourceSkillsDir,e),i=m(t,e);if(y(i)&&!this.options.overwrite)return null;y(i)||T(i,{recursive:!0}),this.copyDirectoryRecursive(n,i);let s=this.getSkillType(e),o=this.getSkillDescription(i),a=y(m(i,"resources"));return{name:e,type:s,description:o,hasResources:a}}copyDirectoryRecursive(e,t){let n=P(e);for(let i of n){let s=m(e,i),o=m(t,i);X(s).isDirectory()?(y(o)||T(o,{recursive:!0}),this.copyDirectoryRecursive(s,o)):Xe(s,o)}}getSkillType(e){return Z.includes(e)?"v3-domain":"v2-methodology"}getSkillDescription(e){let t=m(e,"SKILL.md");if(y(t))try{let n=Ye(t,"utf-8"),i=n.match(/description:\s*["']?([^"'\n]+)["']?/i);if(i)return i[1].trim();let s=n.split(`
7
+ `);for(let o of s){let a=o.trim();if(a&&!a.startsWith("#")&&!a.startsWith("-")&&!a.startsWith("```"))return a.slice(0,100)+(a.length>100?"...":"")}}catch(n){console.debug("[SkillsInstaller] Failed to read skill description:",n instanceof Error?n.message:n)}}async createSkillsIndex(e,t){let n=this.scanSkillsDirectory(e),i=n.filter(l=>!ee.includes(l.name)),s=i.filter(l=>l.type==="v2-methodology"),o=i.filter(l=>l.type==="v3-domain"),a=n.filter(l=>ee.includes(l.name)),c=y(m(e,".validation")),u=`# AQE Skills Index
8
8
 
9
9
  This directory contains Quality Engineering skills managed by Agentic QE.
10
10
 
@@ -54,11 +54,11 @@ See \`.validation/README.md\` for usage instructions.
54
54
  ---
55
55
 
56
56
  *Generated by AQE v3 init on ${new Date().toISOString()}*
57
- `;E(m(e,"README.md"),u,I)}scanSkillsDirectory(e){let t=[];try{let n=T(e);for(let i of n){if(i.startsWith("."))continue;let s=m(e,i);if(!J(s).isDirectory())continue;let o=m(s,"SKILL.md");if(!y(o))continue;let a=this.getSkillType(i),c=this.getSkillDescription(s),u=y(m(s,"resources"));t.push({name:i,type:a,description:c,hasResources:u})}}catch(n){console.debug("[SkillsInstaller] Failed to scan skills directory:",n instanceof Error?n.message:n)}return t.sort((n,i)=>n.name.localeCompare(i.name))}};function $t(r){return new Z(r)}F();import{existsSync as f,mkdirSync as R,readdirSync as ee,statSync as Ae,readFileSync as Se,writeFileSync as Ze,copyFileSync as te}from"fs";import{join as g}from"path";function et(r){let e=new Date().toISOString().slice(0,10),t=r.match(/^---\n([\s\S]*?)\n---/);if(!t)return r;let n=t[1],i;return/^updated:/m.test(n)?i=n.replace(/^updated:.*$/m,`updated: ${e}`):/^created:/m.test(n)?i=n.replace(/^(created:.*$)/m,`$1
57
+ `;I(m(e,"README.md"),u,_)}scanSkillsDirectory(e){let t=[];try{let n=P(e);for(let i of n){if(i.startsWith("."))continue;let s=m(e,i);if(!X(s).isDirectory())continue;let o=m(s,"SKILL.md");if(!y(o))continue;let a=this.getSkillType(i),c=this.getSkillDescription(s),u=y(m(s,"resources"));t.push({name:i,type:a,description:c,hasResources:u})}}catch(n){console.debug("[SkillsInstaller] Failed to scan skills directory:",n instanceof Error?n.message:n)}return t.sort((n,i)=>n.name.localeCompare(i.name))}};function Gt(r){return new te(r)}L();import{existsSync as f,mkdirSync as E,readdirSync as ne,statSync as Ce,readFileSync as we,writeFileSync as nt,copyFileSync as re}from"fs";import{join as g}from"path";function rt(r){let e=new Date().toISOString().slice(0,10),t=r.match(/^---\n([\s\S]*?)\n---/);if(!t)return r;let n=t[1],i;return/^updated:/m.test(n)?i=n.replace(/^updated:.*$/m,`updated: ${e}`):/^created:/m.test(n)?i=n.replace(/^(created:.*$)/m,`$1
58
58
  updated: ${e}`):i=n+`
59
59
  updated: ${e}`,r.replace(/^---\n[\s\S]*?\n---/,`---
60
60
  ${i}
61
- ---`)}var tt=["qe-test-architect","qe-bdd-generator","qe-property-tester","qe-mutation-tester","qe-test-idea-rewriter","qe-quality-criteria-recommender","qe-parallel-executor","qe-flaky-hunter","qe-retry-handler","qe-coverage-specialist","qe-gap-detector","qe-quality-gate","qe-code-complexity","qe-deployment-advisor","qe-risk-assessor","qe-defect-predictor","qe-regression-analyzer","qe-root-cause-analyzer","qe-impact-analyzer","qe-requirements-validator","qe-qx-partner","qe-product-factors-assessor","qe-code-intelligence","qe-kg-builder","qe-dependency-mapper","qe-security-scanner","qe-security-auditor","qe-pentest-validator","qe-contract-validator","qe-graphql-tester","qe-visual-tester","qe-accessibility-auditor","qe-responsive-tester","qe-chaos-engineer","qe-load-tester","qe-performance-tester","qe-learning-coordinator","qe-pattern-learner","qe-metrics-optimizer","qe-transfer-specialist","qe-soap-tester","qe-sap-rfc-tester","qe-sap-idoc-tester","qe-odata-contract-tester","qe-middleware-validator","qe-message-broker-tester","qe-sod-analyzer","qe-fleet-commander","qe-queen-coordinator","qe-tdd-specialist","qe-integration-tester","qe-integration-architect"],nt=["qe-code-reviewer","qe-integration-reviewer","qe-performance-reviewer","qe-security-reviewer","qe-tdd-red","qe-tdd-green","qe-tdd-refactor"],ne=class{projectRoot;options;sourceAgentsDir;constructor(e){this.projectRoot=e.projectRoot,this.options={installQEAgents:!0,installSubagents:!0,overwrite:!1,exclude:[],include:void 0,...e},this.sourceAgentsDir=this.findSourceAgentsDir()}findSourceAgentsDir(){let e=b(import.meta.url),t=[];e&&(t.push(g(e,"assets/agents/v3")),t.push(g(e,".claude/agents/v3"))),t.push(g(this.projectRoot,"node_modules/agentic-qe/assets/agents/v3"));for(let n of t)if(f(n))return n;return t[0]}preserveOverridesDir(){let e=g(this.projectRoot,".claude","agent-overrides");f(e)||R(e,{recursive:!0});let t=g(e,"_example.yaml");if(!f(t))try{let n=b(import.meta.url),i=[...n?[g(n,"assets","templates","agent-override-example.yaml")]:[],g(this.projectRoot,"node_modules","agentic-qe","assets","templates","agent-override-example.yaml")];for(let s of i)if(f(s)){te(s,t);break}}catch{}}async install(){let e={installed:[],skipped:[],errors:[],totalCount:0,agentsDir:g(this.projectRoot,".claude","agents","v3"),overlaysApplied:[],overlayWarnings:[]};if(this.preserveOverridesDir(),!f(this.sourceAgentsDir))return e.errors.push(`Source agents directory not found: ${this.sourceAgentsDir}`),e;let t=g(this.projectRoot,".claude","agents","v3");f(t)||R(t,{recursive:!0});let n=g(t,"subagents");f(n)||R(n,{recursive:!0}),await this.copyHelpersDirectory(t),await this.copyTemplatesDirectory(t);let i=this.getAvailableAgents();e.totalCount=i.length;let s=this.filterAgents(i),o=[];for(let u of s)try{let l=await this.installAgent(u,t,n);l?(e.installed.push(l),o.push(l)):(e.skipped.push(u),o.push(this.describeAgent(u,t,n)))}catch(l){e.errors.push(`Failed to install ${u}: ${k(l)}`)}let a=ue(this.projectRoot);if(a.warnings.length>0){e.overlayWarnings=a.warnings;for(let u of a.warnings)console.error(`[AgentsInstaller] Overlay warning: ${u}`)}if(a.errors.length>0)for(let u of a.errors)e.errors.push(`Overlay error: ${u}`);for(let u of a.overlays){let l=u.agent,P=nt.includes(l)?g(n,`${l}.md`):g(t,`${l}.md`);if(!f(P)){e.overlayWarnings.push(`Overlay for "${l}" found but agent file does not exist. Skipping.`);continue}try{let N=Se(P,"utf-8"),{content:De,applied:O}=ge(N,u),Re=et(De);Ze(P,Re,"utf-8"),e.overlaysApplied.push(l);let je=[...O.replacedFields.map(C=>`replaced:${C}`),...O.appendedFields.map(C=>`appended:${C}`),...O.configOverrides.map(C=>`config:${C}`)];console.error(`[AgentsInstaller] Applied overlay for ${l}: ${je.join(", ")}`)}catch(N){e.overlayWarnings.push(`Failed to apply overlay for "${l}": ${k(N)}`)}}e.overlaysApplied.length>0&&console.error(`[AgentsInstaller] Applied ${e.overlaysApplied.length} agent overlay(s): ${e.overlaysApplied.join(", ")}`);let c=de(t,this.projectRoot);if(e.mcpValidationWarnings=c.warnings,c.warnings.length>0){console.error(`[AgentsInstaller] MCP dependency warnings (${c.agentsWithMissingDeps.length} agents affected):`);for(let u of c.warnings.slice(0,10))console.error(` ${u}`);c.warnings.length>10&&console.error(` ... and ${c.warnings.length-10} more warnings`)}return await this.createAgentsIndex(t,o),e}getAvailableAgents(){let e=[];try{let t=ee(this.sourceAgentsDir);for(let n of t){let i=g(this.sourceAgentsDir,n),s=Ae(i);if(s.isFile()&&n.endsWith(".md"))e.push(n.replace(".md",""));else if(s.isDirectory()&&n==="subagents"){let o=ee(i);for(let a of o)a.endsWith(".md")&&e.push(`subagents/${a.replace(".md","")}`)}}}catch{return[]}return e}filterAgents(e){let t=e.filter(n=>(n.includes("/")?n.split("/")[1]:n).startsWith("qe-"));return this.options.include&&this.options.include.length>0&&(t=t.filter(n=>{let i=n.includes("/")?n.split("/")[1]:n;return this.options.include.includes(i)})),this.options.exclude&&this.options.exclude.length>0&&(t=t.filter(n=>{let i=n.includes("/")?n.split("/")[1]:n;return!this.options.exclude.some(s=>i.includes(s)||i.match(new RegExp(s)))})),this.options.installQEAgents||(t=t.filter(n=>{let i=n.includes("/")?n.split("/")[1]:n;return!tt.includes(i)})),this.options.installSubagents||(t=t.filter(n=>!n.startsWith("subagents/"))),t}async installAgent(e,t,n){let i=e.startsWith("subagents/"),s=i?e.split("/")[1]:e,o=g(this.sourceAgentsDir,`${e}.md`),a=i?g(n,`${s}.md`):g(t,`${s}.md`);if(f(a)&&!this.options.overwrite)return null;if(f(o))te(o,a);else throw new Error(`Source file not found: ${o}`);return this.describeAgent(e,t,n)}describeAgent(e,t,n){let i=e.startsWith("subagents/"),s=i?e.split("/")[1]:e,o=i?g(n,`${s}.md`):g(t,`${s}.md`);return{name:s,type:this.getAgentType(s,i),description:this.getAgentDescription(o),domain:this.getAgentDomain(s)}}getAgentType(e,t){return t?"v3-subagent":"v3-qe"}copyDirectoryRecursive(e,t){if(!f(e))return;f(t)||R(t,{recursive:!0});let n=ee(e);for(let i of n){let s=g(e,i),o=g(t,i);Ae(s).isDirectory()?this.copyDirectoryRecursive(s,o):(!f(o)||this.options.overwrite)&&te(s,o)}}async copyHelpersDirectory(e){let t=g(this.sourceAgentsDir,"helpers"),n=g(this.projectRoot,".claude","helpers","v3");f(t)?this.copyDirectoryRecursive(t,n):console.error(`[AgentsInstaller] Helpers source not found: ${t}`)}async copyTemplatesDirectory(e){let t=g(this.sourceAgentsDir,"templates"),n=g(e,"templates");f(t)?this.copyDirectoryRecursive(t,n):console.error(`[AgentsInstaller] Templates source not found: ${t}`)}getAgentDescription(e){if(f(e))try{let t=Se(e,"utf-8"),n=t.match(/description:\s*["']?([^"'\n]+)["']?/i);if(n)return n[1].trim();let i=t.split(`
61
+ ---`)}var it=["qe-test-architect","qe-bdd-generator","qe-property-tester","qe-mutation-tester","qe-test-idea-rewriter","qe-quality-criteria-recommender","qe-parallel-executor","qe-flaky-hunter","qe-retry-handler","qe-coverage-specialist","qe-gap-detector","qe-quality-gate","qe-code-complexity","qe-deployment-advisor","qe-risk-assessor","qe-defect-predictor","qe-regression-analyzer","qe-root-cause-analyzer","qe-impact-analyzer","qe-requirements-validator","qe-qx-partner","qe-product-factors-assessor","qe-code-intelligence","qe-kg-builder","qe-dependency-mapper","qe-security-scanner","qe-security-auditor","qe-pentest-validator","qe-contract-validator","qe-graphql-tester","qe-visual-tester","qe-accessibility-auditor","qe-responsive-tester","qe-chaos-engineer","qe-load-tester","qe-performance-tester","qe-learning-coordinator","qe-pattern-learner","qe-metrics-optimizer","qe-transfer-specialist","qe-soap-tester","qe-sap-rfc-tester","qe-sap-idoc-tester","qe-odata-contract-tester","qe-middleware-validator","qe-message-broker-tester","qe-sod-analyzer","qe-fleet-commander","qe-queen-coordinator","qe-tdd-specialist","qe-integration-tester","qe-integration-architect"],st=["qe-code-reviewer","qe-integration-reviewer","qe-performance-reviewer","qe-security-reviewer","qe-tdd-red","qe-tdd-green","qe-tdd-refactor"],ie=class{projectRoot;options;sourceAgentsDir;constructor(e){this.projectRoot=e.projectRoot,this.options={installQEAgents:!0,installSubagents:!0,overwrite:!1,exclude:[],include:void 0,...e},this.sourceAgentsDir=this.findSourceAgentsDir()}findSourceAgentsDir(){let e=b(import.meta.url),t=[];e&&(t.push(g(e,"assets/agents/v3")),t.push(g(e,".claude/agents/v3"))),t.push(g(this.projectRoot,"node_modules/agentic-qe/assets/agents/v3"));for(let n of t)if(f(n))return n;return t[0]}preserveOverridesDir(){let e=g(this.projectRoot,".claude","agent-overrides");f(e)||E(e,{recursive:!0});let t=g(e,"_example.yaml");if(!f(t))try{let n=b(import.meta.url),i=[...n?[g(n,"assets","templates","agent-override-example.yaml")]:[],g(this.projectRoot,"node_modules","agentic-qe","assets","templates","agent-override-example.yaml")];for(let s of i)if(f(s)){re(s,t);break}}catch{}}async install(){let e={installed:[],skipped:[],errors:[],totalCount:0,agentsDir:g(this.projectRoot,".claude","agents","v3"),overlaysApplied:[],overlayWarnings:[]};if(this.preserveOverridesDir(),!f(this.sourceAgentsDir))return e.errors.push(`Source agents directory not found: ${this.sourceAgentsDir}`),e;let t=g(this.projectRoot,".claude","agents","v3");f(t)||E(t,{recursive:!0});let n=g(t,"subagents");f(n)||E(n,{recursive:!0}),await this.copyHelpersDirectory(t),await this.copyTemplatesDirectory(t);let i=this.getAvailableAgents();e.totalCount=i.length;let s=this.filterAgents(i),o=[];for(let u of s)try{let l=await this.installAgent(u,t,n);l?(e.installed.push(l),o.push(l)):(e.skipped.push(u),o.push(this.describeAgent(u,t,n)))}catch(l){e.errors.push(`Failed to install ${u}: ${k(l)}`)}let a=de(this.projectRoot);if(a.warnings.length>0){e.overlayWarnings=a.warnings;for(let u of a.warnings)console.error(`[AgentsInstaller] Overlay warning: ${u}`)}if(a.errors.length>0)for(let u of a.errors)e.errors.push(`Overlay error: ${u}`);for(let u of a.overlays){let l=u.agent,N=st.includes(l)?g(n,`${l}.md`):g(t,`${l}.md`);if(!f(N)){e.overlayWarnings.push(`Overlay for "${l}" found but agent file does not exist. Skipping.`);continue}try{let O=we(N,"utf-8"),{content:je,applied:F}=pe(O,u),Ie=rt(je);nt(N,Ie,"utf-8"),e.overlaysApplied.push(l);let _e=[...F.replacedFields.map(C=>`replaced:${C}`),...F.appendedFields.map(C=>`appended:${C}`),...F.configOverrides.map(C=>`config:${C}`)];console.error(`[AgentsInstaller] Applied overlay for ${l}: ${_e.join(", ")}`)}catch(O){e.overlayWarnings.push(`Failed to apply overlay for "${l}": ${k(O)}`)}}e.overlaysApplied.length>0&&console.error(`[AgentsInstaller] Applied ${e.overlaysApplied.length} agent overlay(s): ${e.overlaysApplied.join(", ")}`);let c=me(t,this.projectRoot);if(e.mcpValidationWarnings=c.warnings,c.warnings.length>0){console.error(`[AgentsInstaller] MCP dependency warnings (${c.agentsWithMissingDeps.length} agents affected):`);for(let u of c.warnings.slice(0,10))console.error(` ${u}`);c.warnings.length>10&&console.error(` ... and ${c.warnings.length-10} more warnings`)}return await this.createAgentsIndex(t,o),e}getAvailableAgents(){let e=[];try{let t=ne(this.sourceAgentsDir);for(let n of t){let i=g(this.sourceAgentsDir,n),s=Ce(i);if(s.isFile()&&n.endsWith(".md"))e.push(n.replace(".md",""));else if(s.isDirectory()&&n==="subagents"){let o=ne(i);for(let a of o)a.endsWith(".md")&&e.push(`subagents/${a.replace(".md","")}`)}}}catch{return[]}return e}filterAgents(e){let t=e.filter(n=>(n.includes("/")?n.split("/")[1]:n).startsWith("qe-"));return this.options.include&&this.options.include.length>0&&(t=t.filter(n=>{let i=n.includes("/")?n.split("/")[1]:n;return this.options.include.includes(i)})),this.options.exclude&&this.options.exclude.length>0&&(t=t.filter(n=>{let i=n.includes("/")?n.split("/")[1]:n;return!this.options.exclude.some(s=>i.includes(s)||i.match(new RegExp(s)))})),this.options.installQEAgents||(t=t.filter(n=>{let i=n.includes("/")?n.split("/")[1]:n;return!it.includes(i)})),this.options.installSubagents||(t=t.filter(n=>!n.startsWith("subagents/"))),t}async installAgent(e,t,n){let i=e.startsWith("subagents/"),s=i?e.split("/")[1]:e,o=g(this.sourceAgentsDir,`${e}.md`),a=i?g(n,`${s}.md`):g(t,`${s}.md`);if(f(a)&&!this.options.overwrite)return null;if(f(o))re(o,a);else throw new Error(`Source file not found: ${o}`);return this.describeAgent(e,t,n)}describeAgent(e,t,n){let i=e.startsWith("subagents/"),s=i?e.split("/")[1]:e,o=i?g(n,`${s}.md`):g(t,`${s}.md`);return{name:s,type:this.getAgentType(s,i),description:this.getAgentDescription(o),domain:this.getAgentDomain(s)}}getAgentType(e,t){return t?"v3-subagent":"v3-qe"}copyDirectoryRecursive(e,t){if(!f(e))return;f(t)||E(t,{recursive:!0});let n=ne(e);for(let i of n){let s=g(e,i),o=g(t,i);Ce(s).isDirectory()?this.copyDirectoryRecursive(s,o):(!f(o)||this.options.overwrite)&&re(s,o)}}async copyHelpersDirectory(e){let t=g(this.sourceAgentsDir,"helpers"),n=g(this.projectRoot,".claude","helpers","v3");f(t)?this.copyDirectoryRecursive(t,n):console.error(`[AgentsInstaller] Helpers source not found: ${t}`)}async copyTemplatesDirectory(e){let t=g(this.sourceAgentsDir,"templates"),n=g(e,"templates");f(t)?this.copyDirectoryRecursive(t,n):console.error(`[AgentsInstaller] Templates source not found: ${t}`)}getAgentDescription(e){if(f(e))try{let t=we(e,"utf-8"),n=t.match(/description:\s*["']?([^"'\n]+)["']?/i);if(n)return n[1].trim();let i=t.split(`
62
62
  `);for(let s of i){let o=s.trim();if(o&&!o.startsWith("#")&&!o.startsWith("-")&&!o.startsWith("```")&&!o.startsWith("---"))return o.slice(0,100)+(o.length>100?"...":"")}}catch(t){console.debug("[AgentsInstaller] Failed to read agent description:",t instanceof Error?t.message:t)}}getAgentDomain(e){let t={"test-architect":"test-generation","bdd-generator":"test-generation","property-tester":"test-generation","mutation-tester":"test-generation","parallel-executor":"test-execution","flaky-hunter":"test-execution","retry-handler":"test-execution","coverage-specialist":"coverage-analysis","gap-detector":"coverage-analysis","quality-gate":"quality-assessment","code-complexity":"quality-assessment","deployment-advisor":"quality-assessment","risk-assessor":"quality-assessment","defect-predictor":"defect-intelligence","regression-analyzer":"defect-intelligence","root-cause-analyzer":"defect-intelligence","impact-analyzer":"defect-intelligence","requirements-validator":"requirements-validation","qx-partner":"requirements-validation","product-factors-assessor":"requirements-validation","quality-criteria-recommender":"requirements-validation","test-idea-rewriter":"test-generation","code-intelligence":"code-intelligence","kg-builder":"code-intelligence","dependency-mapper":"code-intelligence","security-scanner":"security-compliance","security-auditor":"security-compliance","pentest-validator":"security-compliance","contract-validator":"contract-testing","graphql-tester":"contract-testing","visual-tester":"visual-accessibility","accessibility-auditor":"visual-accessibility","responsive-tester":"visual-accessibility","chaos-engineer":"chaos-resilience","load-tester":"chaos-resilience","performance-tester":"chaos-resilience","learning-coordinator":"learning-optimization","pattern-learner":"learning-optimization","metrics-optimizer":"learning-optimization","transfer-specialist":"learning-optimization","soap-tester":"enterprise-integration","sap-rfc-tester":"enterprise-integration","sap-idoc-tester":"enterprise-integration","odata-contract-tester":"enterprise-integration","middleware-validator":"enterprise-integration","message-broker-tester":"enterprise-integration","sod-analyzer":"enterprise-integration"},n=e.replace(/^(v3-)?qe-/,"");return t[n]}async createAgentsIndex(e,t){let n=t.filter(c=>c.type==="v3-qe"),i=t.filter(c=>c.type==="v3-subagent"),s=new Map;for(let c of n){let u=c.domain||"general";s.has(u)||s.set(u,[]),s.get(u).push(c)}let o=`# AQE V3 Agents Index
63
63
 
64
64
  This directory contains V3 QE agents installed by \`aqe init\`.
@@ -105,7 +105,7 @@ ${i.map(c=>`- **${c.name}**${c.description?`: ${c.description}`:""}`).join(`
105
105
  ---
106
106
 
107
107
  *Generated by AQE v3 init on ${new Date().toISOString()}*
108
- `,a=g(this.projectRoot,".claude","docs");f(a)||R(a,{recursive:!0}),E(g(a,"v3-agents-index.md"),o,I)}};function Ht(r){return new ne(r)}F();import{existsSync as v,mkdirSync as re,readdirSync as xe,readFileSync as rt,writeFileSync as it,copyFileSync as Ce}from"fs";import{join as h}from"path";var we={core:[{name:"workflow-executor",filename:"n8n-workflow-executor.md",category:"core"},{name:"node-validator",filename:"n8n-node-validator.md",category:"core"},{name:"trigger-test",filename:"n8n-trigger-test.md",category:"core"},{name:"expression-validator",filename:"n8n-expression-validator.md",category:"core"},{name:"integration-test",filename:"n8n-integration-test.md",category:"core"},{name:"security-auditor",filename:"n8n-security-auditor.md",category:"core"}],advanced:[{name:"unit-tester",filename:"n8n-unit-tester.md",category:"advanced"},{name:"performance-tester",filename:"n8n-performance-tester.md",category:"advanced"},{name:"ci-orchestrator",filename:"n8n-ci-orchestrator.md",category:"advanced"}],quality:[{name:"version-comparator",filename:"n8n-version-comparator.md",category:"quality"},{name:"bdd-scenario-tester",filename:"n8n-bdd-scenario-tester.md",category:"quality"},{name:"monitoring-validator",filename:"n8n-monitoring-validator.md",category:"quality"}],enterprise:[{name:"compliance-validator",filename:"n8n-compliance-validator.md",category:"enterprise"},{name:"chaos-tester",filename:"n8n-chaos-tester.md",category:"enterprise"}],reliability:[{name:"base-agent",filename:"n8n-base-agent.md",category:"reliability"}]},st=["n8n-expression-testing","n8n-integration-testing-patterns","n8n-security-testing","n8n-trigger-testing-strategies","n8n-workflow-testing-fundamentals"],ie=class{projectRoot;options;sourceAgentsDir;sourceSkillsDir;constructor(e){this.projectRoot=e.projectRoot,this.options={installAgents:!0,installSkills:!0,overwrite:!1,...e},this.sourceAgentsDir=this.findSourceAgentsDir(),this.sourceSkillsDir=this.findSourceSkillsDir()}findSourceAgentsDir(){let e=b(import.meta.url),t=[];e&&t.push(h(e,".claude/agents/n8n")),t.push(h(this.projectRoot,"node_modules/agentic-qe/.claude/agents/n8n"));for(let n of t)if(v(n))return n;return t[0]}findSourceSkillsDir(){let e=b(import.meta.url),t=[];e&&(t.push(h(e,"assets/skills")),t.push(h(e,".claude/skills"))),t.push(h(this.projectRoot,"node_modules/agentic-qe/assets/skills"));for(let n of t)if(v(n))return n;return t[0]}async install(){let e={success:!0,agentsInstalled:[],skillsInstalled:[],configGenerated:!1,errors:[],agentsDir:h(this.projectRoot,".claude/agents/n8n"),skillsDir:h(this.projectRoot,".claude/skills")};try{if(this.options.installAgents){let t=await this.installAgents(e.agentsDir);e.agentsInstalled=t.installed,e.errors.push(...t.errors)}if(this.options.installSkills){let t=await this.installSkills(e.skillsDir);e.skillsInstalled=t.installed,e.errors.push(...t.errors)}this.options.n8nApiConfig&&(e.configGenerated=!0),e.agentsInstalled.length>0&&this.createAgentsIndex(e.agentsDir,e.agentsInstalled)}catch(t){e.success=!1,e.errors.push(`Installation failed: ${k(t)}`)}return e}async installAgents(e){let t=[],n=[];if(v(e)||re(e,{recursive:!0}),!v(this.sourceAgentsDir))return n.push(`Source agents directory not found: ${this.sourceAgentsDir}`),{installed:t,errors:n};let i=xe(this.sourceAgentsDir).filter(s=>s.endsWith(".md"));for(let s of Object.keys(we))for(let o of we[s]){let a=h(this.sourceAgentsDir,o.filename),c=h(e,o.filename);if(i.includes(o.filename)&&!(v(c)&&!this.options.overwrite))try{Ce(a,c);let l=rt(a,"utf-8").match(/description:\s*["']?(.+?)["']?\n/);o.description=l?.[1]||`n8n ${o.name} agent`,t.push(o)}catch(u){n.push(`Failed to install ${o.name}: ${k(u)}`)}}return{installed:t,errors:n}}async installSkills(e){let t=[],n=[];if(v(e)||re(e,{recursive:!0}),!v(this.sourceSkillsDir))return n.push(`Source skills directory not found: ${this.sourceSkillsDir}`),{installed:t,errors:n};for(let i of st){let s=h(this.sourceSkillsDir,i),o=h(e,i);if(v(s)&&!(v(o)&&!this.options.overwrite))try{this.copyDirectory(s,o),t.push(i)}catch(a){n.push(`Failed to install skill ${i}: ${k(a)}`)}}return{installed:t,errors:n}}copyDirectory(e,t){v(t)||re(t,{recursive:!0});let n=xe(e,{withFileTypes:!0});for(let i of n){let s=h(e,i.name),o=h(t,i.name);i.isDirectory()?this.copyDirectory(s,o):Ce(s,o)}}createAgentsIndex(e,t){let n=h(e,"README.md"),i={core:t.filter(o=>o.category==="core"),advanced:t.filter(o=>o.category==="advanced"),quality:t.filter(o=>o.category==="quality"),enterprise:t.filter(o=>o.category==="enterprise"),reliability:t.filter(o=>o.category==="reliability")},s=`# N8n Testing Agents
108
+ `,a=g(this.projectRoot,".claude","docs");f(a)||E(a,{recursive:!0}),I(g(a,"v3-agents-index.md"),o,_)}};function Xt(r){return new ie(r)}L();import{existsSync as v,mkdirSync as se,readdirSync as De,readFileSync as ot,writeFileSync as at,copyFileSync as Re}from"fs";import{join as h}from"path";var Ee={core:[{name:"workflow-executor",filename:"n8n-workflow-executor.md",category:"core"},{name:"node-validator",filename:"n8n-node-validator.md",category:"core"},{name:"trigger-test",filename:"n8n-trigger-test.md",category:"core"},{name:"expression-validator",filename:"n8n-expression-validator.md",category:"core"},{name:"integration-test",filename:"n8n-integration-test.md",category:"core"},{name:"security-auditor",filename:"n8n-security-auditor.md",category:"core"}],advanced:[{name:"unit-tester",filename:"n8n-unit-tester.md",category:"advanced"},{name:"performance-tester",filename:"n8n-performance-tester.md",category:"advanced"},{name:"ci-orchestrator",filename:"n8n-ci-orchestrator.md",category:"advanced"}],quality:[{name:"version-comparator",filename:"n8n-version-comparator.md",category:"quality"},{name:"bdd-scenario-tester",filename:"n8n-bdd-scenario-tester.md",category:"quality"},{name:"monitoring-validator",filename:"n8n-monitoring-validator.md",category:"quality"}],enterprise:[{name:"compliance-validator",filename:"n8n-compliance-validator.md",category:"enterprise"},{name:"chaos-tester",filename:"n8n-chaos-tester.md",category:"enterprise"}],reliability:[{name:"base-agent",filename:"n8n-base-agent.md",category:"reliability"}]},lt=["n8n-expression-testing","n8n-integration-testing-patterns","n8n-security-testing","n8n-trigger-testing-strategies","n8n-workflow-testing-fundamentals"],oe=class{projectRoot;options;sourceAgentsDir;sourceSkillsDir;constructor(e){this.projectRoot=e.projectRoot,this.options={installAgents:!0,installSkills:!0,overwrite:!1,...e},this.sourceAgentsDir=this.findSourceAgentsDir(),this.sourceSkillsDir=this.findSourceSkillsDir()}findSourceAgentsDir(){let e=b(import.meta.url),t=[];e&&t.push(h(e,".claude/agents/n8n")),t.push(h(this.projectRoot,"node_modules/agentic-qe/.claude/agents/n8n"));for(let n of t)if(v(n))return n;return t[0]}findSourceSkillsDir(){let e=b(import.meta.url),t=[];e&&(t.push(h(e,"assets/skills")),t.push(h(e,".claude/skills"))),t.push(h(this.projectRoot,"node_modules/agentic-qe/assets/skills"));for(let n of t)if(v(n))return n;return t[0]}async install(){let e={success:!0,agentsInstalled:[],skillsInstalled:[],configGenerated:!1,errors:[],agentsDir:h(this.projectRoot,".claude/agents/n8n"),skillsDir:h(this.projectRoot,".claude/skills")};try{if(this.options.installAgents){let t=await this.installAgents(e.agentsDir);e.agentsInstalled=t.installed,e.errors.push(...t.errors)}if(this.options.installSkills){let t=await this.installSkills(e.skillsDir);e.skillsInstalled=t.installed,e.errors.push(...t.errors)}this.options.n8nApiConfig&&(e.configGenerated=!0),e.agentsInstalled.length>0&&this.createAgentsIndex(e.agentsDir,e.agentsInstalled)}catch(t){e.success=!1,e.errors.push(`Installation failed: ${k(t)}`)}return e}async installAgents(e){let t=[],n=[];if(v(e)||se(e,{recursive:!0}),!v(this.sourceAgentsDir))return n.push(`Source agents directory not found: ${this.sourceAgentsDir}`),{installed:t,errors:n};let i=De(this.sourceAgentsDir).filter(s=>s.endsWith(".md"));for(let s of Object.keys(Ee))for(let o of Ee[s]){let a=h(this.sourceAgentsDir,o.filename),c=h(e,o.filename);if(i.includes(o.filename)&&!(v(c)&&!this.options.overwrite))try{Re(a,c);let l=ot(a,"utf-8").match(/description:\s*["']?(.+?)["']?\n/);o.description=l?.[1]||`n8n ${o.name} agent`,t.push(o)}catch(u){n.push(`Failed to install ${o.name}: ${k(u)}`)}}return{installed:t,errors:n}}async installSkills(e){let t=[],n=[];if(v(e)||se(e,{recursive:!0}),!v(this.sourceSkillsDir))return n.push(`Source skills directory not found: ${this.sourceSkillsDir}`),{installed:t,errors:n};for(let i of lt){let s=h(this.sourceSkillsDir,i),o=h(e,i);if(v(s)&&!(v(o)&&!this.options.overwrite))try{this.copyDirectory(s,o),t.push(i)}catch(a){n.push(`Failed to install skill ${i}: ${k(a)}`)}}return{installed:t,errors:n}}copyDirectory(e,t){v(t)||se(t,{recursive:!0});let n=De(e,{withFileTypes:!0});for(let i of n){let s=h(e,i.name),o=h(t,i.name);i.isDirectory()?this.copyDirectory(s,o):Re(s,o)}}createAgentsIndex(e,t){let n=h(e,"README.md"),i={core:t.filter(o=>o.category==="core"),advanced:t.filter(o=>o.category==="advanced"),quality:t.filter(o=>o.category==="quality"),enterprise:t.filter(o=>o.category==="enterprise"),reliability:t.filter(o=>o.category==="reliability")},s=`# N8n Testing Agents
109
109
 
110
110
  > Auto-generated by \`aqe init --with-n8n\`
111
111
 
@@ -138,7 +138,7 @@ Task("Run security audit on workflow", "n8n-security-auditor")
138
138
  `;s+=`
139
139
  `}s+=`---
140
140
  Generated: ${new Date().toISOString()}
141
- `,it(n,s)}generateConfigSection(){return{n8n:{enabled:!0,installAgents:this.options.installAgents,installSkills:this.options.installSkills,apiConfig:this.options.n8nApiConfig||null}}}generateClaudeMdSection(){return`
141
+ `,at(n,s)}generateConfigSection(){return{n8n:{enabled:!0,installAgents:this.options.installAgents,installSkills:this.options.installSkills,apiConfig:this.options.n8nApiConfig||null}}}generateClaudeMdSection(){return`
142
142
  ## N8n Workflow Testing
143
143
 
144
144
  This project includes n8n workflow testing agents. Use them with Claude Code:
@@ -177,4 +177,4 @@ N8n agents map to v3 domains:
177
177
  - Compliance agents \u2192 security-compliance domain
178
178
  - Chaos agents \u2192 chaos-resilience domain
179
179
 
180
- `}};function en(r){return new ie(r)}export{B as a,lt as b,pt as c,yt as d,bt as e,$e as f,At as g,St as h,xt as i,Ct as j,wt as k,_t as l,qt as m,$t as n,Ht as o,en as p};
180
+ `}};function sn(r){return new oe(r)}export{U as a,gt as b,yt as c,kt as d,xt as e,Me as f,Ct as g,wt as h,Dt as i,Ve as j,Rt as k,Et as l,jt as m,Nt as n,Ot as o,Gt as p,Xt as q,sn as r};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.14");process.exit(0)}
2
- import{a as b}from"./chunk-YKQWIXUY.js";import{c as g}from"./chunk-C3OIBFAA.js";import{C as B,S as v,b as p}from"./chunk-E7OR6V3V.js";import{a as I}from"./chunk-V6SE2ZU2.js";b();v();b();v();import{createHash as ue,randomUUID as me}from"crypto";b();function Z(o){let e=2166136261;for(let t=0;t<o.length;t++)e^=o.charCodeAt(t),e=Math.imul(e,16777619);return(e>>>0)%64}function W(o){let e=new Array(64).fill(0),t=o.toLowerCase().split(/[\s,;:.!?()[\]{}"']+/).filter(n=>n.length>0);for(let n of t){let s=Z(n);e[s]++}let r=0;for(let n=0;n<64;n++)r+=e[n]*e[n];if(r=Math.sqrt(r),r>1e-10)for(let n=0;n<64;n++)e[n]/=r;return e}function _(o,e){let t=0,r=0,n=0,s=Math.min(o.length,e.length);for(let a=0;a<s;a++)t+=o[a]*e[a],r+=o[a]*o[a],n+=e[a]*e[a];let i=Math.sqrt(r)*Math.sqrt(n);return i>1e-10?t/i:0}b();import{createRequire as ee}from"module";var S=ee(import.meta.url),V=g.create("coherence-gate-cohomology"),C=null,k=!1;function H(){if(k)return C;k=!0;try{let o=S("prime-radiant-advanced-wasm"),e=S("fs"),t=S("path"),r=t.join(t.dirname(I.resolve("prime-radiant-advanced-wasm")),"prime_radiant_advanced_wasm_bg.wasm");o.initSync({module:e.readFileSync(r)}),C=new o.CohomologyEngine,V.info("CohomologyEngine loaded from prime-radiant-advanced-wasm")}catch(o){V.debug("CohomologyEngine unavailable, using word-frequency fallback",{error:String(o)}),C=null}return C}var te={threshold:5,slack:.5,resetOnAlarm:!0,warmupSamples:20},d=class{config;states=new Map;constructor(e={}){this.config={...te,...e}}update(e,t){let r=this.getOrCreateState(e);if(r.samplesSinceReset++,r.mu===null)return r.warmupSum+=t,r.warmupCount++,r.warmupCount>=this.config.warmupSamples&&(r.mu=r.warmupSum/r.warmupCount),{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:r.samplesSinceReset};r.sPlus=Math.max(0,r.sPlus+(t-r.mu-this.config.slack)),r.sMinus=Math.max(0,r.sMinus+(-t+r.mu-this.config.slack));let n=Math.max(r.sPlus,r.sMinus),s=!1,i="none";r.sPlus>this.config.threshold?(s=!0,i="positive"):r.sMinus>this.config.threshold&&(s=!0,i="negative");let a={driftDetected:s,cumulativeSum:n,direction:i,samplesSinceReset:r.samplesSinceReset};return s&&this.config.resetOnAlarm&&(r.sPlus=0,r.sMinus=0,r.samplesSinceReset=0),a}reset(e){e?this.states.delete(e):this.states.clear()}getState(e){let t=this.states.get(e);if(!t)return{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:0};let r=Math.max(t.sPlus,t.sMinus),n="none";return t.sPlus>this.config.threshold?n="positive":t.sMinus>this.config.threshold&&(n="negative"),{driftDetected:t.sPlus>this.config.threshold||t.sMinus>this.config.threshold,cumulativeSum:r,direction:n,samplesSinceReset:t.samplesSinceReset}}getOrCreateState(e){let t=this.states.get(e);return t||(t={sPlus:0,sMinus:0,samplesSinceReset:0,warmupSum:0,warmupCount:0,mu:null},this.states.set(e,t)),t}};v();var x=g.create("coherence-gate-energy"),D=null,re=[],P=[],ne=100;function oe(){return D||(B()?(D=new d,x.debug("CUSUM drift detector auto-created via feature flag"),D):null)}function O(o,e){let t=oe();if(!t)return;let r=t.update(o,e);if(r.driftDetected){let n={gateType:o,energy:e,cusumResult:r,timestamp:Date.now()};x.warn("CUSUM drift detected",{gateType:o,energy:e,direction:r.direction,cumulativeSum:r.cumulativeSum}),P.push(n),P.length>ne&&P.shift();for(let s of re)try{s(n)}catch(i){x.debug("Drift listener error",{error:String(i)})}}}var f={assertionCoverage:.4,codeCoverage:.3,confidencePenalty:.3,contradictionWeight:.2,laplacianWeight:.15},N=1;function U(o){if(o.assertions.length===0)return 0;let e=o.observedBehavior.length/o.assertions.length;return Math.max(0,Math.min(1-e,1))}function $(o){return Math.max(0,Math.min(1-o.coverage,1))}function j(o){return Math.max(0,Math.min(1-o.confidence,1))}function se(o){if(o.assertions.length===0||o.observedBehavior.length===0)return 0;let e=0,t=["not","never","false","undefined","null","error","fail"];for(let r of o.assertions){let n=r.toLowerCase();for(let s of o.observedBehavior){let i=s.toLowerCase();for(let a of t){let c=n.includes(a),u=i.includes(a);if(c!==u){let m=new Set(n.split(/\s+/)),l=new Set(i.split(/\s+/)),h=0;for(let L of m)l.has(L)&&L.length>3&&h++;if(h>0){e++;break}}}}}return Math.min(e/o.assertions.length,1)}function ie(o,e,t){let r=t[0]?.length??64,n=t.map((c,u)=>({id:u,label:e.assertions[u]?.slice(0,50)??`assertion-${u}`,section:c,weight:e.confidence})),s=[];for(let c=0;c<t.length;c++)for(let u=c+1;u<t.length;u++){let m=[];for(let l=0;l<r;l++)for(let h=0;h<r;h++)m.push(l===h?1:0);s.push({source:c,target:u,weight:1,restriction_map:m,source_dim:r,target_dim:r})}let i=o.consistencyEnergy({nodes:n,edges:s}),a=i/(i+1);return Math.max(0,Math.min(a,1))}function ae(o){let e=0,t=0;for(let n=0;n<o.length;n++)for(let s=n+1;s<o.length;s++)e+=_(o[n],o[s]),t++;if(t===0)return 0;let r=e/t;return Math.max(0,Math.min(1-r,1))}function ce(o){if(o.assertions.length<2)return 0;let e=o.assertions.map(r=>W(r)),t=H();if(t)try{return ie(t,o,e)}catch(r){x.debug("CohomologyEngine.consistencyEnergy failed, using fallback",{error:String(r)})}return ae(e)}function K(o,e="act"){let t=U(o),r=$(o),n=j(o),s=Math.min(t*f.assertionCoverage+r*f.codeCoverage+n*f.confidencePenalty,1);return O(e,s),{energy:s,components:{assertionCoverage:t,codeCoverage:r,confidencePenalty:n,contradictionScore:0,laplacianDeviation:0}}}function q(o,e="retrieve"){let t=U(o),r=$(o),n=j(o),s=se(o),i=ce(o),a=t*f.assertionCoverage+r*f.codeCoverage+n*f.confidencePenalty,c=s*f.contradictionWeight+i*f.laplacianWeight,u=f.assertionCoverage+f.codeCoverage+f.confidencePenalty+f.contradictionWeight+f.laplacianWeight,m=Math.min((a+c)/u,1);return O(e,m),{energy:m,components:{assertionCoverage:t,codeCoverage:r,confidencePenalty:n,contradictionScore:s,laplacianDeviation:i}}}var z=g.create("coherence-gate"),le=.4,T=class{threshold;decisionLog=[];witnessChain=[];lastWitnessHash="0".repeat(64);nativeAvailable=null;governanceChain=null;constructor(e=le){this.threshold=e}setGovernanceChain(e){this.governanceChain=e}computeEnergy(e,t=!1,r="retrieve"){let n=performance.now();if(!t){let a=K(e,r),c=performance.now()-n;if(c<=N)return{energy:a.energy,tier:"reflex",components:a.components,latencyMs:c}}let s=q(e,r),i=performance.now()-n;return{energy:s.energy,tier:"retrieval",components:s.components,latencyMs:i}}validate(e,t,r="retrieve"){let n=t??this.threshold,s=this.computeEnergy(e,!1,r),i=s.energy<=n,a;i||(a=this.buildFailureReason(s,n));let c=this.createWitnessRecord(e,s.energy,n,i);return this.logDecision({id:c.id,timestamp:c.timestamp,domain:e.domain,energy:s.energy,tier:s.tier,passed:i,threshold:n}),{passed:i,energy:s.energy,threshold:n,reason:a,witness:c}}getDecisionLog(){return[...this.decisionLog]}getWitnessChain(){return[...this.witnessChain]}getThreshold(){return this.threshold}clearDecisionLog(){this.decisionLog=[]}validateTransfer(e,t){if(!p().useCoherenceGate)return{approved:!0};let n={assertions:this.extractAssertions(e),observedBehavior:this.extractObservedBehavior(e),coverage:typeof e.coverage=="number"?e.coverage:.5,domain:t,confidence:e.confidence??.5},s=this.validate(n,void 0,"write");return{approved:s.passed,energy:s.energy,rejectionReason:s.reason}}buildFailureReason(e,t){let r=[];r.push(`Coherence energy ${e.energy.toFixed(3)} exceeds threshold ${t.toFixed(3)}.`);let n=e.components;return n.assertionCoverage>.5&&r.push("High assertion-observation mismatch (possible hallucination)."),n.codeCoverage>.5&&r.push("Low code coverage."),n.confidencePenalty>.5&&r.push("Low generator confidence."),n.contradictionScore>.3&&r.push("Contradictions detected between assertions and observed behavior."),n.laplacianDeviation>.5&&r.push("Inconsistent assertion structure (high Laplacian deviation)."),r.join(" ")}createWitnessRecord(e,t,r,n){let s=me(),i=Date.now(),a=this.hashContent(JSON.stringify(e)),c={id:s,timestamp:i,artifactHash:a,energy:t,threshold:r,passed:n,previousHash:this.lastWitnessHash,recordHash:""},u=`${s}|${i}|${a}|${t}|${r}|${n}|${this.lastWitnessHash}`;if(c.recordHash=this.hashContent(u),p().useWitnessChain&&(this.witnessChain.push(c),this.lastWitnessHash=c.recordHash,this.governanceChain))try{let l={type:"coherence-gate",decision:n?"PASS":"FAIL",context:{energy:t,threshold:r,artifactHash:c.artifactHash}};this.governanceChain.appendWitness(l)}catch(l){z.debug("Failed to persist to governance chain",{error:String(l)})}return c}hashContent(e){return ue("sha256").update(e).digest("hex")}logDecision(e){this.decisionLog.push(e);let t=1e3;this.decisionLog.length>t&&(this.decisionLog=this.decisionLog.slice(-t)),z.debug("Coherence decision",{domain:e.domain,energy:e.energy,tier:e.tier,passed:e.passed})}extractAssertions(e){return Array.isArray(e.assertions)?e.assertions.map(String):typeof e.description=="string"?[e.description]:["transfer-pattern"]}extractObservedBehavior(e){return Array.isArray(e.observedBehavior)?e.observedBehavior.map(String):typeof e.evidence=="string"?[e.evidence]:["observed"]}};var R=class{validateTransfer(e,t){return{approved:!0}}};function X(){return p().useCoherenceGate?new T:new R}b();var Y=g.create("transfer-verification"),fe={maxSourceRegression:.05,minTargetImprovement:0,maxSourceConfidenceRegression:.1},w=class{config;constructor(e={}){this.config={...fe,...e}}verifyTransfer(e){let t=e.sourcePerformanceAfter.successRate-e.sourcePerformanceBefore.successRate,r=e.targetPerformanceAfter.successRate-e.targetPerformanceBefore.successRate,n=e.sourcePerformanceAfter.avgConfidence-e.sourcePerformanceBefore.avgConfidence,s=e.targetPerformanceAfter.avgConfidence-e.targetPerformanceBefore.avgConfidence,i=t>=-this.config.maxSourceRegression&&n>=-this.config.maxSourceConfidenceRegression,a=r>=this.config.minTargetImprovement,c=i&&a,u;if(!c){let m=[];i||m.push(`source domain regressed: successRate delta=${t.toFixed(4)}, confidence delta=${n.toFixed(4)}`),a||m.push(`target domain did not improve: successRate delta=${r.toFixed(4)}`),u=m.join("; ")}return c?Y.debug("Transfer verification passed",{transferId:e.transferId,sourceDelta:t,targetDelta:r}):Y.warn("Transfer verification failed",{transferId:e.transferId,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourceDelta:t,targetDelta:r,failureReason:u}),{passed:c,sourceStable:i,targetImproved:a,sourceDelta:t,targetDelta:r,sourceConfidenceDelta:n,targetConfidenceDelta:s,failureReason:u}}getConfig(){return{...this.config}}};function J(o){return new w(o)}v();var y=class{alphas=new Map;betas=new Map;sample(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return this.sampleBeta(t,r)}update(e,t){t?this.alphas.set(e,(this.alphas.get(e)??1)+1):this.betas.set(e,(this.betas.get(e)??1)+1)}getMean(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t/(t+r)}getObservationCount(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t-1+(r-1)}getAlpha(e){return this.alphas.get(e)??1}getBeta(e){return this.betas.get(e)??1}sampleBeta(e,t){let r=this.sampleGamma(e),n=this.sampleGamma(t);return r+n===0?.5:r/(r+n)}sampleGamma(e){if(e<1){let n=Math.random();return this.sampleGamma(e+1)*Math.pow(n,1/e)}let t=e-1/3,r=1/Math.sqrt(9*t);for(;;){let n,s;do n=this.standardNormal(),s=1+r*n;while(s<=0);s=s*s*s;let i=Math.random();if(i<1-.0331*n*n*n*n||Math.log(i)<.5*n*n+t*(1-s+Math.log(s)))return t*s}}standardNormal(){let e=Math.random(),t=Math.random();return Math.sqrt(-2*Math.log(e||1e-10))*Math.cos(2*Math.PI*t)}};var Q=g.create("domain-transfer"),ge={minTransferProbability:.3,explorationWarmup:5,verification:{},maxHistorySize:1e3,useMetaLearningEnhancements:!0},M=class{constructor(e=100){this.decayThreshold=e}decayThreshold;getDecayMultiplier(e){return e<=0?1:Math.pow(.5,e/this.decayThreshold)}applyDecay(e,t,r){return t+(e-t)*this.getDecayMultiplier(r)}},E=class{cusum;outcomes=[];windowSize;constructor(e=20){this.windowSize=e,this.cusum=new d({threshold:3,slack:.1,resetOnAlarm:!1,warmupSamples:Math.min(10,Math.floor(e/2))})}record(e){this.outcomes.push(e),this.outcomes.length>this.windowSize*2&&this.outcomes.splice(0,this.outcomes.length-this.windowSize*2);let t=this.getCurrentRate();this.cusum.update("learn",t)}isPlateaued(){return this.outcomes.length<this.windowSize?!1:!this.cusum.getState("learn").driftDetected}getCurrentRate(){if(this.outcomes.length===0)return 0;let e=this.outcomes.slice(-this.windowSize);return e.filter(Boolean).length/e.length}getOutcomeCount(){return this.outcomes.length}getCusumState(){return this.cusum.getState("learn")}},A=class{front=[];dominates(e,t){let r=e.successRate>=t.successRate&&e.speed>=t.speed&&e.confidence>=t.confidence,n=e.successRate>t.successRate||e.speed>t.speed||e.confidence>t.confidence;return r&&n}add(e){for(let t=this.front.length-1;t>=0;t--)this.dominates(e,this.front[t])&&this.front.splice(t,1);this.front.some(t=>this.dominates(t,e))||this.front.push(e)}getFront(){return[...this.front]}isNonDominated(e){return!this.front.some(t=>this.dominates(t,e))}},F=class{constructor(e=.2){this.bonusScale=e}bonusScale;triedPairs=new Set;markTried(e){this.triedPairs.add(e)}isTried(e){return this.triedPairs.has(e)}getBonus(e){return this.triedPairs.has(e)?0:this.bonusScale}apply(e,t){return Math.min(1,e+this.getBonus(t))}getTriedCount(){return this.triedPairs.size}},G=class{config;sampler;verifier;coherenceGate;transferHistory=[];affinityScores=new Map;performanceProvider=null;transferExecutor=null;nativeModule=null;decayingBeta;plateauDetector;paretoFront;curiosityBonus;constructor(e={}){this.config={...ge,...e},this.sampler=new y,this.verifier=J(this.config.verification),this.coherenceGate=X(),this.decayingBeta=new M,this.plateauDetector=new E,this.paretoFront=new A,this.curiosityBonus=new F,this.tryLoadNativeModule()}evaluateTransfer(e,t){if(!this.isEnabled())return this.createRejectedCandidate(e,t);let r=this.makePairKey(e,t),n=this.sampler.sample(r),i=this.sampler.getObservationCount(r)<this.config.explorationWarmup,a=this.getAffinityScore(e,t);if(this.isMetaLearningEnabled()){let c=this.sampler.getMean(r),u=this.sampler.getAlpha(r)-1;n=this.decayingBeta.applyDecay(n,c,u),n=this.curiosityBonus.apply(n,r)}return{sourceDomain:e,targetDomain:t,sampledProbability:n,affinityScore:a,isExploration:i,pairKey:r}}executeTransfer(e){let t=`transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=this.coherenceGate.validateTransfer({domain:e.sourceDomain},e.targetDomain);if(!r.approved)return Q.info("Transfer blocked by coherence gate",{transferId:t,source:e.sourceDomain,target:e.targetDomain,reason:r.rejectionReason}),this.createBlockedResult(t,e,r);let n=this.getPerformanceSnapshot(e.sourceDomain),s=this.getPerformanceSnapshot(e.targetDomain),i=this.computeSqrtDampening(e),a=this.doTransfer(e.sourceDomain,e.targetDomain,i),c=this.getPerformanceSnapshot(e.sourceDomain),u=this.getPerformanceSnapshot(e.targetDomain),m=this.verifier.verifyTransfer({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourcePerformanceBefore:n,sourcePerformanceAfter:c,targetPerformanceBefore:s,targetPerformanceAfter:u}),l=a&&m.passed;if(this.sampler.update(e.pairKey,l),this.updateAffinityScore(e.pairKey,l),this.isMetaLearningEnabled()){this.plateauDetector.record(l),this.curiosityBonus.markTried(e.pairKey);let h=this.sampler.getMean(e.pairKey);this.paretoFront.add({pairKey:e.pairKey,successRate:h,speed:1/(1+i),confidence:this.getAffinityScore(e.sourceDomain,e.targetDomain)})}return this.addToHistory({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,success:l,sampledProbability:e.sampledProbability,dampeningFactor:i,sourceDelta:m.sourceDelta,targetDelta:m.targetDelta,timestamp:Date.now()}),Q.info("Transfer completed",{transferId:t,source:e.sourceDomain,target:e.targetDomain,success:l,dampeningFactor:i.toFixed(4),sourceDelta:m.sourceDelta.toFixed(4),targetDelta:m.targetDelta.toFixed(4)}),{transferId:t,candidate:e,success:l,dampeningFactor:i,verification:m,coherenceResult:r,sourcePerformanceBefore:n,sourcePerformanceAfter:c,targetPerformanceBefore:s,targetPerformanceAfter:u,timestamp:Date.now()}}getAffinityScore(e,t){return this.affinityScores.get(this.makePairKey(e,t))??.5}getTransferHistory(){return[...this.transferHistory]}getExpectedSuccessRate(e,t){return this.sampler.getMean(this.makePairKey(e,t))}getObservationCount(e,t){return this.sampler.getObservationCount(this.makePairKey(e,t))}setPerformanceProvider(e){this.performanceProvider=e}setTransferExecutor(e){this.transferExecutor=e}getSampler(){return this.sampler}getCoherenceGate(){return this.coherenceGate}getDecayingBeta(){return this.decayingBeta}getPlateauDetector(){return this.plateauDetector}getParetoFront(){return this.paretoFront}getCuriosityBonus(){return this.curiosityBonus}isLearningPlateaued(){return this.plateauDetector.isPlateaued()}isEnabled(){return p().useCrossDomainTransfer===!0}isMetaLearningEnabled(){return this.config.useMetaLearningEnhancements===!0&&p().useMetaLearningEnhancements!==!1}makePairKey(e,t){return`${e}->${t}`}computeSqrtDampening(e){let t=this.sampler.getObservationCount(e.pairKey);return Math.sqrt(t/(t+this.config.explorationWarmup))}doTransfer(e,t,r){return this.transferExecutor?this.transferExecutor(e,t,r):!0}getPerformanceSnapshot(e){return this.performanceProvider?this.performanceProvider(e):{domain:e,successRate:.5,avgConfidence:.5,patternCount:0,timestamp:Date.now()}}updateAffinityScore(e,t){let r=this.affinityScores.get(e)??.5;this.affinityScores.set(e,.2*(t?1:0)+.8*r)}addToHistory(e){for(this.transferHistory.push(e);this.transferHistory.length>this.config.maxHistorySize;)this.transferHistory.shift()}createBlockedResult(e,t,r){let n={domain:"",successRate:0,avgConfidence:0,patternCount:0,timestamp:Date.now()};return{transferId:e,candidate:t,success:!1,dampeningFactor:0,verification:{passed:!1,sourceStable:!1,targetImproved:!1,sourceDelta:0,targetDelta:0,sourceConfidenceDelta:0,targetConfidenceDelta:0,failureReason:`Coherence gate rejected: ${r.rejectionReason??"unknown"}`},coherenceResult:r,sourcePerformanceBefore:{...n,domain:t.sourceDomain},sourcePerformanceAfter:{...n,domain:t.sourceDomain},targetPerformanceBefore:{...n,domain:t.targetDomain},targetPerformanceAfter:{...n,domain:t.targetDomain},timestamp:Date.now()}}createRejectedCandidate(e,t){return{sourceDomain:e,targetDomain:t,sampledProbability:0,affinityScore:0,isExploration:!1,pairKey:this.makePairKey(e,t)}}tryLoadNativeModule(){this.nativeModule=null}};function $e(o){return new G(o)}export{d as a,y as b,ge as c,M as d,E as e,A as f,F as g,G as h,$e 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.15.16");process.exit(0)}
2
+ import{a as b}from"./chunk-YAPLJR7K.js";import{c as g}from"./chunk-G5RHFBAY.js";import{C as B,S as v,b as p}from"./chunk-L6QSTQME.js";import{a as I}from"./chunk-AJMJNQMP.js";b();v();b();v();import{createHash as ue,randomUUID as me}from"crypto";b();function Z(o){let e=2166136261;for(let t=0;t<o.length;t++)e^=o.charCodeAt(t),e=Math.imul(e,16777619);return(e>>>0)%64}function W(o){let e=new Array(64).fill(0),t=o.toLowerCase().split(/[\s,;:.!?()[\]{}"']+/).filter(n=>n.length>0);for(let n of t){let s=Z(n);e[s]++}let r=0;for(let n=0;n<64;n++)r+=e[n]*e[n];if(r=Math.sqrt(r),r>1e-10)for(let n=0;n<64;n++)e[n]/=r;return e}function _(o,e){let t=0,r=0,n=0,s=Math.min(o.length,e.length);for(let a=0;a<s;a++)t+=o[a]*e[a],r+=o[a]*o[a],n+=e[a]*e[a];let i=Math.sqrt(r)*Math.sqrt(n);return i>1e-10?t/i:0}b();import{createRequire as ee}from"module";var S=ee(import.meta.url),V=g.create("coherence-gate-cohomology"),C=null,k=!1;function H(){if(k)return C;k=!0;try{let o=S("prime-radiant-advanced-wasm"),e=S("fs"),t=S("path"),r=t.join(t.dirname(I.resolve("prime-radiant-advanced-wasm")),"prime_radiant_advanced_wasm_bg.wasm");o.initSync({module:e.readFileSync(r)}),C=new o.CohomologyEngine,V.info("CohomologyEngine loaded from prime-radiant-advanced-wasm")}catch(o){V.debug("CohomologyEngine unavailable, using word-frequency fallback",{error:String(o)}),C=null}return C}var te={threshold:5,slack:.5,resetOnAlarm:!0,warmupSamples:20},d=class{config;states=new Map;constructor(e={}){this.config={...te,...e}}update(e,t){let r=this.getOrCreateState(e);if(r.samplesSinceReset++,r.mu===null)return r.warmupSum+=t,r.warmupCount++,r.warmupCount>=this.config.warmupSamples&&(r.mu=r.warmupSum/r.warmupCount),{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:r.samplesSinceReset};r.sPlus=Math.max(0,r.sPlus+(t-r.mu-this.config.slack)),r.sMinus=Math.max(0,r.sMinus+(-t+r.mu-this.config.slack));let n=Math.max(r.sPlus,r.sMinus),s=!1,i="none";r.sPlus>this.config.threshold?(s=!0,i="positive"):r.sMinus>this.config.threshold&&(s=!0,i="negative");let a={driftDetected:s,cumulativeSum:n,direction:i,samplesSinceReset:r.samplesSinceReset};return s&&this.config.resetOnAlarm&&(r.sPlus=0,r.sMinus=0,r.samplesSinceReset=0),a}reset(e){e?this.states.delete(e):this.states.clear()}getState(e){let t=this.states.get(e);if(!t)return{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:0};let r=Math.max(t.sPlus,t.sMinus),n="none";return t.sPlus>this.config.threshold?n="positive":t.sMinus>this.config.threshold&&(n="negative"),{driftDetected:t.sPlus>this.config.threshold||t.sMinus>this.config.threshold,cumulativeSum:r,direction:n,samplesSinceReset:t.samplesSinceReset}}getOrCreateState(e){let t=this.states.get(e);return t||(t={sPlus:0,sMinus:0,samplesSinceReset:0,warmupSum:0,warmupCount:0,mu:null},this.states.set(e,t)),t}};v();var x=g.create("coherence-gate-energy"),D=null,re=[],P=[],ne=100;function oe(){return D||(B()?(D=new d,x.debug("CUSUM drift detector auto-created via feature flag"),D):null)}function O(o,e){let t=oe();if(!t)return;let r=t.update(o,e);if(r.driftDetected){let n={gateType:o,energy:e,cusumResult:r,timestamp:Date.now()};x.warn("CUSUM drift detected",{gateType:o,energy:e,direction:r.direction,cumulativeSum:r.cumulativeSum}),P.push(n),P.length>ne&&P.shift();for(let s of re)try{s(n)}catch(i){x.debug("Drift listener error",{error:String(i)})}}}var f={assertionCoverage:.4,codeCoverage:.3,confidencePenalty:.3,contradictionWeight:.2,laplacianWeight:.15},N=1;function U(o){if(o.assertions.length===0)return 0;let e=o.observedBehavior.length/o.assertions.length;return Math.max(0,Math.min(1-e,1))}function $(o){return Math.max(0,Math.min(1-o.coverage,1))}function j(o){return Math.max(0,Math.min(1-o.confidence,1))}function se(o){if(o.assertions.length===0||o.observedBehavior.length===0)return 0;let e=0,t=["not","never","false","undefined","null","error","fail"];for(let r of o.assertions){let n=r.toLowerCase();for(let s of o.observedBehavior){let i=s.toLowerCase();for(let a of t){let c=n.includes(a),u=i.includes(a);if(c!==u){let m=new Set(n.split(/\s+/)),l=new Set(i.split(/\s+/)),h=0;for(let L of m)l.has(L)&&L.length>3&&h++;if(h>0){e++;break}}}}}return Math.min(e/o.assertions.length,1)}function ie(o,e,t){let r=t[0]?.length??64,n=t.map((c,u)=>({id:u,label:e.assertions[u]?.slice(0,50)??`assertion-${u}`,section:c,weight:e.confidence})),s=[];for(let c=0;c<t.length;c++)for(let u=c+1;u<t.length;u++){let m=[];for(let l=0;l<r;l++)for(let h=0;h<r;h++)m.push(l===h?1:0);s.push({source:c,target:u,weight:1,restriction_map:m,source_dim:r,target_dim:r})}let i=o.consistencyEnergy({nodes:n,edges:s}),a=i/(i+1);return Math.max(0,Math.min(a,1))}function ae(o){let e=0,t=0;for(let n=0;n<o.length;n++)for(let s=n+1;s<o.length;s++)e+=_(o[n],o[s]),t++;if(t===0)return 0;let r=e/t;return Math.max(0,Math.min(1-r,1))}function ce(o){if(o.assertions.length<2)return 0;let e=o.assertions.map(r=>W(r)),t=H();if(t)try{return ie(t,o,e)}catch(r){x.debug("CohomologyEngine.consistencyEnergy failed, using fallback",{error:String(r)})}return ae(e)}function K(o,e="act"){let t=U(o),r=$(o),n=j(o),s=Math.min(t*f.assertionCoverage+r*f.codeCoverage+n*f.confidencePenalty,1);return O(e,s),{energy:s,components:{assertionCoverage:t,codeCoverage:r,confidencePenalty:n,contradictionScore:0,laplacianDeviation:0}}}function q(o,e="retrieve"){let t=U(o),r=$(o),n=j(o),s=se(o),i=ce(o),a=t*f.assertionCoverage+r*f.codeCoverage+n*f.confidencePenalty,c=s*f.contradictionWeight+i*f.laplacianWeight,u=f.assertionCoverage+f.codeCoverage+f.confidencePenalty+f.contradictionWeight+f.laplacianWeight,m=Math.min((a+c)/u,1);return O(e,m),{energy:m,components:{assertionCoverage:t,codeCoverage:r,confidencePenalty:n,contradictionScore:s,laplacianDeviation:i}}}var z=g.create("coherence-gate"),le=.4,T=class{threshold;decisionLog=[];witnessChain=[];lastWitnessHash="0".repeat(64);nativeAvailable=null;governanceChain=null;constructor(e=le){this.threshold=e}setGovernanceChain(e){this.governanceChain=e}computeEnergy(e,t=!1,r="retrieve"){let n=performance.now();if(!t){let a=K(e,r),c=performance.now()-n;if(c<=N)return{energy:a.energy,tier:"reflex",components:a.components,latencyMs:c}}let s=q(e,r),i=performance.now()-n;return{energy:s.energy,tier:"retrieval",components:s.components,latencyMs:i}}validate(e,t,r="retrieve"){let n=t??this.threshold,s=this.computeEnergy(e,!1,r),i=s.energy<=n,a;i||(a=this.buildFailureReason(s,n));let c=this.createWitnessRecord(e,s.energy,n,i);return this.logDecision({id:c.id,timestamp:c.timestamp,domain:e.domain,energy:s.energy,tier:s.tier,passed:i,threshold:n}),{passed:i,energy:s.energy,threshold:n,reason:a,witness:c}}getDecisionLog(){return[...this.decisionLog]}getWitnessChain(){return[...this.witnessChain]}getThreshold(){return this.threshold}clearDecisionLog(){this.decisionLog=[]}validateTransfer(e,t){if(!p().useCoherenceGate)return{approved:!0};let n={assertions:this.extractAssertions(e),observedBehavior:this.extractObservedBehavior(e),coverage:typeof e.coverage=="number"?e.coverage:.5,domain:t,confidence:e.confidence??.5},s=this.validate(n,void 0,"write");return{approved:s.passed,energy:s.energy,rejectionReason:s.reason}}buildFailureReason(e,t){let r=[];r.push(`Coherence energy ${e.energy.toFixed(3)} exceeds threshold ${t.toFixed(3)}.`);let n=e.components;return n.assertionCoverage>.5&&r.push("High assertion-observation mismatch (possible hallucination)."),n.codeCoverage>.5&&r.push("Low code coverage."),n.confidencePenalty>.5&&r.push("Low generator confidence."),n.contradictionScore>.3&&r.push("Contradictions detected between assertions and observed behavior."),n.laplacianDeviation>.5&&r.push("Inconsistent assertion structure (high Laplacian deviation)."),r.join(" ")}createWitnessRecord(e,t,r,n){let s=me(),i=Date.now(),a=this.hashContent(JSON.stringify(e)),c={id:s,timestamp:i,artifactHash:a,energy:t,threshold:r,passed:n,previousHash:this.lastWitnessHash,recordHash:""},u=`${s}|${i}|${a}|${t}|${r}|${n}|${this.lastWitnessHash}`;if(c.recordHash=this.hashContent(u),p().useWitnessChain&&(this.witnessChain.push(c),this.lastWitnessHash=c.recordHash,this.governanceChain))try{let l={type:"coherence-gate",decision:n?"PASS":"FAIL",context:{energy:t,threshold:r,artifactHash:c.artifactHash}};this.governanceChain.appendWitness(l)}catch(l){z.debug("Failed to persist to governance chain",{error:String(l)})}return c}hashContent(e){return ue("sha256").update(e).digest("hex")}logDecision(e){this.decisionLog.push(e);let t=1e3;this.decisionLog.length>t&&(this.decisionLog=this.decisionLog.slice(-t)),z.debug("Coherence decision",{domain:e.domain,energy:e.energy,tier:e.tier,passed:e.passed})}extractAssertions(e){return Array.isArray(e.assertions)?e.assertions.map(String):typeof e.description=="string"?[e.description]:["transfer-pattern"]}extractObservedBehavior(e){return Array.isArray(e.observedBehavior)?e.observedBehavior.map(String):typeof e.evidence=="string"?[e.evidence]:["observed"]}};var R=class{validateTransfer(e,t){return{approved:!0}}};function X(){return p().useCoherenceGate?new T:new R}b();var Y=g.create("transfer-verification"),fe={maxSourceRegression:.05,minTargetImprovement:0,maxSourceConfidenceRegression:.1},w=class{config;constructor(e={}){this.config={...fe,...e}}verifyTransfer(e){let t=e.sourcePerformanceAfter.successRate-e.sourcePerformanceBefore.successRate,r=e.targetPerformanceAfter.successRate-e.targetPerformanceBefore.successRate,n=e.sourcePerformanceAfter.avgConfidence-e.sourcePerformanceBefore.avgConfidence,s=e.targetPerformanceAfter.avgConfidence-e.targetPerformanceBefore.avgConfidence,i=t>=-this.config.maxSourceRegression&&n>=-this.config.maxSourceConfidenceRegression,a=r>=this.config.minTargetImprovement,c=i&&a,u;if(!c){let m=[];i||m.push(`source domain regressed: successRate delta=${t.toFixed(4)}, confidence delta=${n.toFixed(4)}`),a||m.push(`target domain did not improve: successRate delta=${r.toFixed(4)}`),u=m.join("; ")}return c?Y.debug("Transfer verification passed",{transferId:e.transferId,sourceDelta:t,targetDelta:r}):Y.warn("Transfer verification failed",{transferId:e.transferId,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourceDelta:t,targetDelta:r,failureReason:u}),{passed:c,sourceStable:i,targetImproved:a,sourceDelta:t,targetDelta:r,sourceConfidenceDelta:n,targetConfidenceDelta:s,failureReason:u}}getConfig(){return{...this.config}}};function J(o){return new w(o)}v();var y=class{alphas=new Map;betas=new Map;sample(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return this.sampleBeta(t,r)}update(e,t){t?this.alphas.set(e,(this.alphas.get(e)??1)+1):this.betas.set(e,(this.betas.get(e)??1)+1)}getMean(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t/(t+r)}getObservationCount(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t-1+(r-1)}getAlpha(e){return this.alphas.get(e)??1}getBeta(e){return this.betas.get(e)??1}sampleBeta(e,t){let r=this.sampleGamma(e),n=this.sampleGamma(t);return r+n===0?.5:r/(r+n)}sampleGamma(e){if(e<1){let n=Math.random();return this.sampleGamma(e+1)*Math.pow(n,1/e)}let t=e-1/3,r=1/Math.sqrt(9*t);for(;;){let n,s;do n=this.standardNormal(),s=1+r*n;while(s<=0);s=s*s*s;let i=Math.random();if(i<1-.0331*n*n*n*n||Math.log(i)<.5*n*n+t*(1-s+Math.log(s)))return t*s}}standardNormal(){let e=Math.random(),t=Math.random();return Math.sqrt(-2*Math.log(e||1e-10))*Math.cos(2*Math.PI*t)}};var Q=g.create("domain-transfer"),ge={minTransferProbability:.3,explorationWarmup:5,verification:{},maxHistorySize:1e3,useMetaLearningEnhancements:!0},M=class{constructor(e=100){this.decayThreshold=e}decayThreshold;getDecayMultiplier(e){return e<=0?1:Math.pow(.5,e/this.decayThreshold)}applyDecay(e,t,r){return t+(e-t)*this.getDecayMultiplier(r)}},E=class{cusum;outcomes=[];windowSize;constructor(e=20){this.windowSize=e,this.cusum=new d({threshold:3,slack:.1,resetOnAlarm:!1,warmupSamples:Math.min(10,Math.floor(e/2))})}record(e){this.outcomes.push(e),this.outcomes.length>this.windowSize*2&&this.outcomes.splice(0,this.outcomes.length-this.windowSize*2);let t=this.getCurrentRate();this.cusum.update("learn",t)}isPlateaued(){return this.outcomes.length<this.windowSize?!1:!this.cusum.getState("learn").driftDetected}getCurrentRate(){if(this.outcomes.length===0)return 0;let e=this.outcomes.slice(-this.windowSize);return e.filter(Boolean).length/e.length}getOutcomeCount(){return this.outcomes.length}getCusumState(){return this.cusum.getState("learn")}},A=class{front=[];dominates(e,t){let r=e.successRate>=t.successRate&&e.speed>=t.speed&&e.confidence>=t.confidence,n=e.successRate>t.successRate||e.speed>t.speed||e.confidence>t.confidence;return r&&n}add(e){for(let t=this.front.length-1;t>=0;t--)this.dominates(e,this.front[t])&&this.front.splice(t,1);this.front.some(t=>this.dominates(t,e))||this.front.push(e)}getFront(){return[...this.front]}isNonDominated(e){return!this.front.some(t=>this.dominates(t,e))}},F=class{constructor(e=.2){this.bonusScale=e}bonusScale;triedPairs=new Set;markTried(e){this.triedPairs.add(e)}isTried(e){return this.triedPairs.has(e)}getBonus(e){return this.triedPairs.has(e)?0:this.bonusScale}apply(e,t){return Math.min(1,e+this.getBonus(t))}getTriedCount(){return this.triedPairs.size}},G=class{config;sampler;verifier;coherenceGate;transferHistory=[];affinityScores=new Map;performanceProvider=null;transferExecutor=null;nativeModule=null;decayingBeta;plateauDetector;paretoFront;curiosityBonus;constructor(e={}){this.config={...ge,...e},this.sampler=new y,this.verifier=J(this.config.verification),this.coherenceGate=X(),this.decayingBeta=new M,this.plateauDetector=new E,this.paretoFront=new A,this.curiosityBonus=new F,this.tryLoadNativeModule()}evaluateTransfer(e,t){if(!this.isEnabled())return this.createRejectedCandidate(e,t);let r=this.makePairKey(e,t),n=this.sampler.sample(r),i=this.sampler.getObservationCount(r)<this.config.explorationWarmup,a=this.getAffinityScore(e,t);if(this.isMetaLearningEnabled()){let c=this.sampler.getMean(r),u=this.sampler.getAlpha(r)-1;n=this.decayingBeta.applyDecay(n,c,u),n=this.curiosityBonus.apply(n,r)}return{sourceDomain:e,targetDomain:t,sampledProbability:n,affinityScore:a,isExploration:i,pairKey:r}}executeTransfer(e){let t=`transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=this.coherenceGate.validateTransfer({domain:e.sourceDomain},e.targetDomain);if(!r.approved)return Q.info("Transfer blocked by coherence gate",{transferId:t,source:e.sourceDomain,target:e.targetDomain,reason:r.rejectionReason}),this.createBlockedResult(t,e,r);let n=this.getPerformanceSnapshot(e.sourceDomain),s=this.getPerformanceSnapshot(e.targetDomain),i=this.computeSqrtDampening(e),a=this.doTransfer(e.sourceDomain,e.targetDomain,i),c=this.getPerformanceSnapshot(e.sourceDomain),u=this.getPerformanceSnapshot(e.targetDomain),m=this.verifier.verifyTransfer({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourcePerformanceBefore:n,sourcePerformanceAfter:c,targetPerformanceBefore:s,targetPerformanceAfter:u}),l=a&&m.passed;if(this.sampler.update(e.pairKey,l),this.updateAffinityScore(e.pairKey,l),this.isMetaLearningEnabled()){this.plateauDetector.record(l),this.curiosityBonus.markTried(e.pairKey);let h=this.sampler.getMean(e.pairKey);this.paretoFront.add({pairKey:e.pairKey,successRate:h,speed:1/(1+i),confidence:this.getAffinityScore(e.sourceDomain,e.targetDomain)})}return this.addToHistory({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,success:l,sampledProbability:e.sampledProbability,dampeningFactor:i,sourceDelta:m.sourceDelta,targetDelta:m.targetDelta,timestamp:Date.now()}),Q.info("Transfer completed",{transferId:t,source:e.sourceDomain,target:e.targetDomain,success:l,dampeningFactor:i.toFixed(4),sourceDelta:m.sourceDelta.toFixed(4),targetDelta:m.targetDelta.toFixed(4)}),{transferId:t,candidate:e,success:l,dampeningFactor:i,verification:m,coherenceResult:r,sourcePerformanceBefore:n,sourcePerformanceAfter:c,targetPerformanceBefore:s,targetPerformanceAfter:u,timestamp:Date.now()}}getAffinityScore(e,t){return this.affinityScores.get(this.makePairKey(e,t))??.5}getTransferHistory(){return[...this.transferHistory]}getExpectedSuccessRate(e,t){return this.sampler.getMean(this.makePairKey(e,t))}getObservationCount(e,t){return this.sampler.getObservationCount(this.makePairKey(e,t))}setPerformanceProvider(e){this.performanceProvider=e}setTransferExecutor(e){this.transferExecutor=e}getSampler(){return this.sampler}getCoherenceGate(){return this.coherenceGate}getDecayingBeta(){return this.decayingBeta}getPlateauDetector(){return this.plateauDetector}getParetoFront(){return this.paretoFront}getCuriosityBonus(){return this.curiosityBonus}isLearningPlateaued(){return this.plateauDetector.isPlateaued()}isEnabled(){return p().useCrossDomainTransfer===!0}isMetaLearningEnabled(){return this.config.useMetaLearningEnhancements===!0&&p().useMetaLearningEnhancements!==!1}makePairKey(e,t){return`${e}->${t}`}computeSqrtDampening(e){let t=this.sampler.getObservationCount(e.pairKey);return Math.sqrt(t/(t+this.config.explorationWarmup))}doTransfer(e,t,r){return this.transferExecutor?this.transferExecutor(e,t,r):!0}getPerformanceSnapshot(e){return this.performanceProvider?this.performanceProvider(e):{domain:e,successRate:.5,avgConfidence:.5,patternCount:0,timestamp:Date.now()}}updateAffinityScore(e,t){let r=this.affinityScores.get(e)??.5;this.affinityScores.set(e,.2*(t?1:0)+.8*r)}addToHistory(e){for(this.transferHistory.push(e);this.transferHistory.length>this.config.maxHistorySize;)this.transferHistory.shift()}createBlockedResult(e,t,r){let n={domain:"",successRate:0,avgConfidence:0,patternCount:0,timestamp:Date.now()};return{transferId:e,candidate:t,success:!1,dampeningFactor:0,verification:{passed:!1,sourceStable:!1,targetImproved:!1,sourceDelta:0,targetDelta:0,sourceConfidenceDelta:0,targetConfidenceDelta:0,failureReason:`Coherence gate rejected: ${r.rejectionReason??"unknown"}`},coherenceResult:r,sourcePerformanceBefore:{...n,domain:t.sourceDomain},sourcePerformanceAfter:{...n,domain:t.sourceDomain},targetPerformanceBefore:{...n,domain:t.targetDomain},targetPerformanceAfter:{...n,domain:t.targetDomain},timestamp:Date.now()}}createRejectedCandidate(e,t){return{sourceDomain:e,targetDomain:t,sampledProbability:0,affinityScore:0,isExploration:!1,pairKey:this.makePairKey(e,t)}}tryLoadNativeModule(){this.nativeModule=null}};function $e(o){return new G(o)}export{d as a,y as b,ge as c,M as d,E as e,A as f,F as g,G as h,$e as i};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.14");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
2
2
  import{readFileSync as O,existsSync as x,readdirSync as A}from"fs";import{join as m,basename as w}from"path";function f(r){let e=[];if(!r||typeof r!="object")return e.push("Overlay must be a non-null object"),e;let n=r;if((!n.agent||typeof n.agent!="string")&&e.push('Overlay must have a string "agent" field'),n.replace!==void 0)if(typeof n.replace!="object"||n.replace===null)e.push('"replace" must be an object');else{let t=n.replace;t.description!==void 0&&typeof t.description!="string"&&e.push('"replace.description" must be a string'),t.domains!==void 0&&!Array.isArray(t.domains)&&e.push('"replace.domains" must be an array'),t.complexity!==void 0&&typeof t.complexity!="string"&&e.push('"replace.complexity" must be a string')}if(n.append!==void 0)if(typeof n.append!="object"||n.append===null)e.push('"append" must be an object');else{let t=n.append;t.instructions!==void 0&&typeof t.instructions!="string"&&e.push('"append.instructions" must be a string'),t.capabilities!==void 0&&!Array.isArray(t.capabilities)&&e.push('"append.capabilities" must be an array'),t.tags!==void 0&&!Array.isArray(t.tags)&&e.push('"append.tags" must be an array')}if(n.config!==void 0)if(typeof n.config!="object"||n.config===null)e.push('"config" must be an object');else{let t=n.config;t.minimumFindings!==void 0&&typeof t.minimumFindings!="number"&&e.push('"config.minimumFindings" must be a number'),t.maxParallelAgents!==void 0&&typeof t.maxParallelAgents!="number"&&e.push('"config.maxParallelAgents" must be a number'),t.preferredFrameworks!==void 0&&!Array.isArray(t.preferredFrameworks)&&e.push('"config.preferredFrameworks" must be an array'),t.needsContext!==void 0&&typeof t.needsContext!="boolean"&&e.push('"config.needsContext" must be a boolean')}return e}var v=".claude/agent-overrides",F=new Set(["__proto__","constructor","prototype"]);function $(r){let e={},n=p=>{let a=Object.hasOwn(e,p)?e[p]:void 0;if(a!==null&&typeof a=="object")return a;let l={};return e[p]=l,l},t=r.split(`
3
3
  `),i=null,s=null,o=null;for(let p of t){let a=p.replace(/\r$/,"");if(a.trim().startsWith("#")||a.trim()==="")continue;let l=a.length-a.trimStart().length,u=a.trim();if(u.startsWith("- ")){let b=u.slice(2).trim().replace(/^["']|["']$/g,"");s&&s.push(b);continue}s&&o&&(i&&(n(i)[o]=s),s=null,o=null);let g=u.match(/^(\w[\w.-]*)\s*:\s*(.*)$/);if(!g)continue;let[,c,h]=g,d=h.trim().replace(/^["']|["']$/g,"");if(F.has(c)){l===0&&(i=null);continue}l===0?d===""||d===void 0?(i=c,n(c)):(e[c]=y(d),i=null):l<=4&&i&&(d===""||d===void 0?(s=[],o=c):n(i)[c]=y(d))}return s&&o&&i&&(n(i)[o]=s),e}function y(r){if(r==="true")return!0;if(r==="false")return!1;if(r==="null")return null;let e=Number(r);return!isNaN(e)&&r!==""?e:r}function _(r){let e=m(r,v),n={overlays:[],warnings:[],errors:[]};if(!x(e))return n;let t;try{t=A(e).filter(i=>(i.endsWith(".yaml")||i.endsWith(".yml"))&&!i.startsWith("_"))}catch(i){return n.errors.push(`Failed to read overrides directory: ${i.message}`),n}for(let i of t){let s=m(e,i);try{let o=O(s,"utf-8"),p=$(o);if(!p.agent){let l=w(i).replace(/\.(override|customize)\.(yaml|yml)$/,"");p.agent=l}let a=f(p);if(a.length>0){n.warnings.push(`Overlay ${i} has validation issues: ${a.join("; ")}. Loading without overlay.`);continue}n.overlays.push(p)}catch(o){n.warnings.push(`Failed to parse overlay ${i}: ${o.message}. Agent loads without overlay.`)}}return n}function L(r,e){let n=r,t={agentName:e.agent,overlayFile:`${e.agent}.override.yaml`,replacedFields:[],appendedFields:[],configOverrides:[]};if(e.replace){if(e.replace.description){let i=/^(description:\s*).+$/m;i.test(n)&&(n=n.replace(i,`$1${e.replace.description}`),t.replacedFields.push("description"))}if(e.replace.domains){let i=/^(domain:\s*).+$/m;i.test(n)&&(n=n.replace(i,`$1${e.replace.domains.join(", ")}`),t.replacedFields.push("domains"))}if(e.replace.complexity){let i=/^(complexity:\s*).+$/m;i.test(n)&&(n=n.replace(i,`$1${e.replace.complexity}`),t.replacedFields.push("complexity"))}}if(e.append){if(e.append.instructions&&(n+=`
4
4
 
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.14");process.exit(0)}
2
- import{a as F,d as C}from"./chunk-QP2HLKTS.js";import{a as E}from"./chunk-EC65UZ77.js";import{a as O,b as P,c as x,e as J}from"./chunk-UDSB3XCG.js";import{b as W,d as B}from"./chunk-2UZBLC5H.js";var Q=new Set(["false","0","off","no"]),K=new Set([...Q,"disabled","disable","none","never"]),V=30,G=36500;function pe(l=process.env){let e=l.AQE_WORKERS_ENABLED;return e===void 0?!0:!Q.has(e.trim().toLowerCase())}function ge(l=process.env){let e=l.AQE_DISABLED_WORKERS;if(!e)return[];let t=e.split(",").map(i=>i.trim().toLowerCase()).filter(i=>i.length>0);return Array.from(new Set(t))}function fe(l=process.env){let e=l.AQE_DREAM_INSIGHTS_RETENTION_DAYS;if(e===void 0||e.trim()==="")return{retentionDays:V};let t=e.trim().toLowerCase();if(K.has(t))return{retentionDays:null};if(/^\d+$/.test(t)){let i=Number(t);if(i>=1&&i<=G)return{retentionDays:i}}return{retentionDays:null,warning:`Invalid AQE_DREAM_INSIGHTS_RETENTION_DAYS=${JSON.stringify(e)}; expected a whole number of days (1-${G}), 0 or "off". The dream_insights retention sweep is off until this is fixed; nothing is deleted.`}}var I="quality-daemon",R=class{constructor(e){this.backend=e}backend;async get(e,t){return this.backend.kvGet(e,t?.namespace??I)}async set(e,t){await this.backend.kvSet(e,t,I)}async search(e,t,i){return this.backend.kvSearch(e,i?.namespace??I,t)}};import{cpus as ce,freemem as de,totalmem as he,loadavg as me}from"os";var p=class{queues={now:[],next:[],later:[]};_maxSize;constructor(e=1e3){this._maxSize=e}enqueue(e){return this.size>=this._maxSize&&(this.pruneExpired(),this.size>=this._maxSize)?!1:(this.queues[e.priority].push(e),!0)}dequeue(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(;i.length>0;){let r=i.shift();if(!(r.ttlMs&&e-r.createdAt>r.ttlMs))return r}}}peek(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(let r of i)if(!r.ttlMs||e-r.createdAt<=r.ttlMs)return r}}drainPriority(e){let t=this.queues[e].splice(0),i=Date.now();return t.filter(r=>!r.ttlMs||i-r.createdAt<=r.ttlMs)}pruneExpired(){let e=0,t=Date.now();for(let i of["now","next","later"]){let r=this.queues[i].length;this.queues[i]=this.queues[i].filter(o=>!o.ttlMs||t-o.createdAt<=o.ttlMs),e+=r-this.queues[i].length}return e}get size(){return this.queues.now.length+this.queues.next.length+this.queues.later.length}get depths(){return{now:this.queues.now.length,next:this.queues.next.length,later:this.queues.later.length}}get isEmpty(){return this.size===0}clear(){this.queues.now=[],this.queues.next=[],this.queues.later=[]}};import{watch as Y}from"fs";import{resolve as $,join as X}from"path";import{existsSync as Z,readFileSync as ee}from"fs";var M=1e4,te={repoRoot:process.cwd(),debounceMs:500,maxChangedFiles:200,pollIntervalMs:5e3},g=class{constructor(e,t){this.queue=e;this.options={...te,...t}}queue;watcher;pollTimer;options;lastKnownHeads=new Map;debounceTimer;_running=!1;_polling=!1;get running(){return this._running}async start(){if(this._running)return;let e=$(this.options.repoRoot,".git","refs","heads");if(!Z(e))throw new Error(`Git refs directory not found: ${e}`);await this.snapshotHeads(),process.platform==="darwin"||process.platform==="win32"?this.watcher=Y(e,{recursive:!0},(i,r)=>{r&&this.handleRefChange(r)}):(this.pollTimer=setInterval(()=>{this.poll().catch(i=>{console.debug("[GitWatcher] Poll error:",i)})},this.options.pollIntervalMs),this.pollTimer.unref?.()),this._running=!0}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0),this.watcher&&(this.watcher.close(),this.watcher=void 0),this._running=!1}async poll(){if(this._polling)return[];this._polling=!0;let e=[];try{let t=await C(["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot,timeout:M});for(let i of t.trim().split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
2
+ import{a as F,d as C}from"./chunk-YRAX7SFJ.js";import{a as E}from"./chunk-NVEWF4JV.js";import{a as O,b as P,c as x,e as J}from"./chunk-S75SOOZL.js";import{b as W,d as B}from"./chunk-AGRV5B3T.js";var Q=new Set(["false","0","off","no"]),K=new Set([...Q,"disabled","disable","none","never"]),V=30,G=36500;function pe(l=process.env){let e=l.AQE_WORKERS_ENABLED;return e===void 0?!0:!Q.has(e.trim().toLowerCase())}function ge(l=process.env){let e=l.AQE_DISABLED_WORKERS;if(!e)return[];let t=e.split(",").map(i=>i.trim().toLowerCase()).filter(i=>i.length>0);return Array.from(new Set(t))}function fe(l=process.env){let e=l.AQE_DREAM_INSIGHTS_RETENTION_DAYS;if(e===void 0||e.trim()==="")return{retentionDays:V};let t=e.trim().toLowerCase();if(K.has(t))return{retentionDays:null};if(/^\d+$/.test(t)){let i=Number(t);if(i>=1&&i<=G)return{retentionDays:i}}return{retentionDays:null,warning:`Invalid AQE_DREAM_INSIGHTS_RETENTION_DAYS=${JSON.stringify(e)}; expected a whole number of days (1-${G}), 0 or "off". The dream_insights retention sweep is off until this is fixed; nothing is deleted.`}}var I="quality-daemon",R=class{constructor(e){this.backend=e}backend;async get(e,t){return this.backend.kvGet(e,t?.namespace??I)}async set(e,t){await this.backend.kvSet(e,t,I)}async search(e,t,i){return this.backend.kvSearch(e,i?.namespace??I,t)}};import{cpus as ce,freemem as de,totalmem as he,loadavg as me}from"os";var p=class{queues={now:[],next:[],later:[]};_maxSize;constructor(e=1e3){this._maxSize=e}enqueue(e){return this.size>=this._maxSize&&(this.pruneExpired(),this.size>=this._maxSize)?!1:(this.queues[e.priority].push(e),!0)}dequeue(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(;i.length>0;){let r=i.shift();if(!(r.ttlMs&&e-r.createdAt>r.ttlMs))return r}}}peek(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(let r of i)if(!r.ttlMs||e-r.createdAt<=r.ttlMs)return r}}drainPriority(e){let t=this.queues[e].splice(0),i=Date.now();return t.filter(r=>!r.ttlMs||i-r.createdAt<=r.ttlMs)}pruneExpired(){let e=0,t=Date.now();for(let i of["now","next","later"]){let r=this.queues[i].length;this.queues[i]=this.queues[i].filter(o=>!o.ttlMs||t-o.createdAt<=o.ttlMs),e+=r-this.queues[i].length}return e}get size(){return this.queues.now.length+this.queues.next.length+this.queues.later.length}get depths(){return{now:this.queues.now.length,next:this.queues.next.length,later:this.queues.later.length}}get isEmpty(){return this.size===0}clear(){this.queues.now=[],this.queues.next=[],this.queues.later=[]}};import{watch as Y}from"fs";import{resolve as $,join as X}from"path";import{existsSync as Z,readFileSync as ee}from"fs";var M=1e4,te={repoRoot:process.cwd(),debounceMs:500,maxChangedFiles:200,pollIntervalMs:5e3},g=class{constructor(e,t){this.queue=e;this.options={...te,...t}}queue;watcher;pollTimer;options;lastKnownHeads=new Map;debounceTimer;_running=!1;_polling=!1;get running(){return this._running}async start(){if(this._running)return;let e=$(this.options.repoRoot,".git","refs","heads");if(!Z(e))throw new Error(`Git refs directory not found: ${e}`);await this.snapshotHeads(),process.platform==="darwin"||process.platform==="win32"?this.watcher=Y(e,{recursive:!0},(i,r)=>{r&&this.handleRefChange(r)}):(this.pollTimer=setInterval(()=>{this.poll().catch(i=>{console.debug("[GitWatcher] Poll error:",i)})},this.options.pollIntervalMs),this.pollTimer.unref?.()),this._running=!0}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0),this.watcher&&(this.watcher.close(),this.watcher=void 0),this._running=!1}async poll(){if(this._polling)return[];this._polling=!0;let e=[];try{let t=await C(["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot,timeout:M});for(let i of t.trim().split(`
3
3
  `)){if(!i)continue;let[r,o]=i.split(" "),n=this.lastKnownHeads.get(r);n&&n!==o&&(e.push(r),await this.enqueueCommitAnalysis(r,o)),this.lastKnownHeads.set(r,o)}}catch{}finally{this._polling=!1}return e}handleRefChange(e){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.processRefChange(e).catch(t=>{console.debug("[GitWatcher] Error processing ref change:",t)})},this.options.debounceMs)}async processRefChange(e){let t=e.replace(/\\/g,"/"),i=$(this.options.repoRoot,".git","refs","heads"),r=X(i,e),o;try{o=ee(r,"utf-8").trim()}catch{return}this.lastKnownHeads.get(t)!==o&&(this.lastKnownHeads.set(t,o),await this.enqueueCommitAnalysis(t,o))}async enqueueCommitAnalysis(e,t){if(E(t,"commit hash"))return;let i=[];try{i=(await C(["diff-tree","--no-commit-id","--name-only","-r",t],{cwd:this.options.repoRoot,timeout:M})).trim().split(`
4
4
  `).filter(Boolean).slice(0,this.options.maxChangedFiles)}catch{}let r={type:"git_commit",branch:e,commitHash:t,changedFiles:i},o={id:`git-${t}-${Date.now()}`,priority:"next",payload:r,createdAt:Date.now(),source:"git-watcher",ttlMs:300*1e3};this.queue.enqueue(o)}async snapshotHeads(){try{let e=await C(["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot,timeout:M});for(let t of e.trim().split(`
5
5
  `)){if(!t)continue;let[i,r]=t.split(" ");this.lastKnownHeads.set(i,r)}}catch{}}};function A(l,e){return l===null||e===null?0:l-e}var ie={regressionThreshold:2,gapThreshold:60,memoryPrefix:"quality-daemon:coverage"},f=class{constructor(e,t){this.queue=e;this.options={...ie,...t}}queue;options;async analyze(e,t,i){let r=await t.get(`${this.options.memoryPrefix}:snapshot`);if(await t.set(`${this.options.memoryPrefix}:snapshot`,e),!r)return{regressionDetected:!1,overallDelta:{line:0,branch:0,function:0,statement:0},affectedFiles:[],newGaps:[]};let o=r,n={line:e.overall.line-o.overall.line,branch:A(e.overall.branch,o.overall.branch??null),function:A(e.overall.function,o.overall.function??null),statement:A(e.overall.statement,o.overall.statement??null)},s=n.line<-this.options.regressionThreshold||(n.branch??0)<-this.options.regressionThreshold,a=i??Object.keys(e.files),c=[],d=[];for(let h of a){let u=e.files[h],m=o.files[h];if(!u)continue;let q=m?u.line-m.line:0,N=m?u.branch-m.branch:0,T=m?u.uncoveredLines.filter(_=>!m.uncoveredLines.includes(_)):u.uncoveredLines;if((q!==0||N!==0||T.length>0)&&c.push({file:h,lineDelta:q,branchDelta:N,newUncoveredLines:T}),u.line<this.options.gapThreshold){let _=this.computeRiskScore(u,T.length);d.push({file:h,uncoveredLines:u.uncoveredLines,currentCoverage:u.line,riskScore:_})}}return(s||d.length>0)&&this.enqueueTestSuggestion(e,o,d),await t.set(`${this.options.memoryPrefix}:delta`,{timestamp:Date.now(),overallDelta:n,regressionDetected:s,affectedFileCount:c.length,gapCount:d.length}),{regressionDetected:s,overallDelta:n,affectedFiles:c,newGaps:d}}async buildSnapshot(e){let t=await e.get("coverage:latest"),i=F(t);if(i)return{timestamp:Date.now(),overall:{line:i.line,branch:i.branch,function:i.function,statement:i.statement},files:t&&typeof t.files=="object"?t.files:{}}}computeRiskScore(e,t){let r=1-Math.min(100,Math.max(0,e.line))/100,o=Math.min(t/50,1);return Math.min(1,r*.6+o*.4)}enqueueTestSuggestion(e,t,i){let r={type:"coverage_delta",previousSnapshot:`snapshot-${t.timestamp}`,currentSnapshot:`snapshot-${e.timestamp}`},o={id:`coverage-delta-${Date.now()}`,priority:i.some(n=>n.riskScore>.8)?"now":"next",payload:r,createdAt:Date.now(),source:"coverage-delta",ttlMs:600*1e3};this.queue.enqueue(o)}};J();import{execFile as re}from"child_process";import{promisify as oe}from"util";var ne=oe(re),se={runsPerWorkflow:10,flakyThreshold:3,repo:""},y=class{constructor(e,t){this.queue=e;this.options={...se,...t}}queue;options;async check(){let e=await this.fetchRecentRuns(),t=this.groupByWorkflow(e),i=[],r=[],o=0;for(let[s,a]of Object.entries(t)){let c=a.filter(m=>m.conclusion==="failure").length,d=a.length>0?(a.length-c)/a.length*100:100,h=this.countConsecutiveFailures(a),u=a[0]?.conclusion??"unknown";u==="failure"&&o++,h>=this.options.flakyThreshold&&(r.push(s),this.enqueueFailureAlert(s,a[0])),i.push({name:s,recentRuns:a.length,failedRuns:c,successRate:Math.round(d*10)/10,lastConclusion:u,consecutiveFailures:h})}let n=this.calculateHealthScore(i);return{timestamp:Date.now(),workflows:i,failingWorkflows:o,flakyWorkflows:r,healthScore:n}}async fetchRecentRuns(){try{let e=["run","list","--limit",String(this.options.runsPerWorkflow*5),"--json","name,status,conclusion,headBranch,number,databaseId,createdAt"];this.options.repo&&e.push("--repo",this.options.repo);let{stdout:t}=await ne("gh",e,{timeout:15e3});return JSON.parse(t).map(r=>({name:r.name,status:r.status,conclusion:r.conclusion??"pending",headBranch:r.headBranch,runNumber:r.number,databaseId:r.databaseId,createdAt:r.createdAt}))}catch{return[]}}groupByWorkflow(e){let t=O();for(let i of e){let r=P(t,i.name);r||(r=[],x(t,i.name,r)),r.push(i)}for(let i of Object.keys(t))x(t,i,P(t,i).slice(0,this.options.runsPerWorkflow));return t}countConsecutiveFailures(e){let t=0;for(let i of e)if(i.conclusion==="failure")t++;else break;return t}calculateHealthScore(e){if(e.length===0)return 100;let t=e.reduce((i,r)=>i+r.successRate,0)/e.length;return Math.round(t)}enqueueFailureAlert(e,t){let i={type:"ci_failure",workflowName:e,runId:t.databaseId,conclusion:t.conclusion},r={id:`ci-failure-${e}-${Date.now()}`,priority:"now",payload:i,createdAt:Date.now(),source:"ci-monitor",ttlMs:1800*1e3};this.queue.enqueue(r)}};var ae={memoryPrefix:"quality-daemon:suggestions",maxSuggestions:100,minRiskScore:.3},v=class{options;constructor(e){this.options={...ae,...e}}async suggest(e,t,i){let r=[],o=e.filter(s=>s.riskScore>=this.options.minRiskScore);for(let s of o){let a=t.includes(s.file),c=this.determinePriority(s,a),d=this.determineTestType(s.file),h=this.estimateEffort(s);r.push({id:`suggestion-${Date.now()}-${r.length}`,file:s.file,uncoveredLines:s.uncoveredLines.slice(0,50),suggestedTestType:d,description:this.generateDescription(s,d),priority:c,estimatedEffort:h,createdAt:Date.now(),status:"pending"})}r.sort((s,a)=>{let c={high:0,medium:1,low:2};return c[s.priority]-c[a.priority]});let n=r.slice(0,this.options.maxSuggestions);return await this.storeSuggestions(n,i),n}async getPending(e){return(await e.get(`${this.options.memoryPrefix}:list`)??[]).filter(i=>i.status==="pending")}async updateStatus(e,t,i){let r=await i.get(`${this.options.memoryPrefix}:list`);if(!r)return!1;let o=r.findIndex(s=>s.id===e);if(o===-1)return!1;let n=r.map((s,a)=>a===o?{...s,status:t}:s);return await i.set(`${this.options.memoryPrefix}:list`,n),!0}determinePriority(e,t){return e.riskScore>.8?"high":t||e.riskScore>.5?"medium":"low"}determineTestType(e){return e.includes("/api/")||e.includes("/routes/")||e.includes("/handlers/")?"integration":e.includes("/e2e/")||e.includes("/pages/")||e.includes("/views/")?"e2e":"unit"}estimateEffort(e){return e.uncoveredLines.length<=10?"small":e.uncoveredLines.length<=50?"medium":"large"}generateDescription(e,t){let i=e.uncoveredLines.length,r=Math.round(e.currentCoverage);return`Add ${t} tests for ${e.file} (${i} uncovered lines, ${r}% coverage, risk ${(e.riskScore*100).toFixed(0)}%)`}async storeSuggestions(e,t){let o=[...(await t.get(`${this.options.memoryPrefix}:list`)??[]).filter(n=>n.status!=="pending"),...e].slice(-this.options.maxSuggestions);await t.set(`${this.options.memoryPrefix}:list`,o),await t.set(`${this.options.memoryPrefix}:count`,{pending:e.length,total:o.length,lastUpdated:Date.now()})}};var le={memoryPrefix:"quality-daemon:nightly",maxEntryAge:6048e5,nightlyHour:2},w=class{constructor(e,t){this.queue=e;this.options={...le,...t}}queue;options;lastRunDate;shouldRun(){let e=new Date,t=e.toISOString().split("T")[0];return this.lastRunDate===t?!1:e.getHours()>=this.options.nightlyHour}scheduleIfDue(){if(!this.shouldRun())return!1;let e={type:"nightly",tasks:["consolidate_patterns","prune_expired","generate_report"]},t={id:`nightly-${Date.now()}`,priority:"later",payload:e,createdAt:Date.now(),source:"nightly-consolidation",ttlMs:720*60*1e3};return this.queue.enqueue(t)}async execute(e,t){let i=Date.now(),r=new Date().toISOString().split("T")[0],o=await this.consolidatePatterns(e),n=await this.pruneExpired(e),s=this.generateReport(r,t);await e.set(`${this.options.memoryPrefix}:report:${r}`,s),this.lastRunDate=r;let a={timestamp:Date.now(),patternsConsolidated:o,entriesPruned:n,reportGenerated:!0,durationMs:Date.now()-i};return await e.set(`${this.options.memoryPrefix}:last-result`,a),a}async getLastResult(e){return e.get(`${this.options.memoryPrefix}:last-result`)}async consolidatePatterns(e){let t=await e.search("quality-daemon:*"),i=0;return await e.get("quality-daemon:suggestions:count")&&i++,await e.get("quality-daemon:coverage:delta")&&i++,i}async pruneExpired(e){let t=await e.search("quality-daemon:*"),i=0,r=Date.now();for(let o of t){if(o.endsWith(":snapshot")||o.endsWith(":list"))continue;let n=await e.get(o);n&&typeof n.timestamp=="number"&&r-n.timestamp>this.options.maxEntryAge&&(await e.set(o,{pruned:!0,prunedAt:r}),i++)}return i}generateReport(e,t){return{date:e,coverageHealth:t.coverageHealth??0,ciHealth:t.ciHealth??0,commitsAnalyzed:t.commitsAnalyzed??0,suggestionsGenerated:t.suggestionsGenerated??0,notificationsSent:t.notificationsSent??0,queueDepthAvg:t.queueDepthAvg??0,daemonUptime:t.uptimeSeconds??0}}};B();import{writeFileSync as H,mkdirSync as L,readdirSync as D,readFileSync as U,unlinkSync as z}from"fs";import{join as b}from"path";var ue={maxNotifications:200},k=class{notificationsDir;maxNotifications;webhookUrl;urlValidator;_sentCount=0;constructor(e){this.notificationsDir=e?.notificationsDir??W("notifications"),this.maxNotifications=e?.maxNotifications??ue.maxNotifications,this.webhookUrl=e?.webhookUrl,this.urlValidator=e?.urlValidator}get sentCount(){return this._sentCount}initialize(){L(this.notificationsDir,{recursive:!0})}async send(e){let t={...e,id:`notif-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now(),read:!1};return this.writeToFile(t),this.webhookUrl&&await this.sendWebhook(t),this._sentCount++,this.pruneOldNotifications(),t}list(e){let t=e?.limit??50;try{let i=D(this.notificationsDir).filter(o=>o.endsWith(".json")).sort().reverse(),r=[];for(let o of i){if(r.length>=t)break;try{let n=U(b(this.notificationsDir,o),"utf-8"),s=JSON.parse(n);if(e?.unreadOnly&&s.read||e?.type&&s.type!==e.type)continue;r.push(s)}catch{}}return r}catch{return[]}}markRead(e){try{let t=D(this.notificationsDir).filter(n=>n.endsWith(`-${e}.json`));if(t.length===0)return!1;let i=b(this.notificationsDir,t[0]),o={...JSON.parse(U(i,"utf-8")),read:!0};return H(i,JSON.stringify(o,null,2)),!0}catch{return!1}}clear(){try{let e=D(this.notificationsDir).filter(t=>t.endsWith(".json"));for(let t of e)z(b(this.notificationsDir,t));return e.length}catch{return 0}}writeToFile(e){try{L(this.notificationsDir,{recursive:!0});let t=`${e.timestamp}-${e.id}.json`,i=b(this.notificationsDir,t);H(i,JSON.stringify(e,null,2))}catch(t){console.debug("[NotificationService] Failed to write notification:",t)}}async sendWebhook(e){if(this.webhookUrl){if(this.urlValidator&&!this.urlValidator(this.webhookUrl)){console.warn("[NotificationService] Webhook URL blocked by SSRF guard:",this.webhookUrl);return}try{let t=await fetch(this.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});t.ok||console.debug(`[NotificationService] Webhook returned ${t.status}`)}catch(t){console.debug("[NotificationService] Webhook delivery failed:",t)}}}pruneOldNotifications(){try{let e=D(this.notificationsDir).filter(i=>i.endsWith(".json")).sort();if(e.length<=this.maxNotifications)return;let t=e.slice(0,e.length-this.maxNotifications);for(let i of t)z(b(this.notificationsDir,i))}catch{}}};var S={tickIntervalMs:3e4,ciPollIntervalMs:5*6e4,coverageCheckIntervalMs:2*6e4,cpuThreshold:.7,memoryThreshold:.8},j=class{queue;gitWatcher;coverageDelta;ciMonitor;testSuggester;nightlyConsolidation;notificationService;tickTimer;_running=!1;_startedAt=0;_tickCount=0;_lastTickAt;_throttled=!1;_commitsAnalyzed=0;_suggestionsGenerated=0;_ciHealth=100;_coverageHealth=100;_lastCICheck;_lastCoverageCheck;_memory;config;constructor(e){this.config={tickIntervalMs:e?.tickIntervalMs??S.tickIntervalMs,ciPollIntervalMs:e?.ciPollIntervalMs??S.ciPollIntervalMs,coverageCheckIntervalMs:e?.coverageCheckIntervalMs??S.coverageCheckIntervalMs,cpuThreshold:e?.cpuThreshold??S.cpuThreshold,memoryThreshold:e?.memoryThreshold??S.memoryThreshold},this.queue=new p,this.gitWatcher=new g(this.queue,e?.git),this.coverageDelta=new f(this.queue,e?.coverage),this.ciMonitor=new y(this.queue,e?.ci),this.testSuggester=new v(e?.suggestions),this.nightlyConsolidation=new w(this.queue,e?.nightly),this.notificationService=new k(e?.notifications)}get running(){return this._running}async start(e){this._running||(this._memory=e,this._running=!0,this._startedAt=Date.now(),this.notificationService.initialize(),await this.gitWatcher.start().catch(t=>{console.debug("[QualityDaemon] Git watcher failed to start:",t)}),this.scheduleTick())}async stop(){this._running&&(this._running=!1,this.tickTimer&&(clearTimeout(this.tickTimer),this.tickTimer=void 0),this.gitWatcher.stop(),this._memory&&await this._memory.set("quality-daemon:state",{stoppedAt:Date.now(),tickCount:this._tickCount,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated}))}getStatus(){return{running:this._running,uptimeSeconds:this._running?Math.floor((Date.now()-this._startedAt)/1e3):0,tickCount:this._tickCount,queueDepth:this.queue.depths,lastTickAt:this._lastTickAt,throttled:this._throttled,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,ciHealth:this._ciHealth,coverageHealth:this._coverageHealth,lastCICheck:this._lastCICheck,lastCoverageCheck:this._lastCoverageCheck}}scheduleTick(){this._running&&(this.tickTimer=setTimeout(()=>this.tick(),this.config.tickIntervalMs),this.tickTimer.unref?.())}async tick(){if(!(!this._running||!this._memory)){if(this._tickCount++,this._lastTickAt=Date.now(),this._throttled=this.isResourceConstrained(),this._throttled){await this.processNowItems(this._memory),this.scheduleTick();return}await this.processQueue(this._memory),await this.runPeriodicChecks(this._memory),this.nightlyConsolidation.scheduleIfDue(),this.queue.pruneExpired(),this.scheduleTick()}}async processQueue(e){let t=0,i=10;for(;t<i&&!this.queue.isEmpty;){let r=this.queue.dequeue();if(!r)break;await this.handleQueueItem(r,e),t++}}async processNowItems(e){let t=this.queue.drainPriority("now");for(let i of t)await this.handleQueueItem(i,e)}async handleQueueItem(e,t){let i=e.payload;switch(i.type){case"git_commit":{this._commitsAnalyzed++;let r=await this.coverageDelta.buildSnapshot(t);if(r){let o=await this.coverageDelta.analyze(r,t,i.changedFiles);if(o.regressionDetected&&await this.notificationService.send({type:"coverage_drop",title:"Coverage Regression Detected",message:`Line coverage delta: ${o.overallDelta.line.toFixed(1)}% (${o.affectedFiles.length} files affected)`,severity:"high",metadata:{delta:o.overallDelta,commit:i.commitHash}}),o.newGaps.length>0){let n=await this.testSuggester.suggest(o.newGaps,i.changedFiles,t);this._suggestionsGenerated+=n.length,n.length>0&&await this.notificationService.send({type:"suggestion_available",title:"New Test Suggestions Available",message:`${n.length} test suggestions generated for uncovered code`,severity:"info",metadata:{count:n.length}})}}break}case"coverage_delta":{let r=await this.testSuggester.getPending(t);r.length>0&&await this.notificationService.send({type:"suggestion_available",title:"Test Suggestions Pending",message:`${r.length} test suggestions awaiting review`,severity:"info",metadata:{count:r.length}});break}case"gate_failure":await this.notificationService.send({type:"gate_failure",title:`Quality Gate Failed: ${i.gateName}`,message:`Score ${i.score} below threshold ${i.threshold}`,severity:"critical",metadata:{gate:i.gateName,score:i.score,threshold:i.threshold}});break;case"ci_failure":await this.notificationService.send({type:"ci_failure",title:`CI Failure: ${i.workflowName}`,message:`Workflow ${i.workflowName} run #${i.runId} concluded: ${i.conclusion}`,severity:"high",metadata:{workflow:i.workflowName,runId:i.runId}});break;case"nightly":{let r={coverageHealth:this._coverageHealth,ciHealth:this._ciHealth,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,queueDepthAvg:this.queue.size,uptimeSeconds:Math.floor((Date.now()-this._startedAt)/1e3)};await this.nightlyConsolidation.execute(t,r);break}default:console.warn("[QualityDaemon] Unhandled payload type:",i.type)}}async runPeriodicChecks(e){let t=Date.now();if(!this._lastCICheck||t-this._lastCICheck>=this.config.ciPollIntervalMs)try{let i=await this.ciMonitor.check();this._ciHealth=i.healthScore,this._lastCICheck=t,i.flakyWorkflows.length>0&&await this.notificationService.send({type:"flaky_detected",title:"Flaky Workflows Detected",message:`${i.flakyWorkflows.length} workflows showing repeated failures: ${i.flakyWorkflows.join(", ")}`,severity:"medium",metadata:{workflows:i.flakyWorkflows}})}catch{}if(!this._lastCoverageCheck||t-this._lastCoverageCheck>=this.config.coverageCheckIntervalMs)try{let i=await this.coverageDelta.buildSnapshot(e);if(i){let r=[i.overall.line,i.overall.branch,i.overall.function,i.overall.statement].filter(o=>typeof o=="number");this._coverageHealth=Math.round(r.reduce((o,n)=>o+n,0)/r.length),this._lastCoverageCheck=t}}catch{}}isResourceConstrained(){if(1-de()/he()>this.config.memoryThreshold)return!0;let t=ce().length;return(t>0?me()[0]/t:0)>this.config.cpuThreshold}};export{pe as a,ge as b,fe as c,R as d,j 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.15.14");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
2
2
  import{existsSync as c,readFileSync as f}from"fs";import{join as p,dirname as i}from"path";import{fileURLToPath as s}from"url";function u(o,a=10){let t=i(s(o));for(let r=0;r<a;r++){let n=p(t,"package.json");if(c(n))try{if(JSON.parse(f(n,"utf-8")).name==="agentic-qe")return t}catch{}let e=i(t);if(e===t)break;t=e}return null}export{u as a};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.14");process.exit(0)}
2
- import{b as l,d as y}from"./chunk-XN3KCKAM.js";y();import{copyFileSync as k,existsSync as c,readFileSync as u,writeFileSync as s}from"fs";function J(n,r){let e=typeof r=="string"?Buffer.from(r,"utf-8"):r;try{if(c(n)&&u(n).equals(e))return!1}catch{}return typeof r=="string"?s(n,r,"utf-8"):s(n,r),!0}function S(n,r){try{if(c(r)&&u(r).equals(u(n)))return!1}catch{}return k(n,r),!0}function E(n,r,e){try{if(c(n)){let t=o=>o.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
2
+ import{b as l,d as y}from"./chunk-V5NHZV7S.js";y();import{copyFileSync as k,existsSync as c,readFileSync as u,writeFileSync as s}from"fs";function J(n,r){let e=typeof r=="string"?Buffer.from(r,"utf-8"):r;try{if(c(n)&&u(n).equals(e))return!1}catch{}return typeof r=="string"?s(n,r,"utf-8"):s(n,r),!0}function S(n,r){try{if(c(r)&&u(r).equals(u(n)))return!1}catch{}return k(n,r),!0}function E(n,r,e){try{if(c(n)){let t=o=>o.split(`
3
3
  `).filter(i=>!e.test(i)).join(`
4
4
  `);if(t(u(n,"utf-8"))===t(r))return!1}}catch{}return s(n,r,"utf-8"),!0}var I=/^\*Generated by AQE v3 init on [^*]+\*$/;function a(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function d(n){return JSON.stringify(n,(r,e)=>{if(!a(e))return e;let t={};for(let o of Object.keys(e).sort())t[o]=e[o];return t})}function w(n,r){return d(n)===d(r)}function f(n,r){let e=n;for(let t of r){if(!a(e))return;e=e[t]}return e}function g(n,r,e){let t=n;for(let i of r.slice(0,-1)){if(!a(t[i]))return;t=t[i]}let o=r[r.length-1];o in t&&(t[o]=e)}function p(n,r,e){if(!a(n))return!0;let t=JSON.parse(JSON.stringify(r));for(let o of e){let i=f(n,o);i!==void 0&&f(t,o)!==void 0&&g(t,o,i)}if(!w(n,t))return!0;for(let o of e){let i=f(n,o);i!==void 0&&f(r,o)!==void 0&&g(r,o,i)}return!1}function R(n){if(c(n))try{return l(u(n,"utf-8"))}catch{return}}function N(n,r,e=[]){let t=R(n);return t!==void 0&&!p(t,r,e)?!1:(s(n,JSON.stringify(r,null,2),"utf-8"),!0)}export{J as a,S as b,E as c,I as d,p as e,N as f};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.14");process.exit(0)}
2
- import{g,n as f}from"./chunk-52KOPIMI.js";import{a as l,d as c,e as k}from"./chunk-UDSB3XCG.js";import{b as C}from"./chunk-V6SE2ZU2.js";import{randomUUID as T}from"crypto";function b(s){let t=Object.hasOwn(h,s)?h[s]:void 0;if(t)return{input:t.input,output:t.output};let e=g(s);if(e.inputCostPerMillion>0||e.outputCostPerMillion>0)return{input:e.inputCostPerMillion,output:e.outputCostPerMillion}}function w(){return d||(d=new m),d}function x(){d&&(d.dispose(),d=void 0)}var h,m,d,R=C(()=>{f();k();h={"claude-sonnet-5":{input:2,output:10,provider:"claude"},"claude-opus-5":{input:5,output:25,provider:"claude"},"claude-opus-5-5":{input:4,output:20,provider:"claude"},"claude-fable-5-1":{input:10,output:50,provider:"claude"},"claude-fable-5":{input:10,output:50,provider:"claude"},"claude-opus-4-8":{input:5,output:25,provider:"claude"},"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-haiku-4-5":{input:1,output:5,provider:"claude"},"claude-opus-4-5-20251101":{input:5,output:25,provider:"claude"},"claude-opus-4-6":{input:5,output:25,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-6-astra":{input:10,output:50,provider:"openai"},"gpt-6-sol":{input:2,output:10,provider:"openai"},"gpt-6-luna":{input:.1,output:.5,provider:"openai"},"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-sonnet-5":{input:2,output:10,provider:"openrouter"},"anthropic/claude-opus-5":{input:5,output:25,provider:"openrouter"},"anthropic/claude-opus-5.5":{input:4,output:20,provider:"openrouter"},"anthropic/claude-haiku-4.5":{input:1,output:5,provider:"openrouter"},"openai/gpt-6-sol":{input:2,output:10,provider:"openrouter"},"openai/gpt-6-luna":{input:.1,output:.5,provider:"openrouter"},"google/gemini-3.8-flash":{input:.75,output:3.75,provider:"openrouter"},"meta-llama/llama-4-maverick":{input:.1875,output:.6525,provider:"openrouter"},"openai/gpt-oss-120b":{input:.15,output:.6,provider:"openrouter"},"qwen/qwen3-coder":{input:.3,output:1,provider:"openrouter"},"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-3.8-flash":{input:.75,output:3.75,provider:"gemini"},"gemini-3.5-flash":{input:1.5,output:9,provider:"gemini"},"gemini-3.1-pro-preview":{input:2,output:12,provider:"gemini"},"gemini-2.5-flash":{input:.3,output:2.5,provider:"gemini"},"gemini-2.5-pro":{input:1.25,output:10,provider:"gemini"},"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"}};m=class s{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(t=1e4){this.maxRecords=t}static calculateCost(t,e){let o=b(t);if(!o)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let i=e.promptTokens/1e6*o.input+(e.cacheReadTokens??0)/1e6*o.input*.1+(e.cacheCreationTokens??0)/1e6*o.input*1.25,r=e.completionTokens/1e6*o.output;return{inputCost:i,outputCost:r,totalCost:i+r,currency:"USD"}}static getCostPerToken(t){let e=b(t);return e?{input:e.input/1e6,output:e.output/1e6}:{input:0,output:0}}recordUsage(t,e,o,i,r){let p=s.calculateCost(e,o),n={timestamp:new Date,provider:t,model:e,usage:o,cost:p,requestId:i,metadata:r};return this.records.push(n),this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords)),this.checkAlerts(),p}getSummary(t){let e=new Date,o=this.getPeriodStart(e,t),i=e,r=this.records.filter(a=>a.timestamp>=o&&a.timestamp<=i),p={claude:0,"claude-code":0,codex:0,openai:0,ollama:0,openrouter:0,bedrock:0,"azure-openai":0,gemini:0,cognitum:0},n=l(),u=0,v=0;for(let a of r)u+=a.cost.totalCost,v+=a.usage.totalTokens,c(p,a.provider,a.cost.totalCost),c(n,a.model,a.cost.totalCost);return{period:t,periodStart:o,periodEnd:i,totalCost:u,byProvider:p,byModel:n,totalTokens:v,totalRequests:r.length}}getCurrentCost(t){return this.getSummary(t).totalCost}getTotalTokens(t){return this.getSummary(t).totalTokens}getUsageByProvider(t,e="all"){let o=this.getPeriodStart(new Date,e),i=this.records.filter(u=>u.provider===t&&u.timestamp>=o),r=l(),p=0,n=0;for(let u of i)p+=u.cost.totalCost,n+=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:p,totalTokens:n,totalRequests:i.length,models:r}}addAlert(t,e,o){let i=`alert-${Date.now()}-${T().slice(0,12)}`;return this.alerts.push({threshold:t,period:e,onThreshold:o,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 e of t)e.timestamp=new Date(e.timestamp),this.records.push(e);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,e,o){return s.calculateCost(t,{promptTokens:e,completionTokens:o,totalTokens:e+o})}wouldExceedLimit(t,e,o,i,r){let p=this.getCurrentCost(r),n=this.estimateCost(t,e,o);return p+n.totalCost>i}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}getPeriodStart(t,e){let o=new Date(t);switch(e){case"minute":o.setSeconds(0,0),o.setMinutes(o.getMinutes()-1);break;case"hour":o.setMinutes(0,0,0),o.setHours(o.getHours()-1);break;case"day":o.setHours(0,0,0,0);break;case"week":o.setHours(0,0,0,0),o.setDate(o.getDate()-7);break;case"month":o.setHours(0,0,0,0),o.setDate(1);break;case"all":return new Date(0)}return o}checkAlerts(){for(let t of this.alerts){if(!t.active)continue;let e=this.getSummary(t.period);if(e.totalCost>=t.threshold){t.active=!1;try{t.onThreshold(e)}catch(o){console.error("Cost alert callback error:",o)}}}}}});export{h as a,b,m as c,w as d,x as e,R 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.15.16");process.exit(0)}
2
+ import{g,n as f}from"./chunk-ZQ2XW3IP.js";import{a as l,d as c,e as k}from"./chunk-S75SOOZL.js";import{b as C}from"./chunk-AJMJNQMP.js";import{randomUUID as T}from"crypto";function b(s){let t=Object.hasOwn(h,s)?h[s]:void 0;if(t)return{input:t.input,output:t.output};let e=g(s);if(e.inputCostPerMillion>0||e.outputCostPerMillion>0)return{input:e.inputCostPerMillion,output:e.outputCostPerMillion}}function w(){return d||(d=new m),d}function x(){d&&(d.dispose(),d=void 0)}var h,m,d,R=C(()=>{f();k();h={"claude-sonnet-5":{input:2,output:10,provider:"claude"},"claude-opus-5":{input:5,output:25,provider:"claude"},"claude-opus-5-5":{input:4,output:20,provider:"claude"},"claude-fable-5-1":{input:10,output:50,provider:"claude"},"claude-fable-5":{input:10,output:50,provider:"claude"},"claude-opus-4-8":{input:5,output:25,provider:"claude"},"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-haiku-4-5":{input:1,output:5,provider:"claude"},"claude-opus-4-5-20251101":{input:5,output:25,provider:"claude"},"claude-opus-4-6":{input:5,output:25,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-6-astra":{input:10,output:50,provider:"openai"},"gpt-6-sol":{input:2,output:10,provider:"openai"},"gpt-6-luna":{input:.1,output:.5,provider:"openai"},"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-sonnet-5":{input:2,output:10,provider:"openrouter"},"anthropic/claude-opus-5":{input:5,output:25,provider:"openrouter"},"anthropic/claude-opus-5.5":{input:4,output:20,provider:"openrouter"},"anthropic/claude-haiku-4.5":{input:1,output:5,provider:"openrouter"},"openai/gpt-6-sol":{input:2,output:10,provider:"openrouter"},"openai/gpt-6-luna":{input:.1,output:.5,provider:"openrouter"},"google/gemini-3.8-flash":{input:.75,output:3.75,provider:"openrouter"},"meta-llama/llama-4-maverick":{input:.1875,output:.6525,provider:"openrouter"},"openai/gpt-oss-120b":{input:.15,output:.6,provider:"openrouter"},"qwen/qwen3-coder":{input:.3,output:1,provider:"openrouter"},"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-3.8-flash":{input:.75,output:3.75,provider:"gemini"},"gemini-3.5-flash":{input:1.5,output:9,provider:"gemini"},"gemini-3.1-pro-preview":{input:2,output:12,provider:"gemini"},"gemini-2.5-flash":{input:.3,output:2.5,provider:"gemini"},"gemini-2.5-pro":{input:1.25,output:10,provider:"gemini"},"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"}};m=class s{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(t=1e4){this.maxRecords=t}static calculateCost(t,e){let o=b(t);if(!o)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let i=e.promptTokens/1e6*o.input+(e.cacheReadTokens??0)/1e6*o.input*.1+(e.cacheCreationTokens??0)/1e6*o.input*1.25,r=e.completionTokens/1e6*o.output;return{inputCost:i,outputCost:r,totalCost:i+r,currency:"USD"}}static getCostPerToken(t){let e=b(t);return e?{input:e.input/1e6,output:e.output/1e6}:{input:0,output:0}}recordUsage(t,e,o,i,r){let p=s.calculateCost(e,o),n={timestamp:new Date,provider:t,model:e,usage:o,cost:p,requestId:i,metadata:r};return this.records.push(n),this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords)),this.checkAlerts(),p}getSummary(t){let e=new Date,o=this.getPeriodStart(e,t),i=e,r=this.records.filter(a=>a.timestamp>=o&&a.timestamp<=i),p={claude:0,"claude-code":0,codex:0,openai:0,ollama:0,openrouter:0,bedrock:0,"azure-openai":0,gemini:0,cognitum:0},n=l(),u=0,v=0;for(let a of r)u+=a.cost.totalCost,v+=a.usage.totalTokens,c(p,a.provider,a.cost.totalCost),c(n,a.model,a.cost.totalCost);return{period:t,periodStart:o,periodEnd:i,totalCost:u,byProvider:p,byModel:n,totalTokens:v,totalRequests:r.length}}getCurrentCost(t){return this.getSummary(t).totalCost}getTotalTokens(t){return this.getSummary(t).totalTokens}getUsageByProvider(t,e="all"){let o=this.getPeriodStart(new Date,e),i=this.records.filter(u=>u.provider===t&&u.timestamp>=o),r=l(),p=0,n=0;for(let u of i)p+=u.cost.totalCost,n+=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:p,totalTokens:n,totalRequests:i.length,models:r}}addAlert(t,e,o){let i=`alert-${Date.now()}-${T().slice(0,12)}`;return this.alerts.push({threshold:t,period:e,onThreshold:o,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 e of t)e.timestamp=new Date(e.timestamp),this.records.push(e);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,e,o){return s.calculateCost(t,{promptTokens:e,completionTokens:o,totalTokens:e+o})}wouldExceedLimit(t,e,o,i,r){let p=this.getCurrentCost(r),n=this.estimateCost(t,e,o);return p+n.totalCost>i}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}getPeriodStart(t,e){let o=new Date(t);switch(e){case"minute":o.setSeconds(0,0),o.setMinutes(o.getMinutes()-1);break;case"hour":o.setMinutes(0,0,0),o.setHours(o.getHours()-1);break;case"day":o.setHours(0,0,0,0);break;case"week":o.setHours(0,0,0,0),o.setDate(o.getDate()-7);break;case"month":o.setHours(0,0,0,0),o.setDate(1);break;case"all":return new Date(0)}return o}checkAlerts(){for(let t of this.alerts){if(!t.active)continue;let e=this.getSummary(t.period);if(e.totalCost>=t.threshold){t.active=!1;try{t.onThreshold(e)}catch(o){console.error("Cost alert callback error:",o)}}}}}});export{h as a,b,m as c,w as d,x as e,R as f};