agentic-qe 3.15.7 → 3.15.8

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 (371) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +122 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/cli/bundle.js +6 -6
  5. package/dist/cli/chunks/adapter-FC4EY447.js +2 -0
  6. package/dist/cli/chunks/{agent-booster-wasm-OS5G7KMQ.js → agent-booster-wasm-W3V5P7LE.js} +2 -2
  7. package/dist/cli/chunks/{agent-handler-PI4I7PME.js → agent-handler-2NQFHAWE.js} +2 -2
  8. package/dist/cli/chunks/{agent-memory-branch-J7TXHX4U.js → agent-memory-branch-457ECHHK.js} +2 -2
  9. package/dist/cli/chunks/aqe-learning-engine-AUAL6UBL.js +2 -0
  10. package/dist/cli/chunks/{arena-FXESDCFR.js → arena-IYBQ3GPY.js} +4 -4
  11. package/dist/cli/chunks/{arena-OWUGXKNT.js → arena-JV3WSEHU.js} +2 -2
  12. package/dist/cli/chunks/{audit-EPAWLYIZ.js → audit-5OS3T3K6.js} +3 -3
  13. package/dist/cli/chunks/base-2XML4WH7.js +2 -0
  14. package/dist/cli/chunks/{better-sqlite3-IYVR5EQY.js → better-sqlite3-IQKBFVAO.js} +2 -2
  15. package/dist/cli/chunks/{brain-handler-3W2E6TC6.js → brain-handler-KA3SGAFM.js} +3 -3
  16. package/dist/cli/chunks/{branch-enumerator-HU7VACJ4.js → branch-enumerator-QZDU2VOQ.js} +2 -2
  17. package/dist/cli/chunks/{browser-72XOR6E2.js → browser-ZL7OLKJQ.js} +2 -2
  18. package/dist/cli/chunks/browser-workflow-2IFEUAAK.js +2 -0
  19. package/dist/cli/chunks/{chunk-ZRLNACPY.js → chunk-22DOS3PM.js} +2 -2
  20. package/dist/cli/chunks/{chunk-QVG4ZDXX.js → chunk-2DPHFCMW.js} +2 -2
  21. package/dist/cli/chunks/{chunk-JFPXCQNP.js → chunk-2GSAAUW3.js} +1 -1
  22. package/dist/cli/chunks/{chunk-HPG7354V.js → chunk-2JCLACCS.js} +2 -2
  23. package/dist/cli/chunks/{chunk-44DPYNPE.js → chunk-2QRGIEQV.js} +1 -1
  24. package/dist/cli/chunks/{chunk-W4X2VTIY.js → chunk-2UN4JOTN.js} +2 -2
  25. package/dist/cli/chunks/{chunk-2423JAA5.js → chunk-2ZRNXEVI.js} +1 -1
  26. package/dist/cli/chunks/{chunk-CXTJ47QS.js → chunk-3LFLO2WK.js} +2 -2
  27. package/dist/cli/chunks/{chunk-QQT6QENQ.js → chunk-3N627QRU.js} +2 -2
  28. package/dist/cli/chunks/{chunk-LQOVA4YX.js → chunk-4C3RYBTT.js} +2 -2
  29. package/dist/cli/chunks/{chunk-5PBRBS7D.js → chunk-4C7KE2EL.js} +2 -2
  30. package/dist/cli/chunks/{chunk-J43DV3ME.js → chunk-4GUVVGJX.js} +1 -1
  31. package/dist/cli/chunks/{chunk-EL75G2A3.js → chunk-4GYFONJB.js} +1 -1
  32. package/dist/cli/chunks/{chunk-MJJC6HUK.js → chunk-4I35ARWW.js} +1 -1
  33. package/dist/cli/chunks/{chunk-6OS7HREG.js → chunk-4NTLGGXO.js} +1 -1
  34. package/dist/cli/chunks/{chunk-3RM46XFP.js → chunk-4TZLZRZ4.js} +1 -1
  35. package/dist/cli/chunks/{chunk-BTYKGVJ5.js → chunk-4YUBWU3E.js} +1 -1
  36. package/dist/cli/chunks/{chunk-6AYRAOCA.js → chunk-52YRSWPS.js} +2 -2
  37. package/dist/cli/chunks/{chunk-24CENUT4.js → chunk-5DZDLOY6.js} +3 -3
  38. package/dist/cli/chunks/{chunk-34JLY3U6.js → chunk-5MBNRTT5.js} +2 -2
  39. package/dist/cli/chunks/{chunk-SQHLC6I5.js → chunk-5ONJ7AV6.js} +1 -1
  40. package/dist/cli/chunks/{chunk-Y4SAWE45.js → chunk-5YOO5QSE.js} +1 -1
  41. package/dist/cli/chunks/{chunk-V2SAEMZY.js → chunk-62T7U25U.js} +1 -1
  42. package/dist/cli/chunks/{chunk-UIYKR2SA.js → chunk-6CKTLVYV.js} +2 -2
  43. package/dist/cli/chunks/{chunk-2E3XWKEU.js → chunk-6E7EOHMN.js} +2 -2
  44. package/dist/cli/chunks/{chunk-DGK6GQMO.js → chunk-6GIC2263.js} +2 -2
  45. package/dist/cli/chunks/{chunk-2RJYA6WK.js → chunk-767SR7WH.js} +2 -2
  46. package/dist/cli/chunks/{chunk-RCYLCA7E.js → chunk-7C6FMLQR.js} +2 -2
  47. package/dist/cli/chunks/{chunk-XTJMY3KS.js → chunk-7CVMT64N.js} +1 -1
  48. package/dist/cli/chunks/{chunk-JK6B3ULP.js → chunk-7DHSHD5B.js} +2 -2
  49. package/dist/cli/chunks/{chunk-JYXOFN3E.js → chunk-7H3GNRNA.js} +2 -2
  50. package/dist/cli/chunks/{chunk-7EX4DEQR.js → chunk-7SLEUVPZ.js} +2 -2
  51. package/dist/cli/chunks/{chunk-ZLVQSEZK.js → chunk-7XGM7Q2N.js} +2 -2
  52. package/dist/cli/chunks/{chunk-RNYX4CPI.js → chunk-A2UGPKCS.js} +2 -2
  53. package/dist/cli/chunks/{chunk-K7W55B7Q.js → chunk-A6GCO6ZU.js} +2 -2
  54. package/dist/cli/chunks/{chunk-C2MDBBFF.js → chunk-BEVWCF3Q.js} +3 -3
  55. package/dist/cli/chunks/{chunk-PZG3542B.js → chunk-BLZEOGQE.js} +2 -2
  56. package/dist/cli/chunks/{chunk-6PKCQXEW.js → chunk-BQUIZ5QT.js} +2 -2
  57. package/dist/cli/chunks/{chunk-JY4AIEZ7.js → chunk-BTMEOZYY.js} +1 -1
  58. package/dist/cli/chunks/{chunk-OA4GR3EZ.js → chunk-CDLG3Q2O.js} +2 -2
  59. package/dist/cli/chunks/{chunk-FVBFASOD.js → chunk-CQ3SBRDP.js} +2 -2
  60. package/dist/cli/chunks/{chunk-ZUMDDMDE.js → chunk-CQ5G64EA.js} +2 -2
  61. package/dist/cli/chunks/{chunk-ED32XJ5R.js → chunk-CRUQ6RXU.js} +2 -2
  62. package/dist/cli/chunks/{chunk-ZTMZFF25.js → chunk-D4IBIMWI.js} +2 -2
  63. package/dist/cli/chunks/{chunk-QNQSM2OG.js → chunk-D4O3TJI7.js} +2 -2
  64. package/dist/cli/chunks/{chunk-IYQ7XNE5.js → chunk-DAFMHM64.js} +2 -2
  65. package/dist/cli/chunks/{chunk-5KS7HA37.js → chunk-DCYUHCPK.js} +1 -1
  66. package/dist/cli/chunks/{chunk-Q2T5FXEA.js → chunk-DKFSCJEF.js} +2 -2
  67. package/dist/cli/chunks/{chunk-ONVALAZN.js → chunk-DN3AKAPY.js} +2 -2
  68. package/dist/cli/chunks/{chunk-LDXQRNTT.js → chunk-DY37YMMQ.js} +1 -1
  69. package/dist/cli/chunks/{chunk-NZQPP533.js → chunk-EUVSSIGR.js} +3 -3
  70. package/dist/cli/chunks/{chunk-V5NGBQAQ.js → chunk-FAYXES7R.js} +2 -2
  71. package/dist/cli/chunks/{chunk-EV2BYY6T.js → chunk-FEN2DHFM.js} +1 -1
  72. package/dist/cli/chunks/{chunk-TU4LIIOP.js → chunk-FEPFXXI7.js} +2 -2
  73. package/dist/cli/chunks/{chunk-Y6A46M3B.js → chunk-FJAO4UX2.js} +2 -2
  74. package/dist/cli/chunks/{chunk-4G2VNW4C.js → chunk-FWXNFPLS.js} +2 -2
  75. package/dist/cli/chunks/{chunk-DVPGBDBP.js → chunk-G6CLO74Q.js} +3 -3
  76. package/dist/cli/chunks/{chunk-RORZ5O5Z.js → chunk-G77Q22EN.js} +2 -2
  77. package/dist/cli/chunks/{chunk-G762PEFO.js → chunk-GENNJRNK.js} +3 -3
  78. package/dist/cli/chunks/{chunk-XXAVQACL.js → chunk-GGSTLKY5.js} +1 -1
  79. package/dist/cli/chunks/{chunk-BB7OLQKO.js → chunk-GSOK4M6V.js} +1 -1
  80. package/dist/cli/chunks/{chunk-PEKDSJBC.js → chunk-HI6OBDDY.js} +2 -2
  81. package/dist/cli/chunks/{chunk-MMXG3LL6.js → chunk-HNGNRIZZ.js} +2 -2
  82. package/dist/cli/chunks/{chunk-N4PMPSJJ.js → chunk-HXCGV5UJ.js} +2 -2
  83. package/dist/cli/chunks/{chunk-YDZJWDR6.js → chunk-I4U7YCXG.js} +3 -3
  84. package/dist/cli/chunks/{chunk-I7H4IP7T.js → chunk-I77D65X5.js} +2 -2
  85. package/dist/cli/chunks/{chunk-WXI2STKQ.js → chunk-IJSFZO7P.js} +2 -2
  86. package/dist/cli/chunks/{chunk-WTLIEBDH.js → chunk-IMSRWNWF.js} +1 -1
  87. package/dist/cli/chunks/{chunk-634D2ENF.js → chunk-J6LL25QJ.js} +2 -2
  88. package/dist/cli/chunks/{chunk-LVEX4GID.js → chunk-J7FLNP5L.js} +2 -2
  89. package/dist/cli/chunks/{chunk-CIFWOMNX.js → chunk-J7RCI25Q.js} +1 -1
  90. package/dist/cli/chunks/{chunk-HLZATDD2.js → chunk-JFWQFB3S.js} +2 -2
  91. package/dist/cli/chunks/{chunk-3JD2USUH.js → chunk-JLTGO5BB.js} +2 -2
  92. package/dist/cli/chunks/{chunk-SX2YSHE7.js → chunk-JWPYMRIX.js} +1 -1
  93. package/dist/cli/chunks/{chunk-4DIZ5BT6.js → chunk-K4N2MBCE.js} +2 -2
  94. package/dist/cli/chunks/{chunk-HSDOOFV7.js → chunk-K5R3WUJP.js} +1 -1
  95. package/dist/cli/chunks/{chunk-LP4AS2E4.js → chunk-KITKQUBX.js} +1 -1
  96. package/dist/cli/chunks/{chunk-VCA6YYII.js → chunk-KJNUETCB.js} +1 -1
  97. package/dist/cli/chunks/{chunk-PXZKPUW6.js → chunk-KMVFBYJO.js} +2 -2
  98. package/dist/cli/chunks/{chunk-IWQQIXHO.js → chunk-KMZW2P3R.js} +2 -2
  99. package/dist/cli/chunks/{chunk-2AYBYXOA.js → chunk-KNHLOANK.js} +2 -2
  100. package/dist/cli/chunks/{chunk-JY4WLN3K.js → chunk-KNQUHGNY.js} +2 -2
  101. package/dist/cli/chunks/{chunk-LGBN7TKC.js → chunk-KVMKYUOE.js} +2 -2
  102. package/dist/cli/chunks/{chunk-YK3NOC2R.js → chunk-LHRVSK44.js} +2 -2
  103. package/dist/cli/chunks/{chunk-IARSGAG7.js → chunk-LPSMVBB3.js} +2 -2
  104. package/dist/cli/chunks/{chunk-CWPRU7ZI.js → chunk-LVHZK7GW.js} +2 -2
  105. package/dist/cli/chunks/{chunk-T3ZDVU6F.js → chunk-LZWBUVCK.js} +2 -2
  106. package/dist/cli/chunks/{chunk-MNCF643K.js → chunk-MMY52Y6R.js} +2 -2
  107. package/dist/cli/chunks/{chunk-YUC7RJGR.js → chunk-MUDBF2JC.js} +1 -1
  108. package/dist/cli/chunks/{chunk-XEWXYGJI.js → chunk-MV4S3TEC.js} +2 -2
  109. package/dist/cli/chunks/{chunk-MRHM4COP.js → chunk-NF63NHJH.js} +2 -2
  110. package/dist/cli/chunks/{chunk-KPOPBUUJ.js → chunk-NHOMVBCI.js} +2 -2
  111. package/dist/cli/chunks/{chunk-RXAFLK34.js → chunk-NLYUC63R.js} +2 -2
  112. package/dist/cli/chunks/{chunk-MHZPC4HJ.js → chunk-NQDYOF35.js} +2 -2
  113. package/dist/cli/chunks/{chunk-OJEZNLB6.js → chunk-NW7HTOSN.js} +2 -2
  114. package/dist/cli/chunks/{chunk-6JT73S5B.js → chunk-NWFBF3KT.js} +1 -1
  115. package/dist/cli/chunks/{chunk-REEIFA6A.js → chunk-NZATJ2C6.js} +2 -2
  116. package/dist/cli/chunks/{chunk-5KCBX225.js → chunk-O4RRVTXN.js} +2 -2
  117. package/dist/cli/chunks/{chunk-6BO3WCK7.js → chunk-OCLAMZJG.js} +2 -2
  118. package/dist/cli/chunks/{chunk-ICPALF4Q.js → chunk-OJWEZYLR.js} +2 -2
  119. package/dist/cli/chunks/{chunk-Z3VJLWRR.js → chunk-OWBFVAEH.js} +2 -2
  120. package/dist/cli/chunks/{chunk-LDZWIV2O.js → chunk-P2EA62YS.js} +1 -1
  121. package/dist/cli/chunks/{chunk-IC2WSSD5.js → chunk-P4UT4LBE.js} +3 -3
  122. package/dist/cli/chunks/{chunk-FTTFJ7SJ.js → chunk-PICEGWGB.js} +1 -1
  123. package/dist/cli/chunks/{chunk-AXO7OOOA.js → chunk-PIEKGKW6.js} +2 -2
  124. package/dist/cli/chunks/{chunk-PQV7E7XH.js → chunk-PJGQ2TKN.js} +2 -2
  125. package/dist/cli/chunks/{chunk-7UCVYYWL.js → chunk-PPIM7B5G.js} +2 -2
  126. package/dist/cli/chunks/{chunk-UBYCR3O4.js → chunk-PUYQ6EKC.js} +2 -2
  127. package/dist/cli/chunks/{chunk-2YVJ5OUL.js → chunk-PWA6XBW4.js} +8 -8
  128. package/dist/cli/chunks/{chunk-VNW5Q2CX.js → chunk-PZ7FJ4UG.js} +2 -2
  129. package/dist/cli/chunks/{chunk-DCJW2DPL.js → chunk-QFYUZYRA.js} +4 -4
  130. package/dist/cli/chunks/{chunk-F62EKVVC.js → chunk-R2NHGESM.js} +2 -2
  131. package/dist/cli/chunks/{chunk-HTWIGQL4.js → chunk-RG42LDOB.js} +2 -2
  132. package/dist/cli/chunks/{chunk-UCLN6AME.js → chunk-RSMPJWQH.js} +1 -1
  133. package/dist/cli/chunks/{chunk-HZFT3P5B.js → chunk-SFPGLUXS.js} +1 -1
  134. package/dist/cli/chunks/{chunk-5Q22XPTH.js → chunk-SHEVM5PF.js} +2 -2
  135. package/dist/cli/chunks/{chunk-B7M323VL.js → chunk-SJMZZMHP.js} +2 -2
  136. package/dist/cli/chunks/{chunk-PG64YV6C.js → chunk-ST7ASEJO.js} +11 -11
  137. package/dist/cli/chunks/{chunk-WUV5RZUI.js → chunk-SWY6KGMF.js} +2 -2
  138. package/dist/cli/chunks/{chunk-MDC4G323.js → chunk-T2TDTBFV.js} +1 -1
  139. package/dist/cli/chunks/{chunk-6FEQ73BF.js → chunk-TC52M542.js} +2 -2
  140. package/dist/cli/chunks/{chunk-PTK66HEY.js → chunk-TMNEK7TP.js} +2 -2
  141. package/dist/cli/chunks/{chunk-UY3REQOK.js → chunk-U3BWBP6B.js} +2 -2
  142. package/dist/cli/chunks/{chunk-PUECC4WI.js → chunk-U7CIY3YR.js} +2 -2
  143. package/dist/cli/chunks/{chunk-LMEU64TR.js → chunk-UDCYQLTD.js} +2 -2
  144. package/dist/cli/chunks/{chunk-MNZFEIE5.js → chunk-UKKFZJME.js} +1 -1
  145. package/dist/cli/chunks/{chunk-BTIBXGVQ.js → chunk-UQLAN5TX.js} +4 -4
  146. package/dist/cli/chunks/{chunk-UUHIEM2M.js → chunk-UTFMMZ57.js} +3 -3
  147. package/dist/cli/chunks/{chunk-C2CUPJGR.js → chunk-UTNKMPTC.js} +1 -1
  148. package/dist/cli/chunks/{chunk-ECSLJJOQ.js → chunk-V4QJ3MMT.js} +1 -1
  149. package/dist/cli/chunks/{chunk-56ZKQYZY.js → chunk-V7VZSNDK.js} +3 -3
  150. package/dist/cli/chunks/{chunk-AAA4SHEG.js → chunk-VKFVJCIH.js} +1 -1
  151. package/dist/cli/chunks/{chunk-VKPKYMCT.js → chunk-VQRBBR27.js} +2 -2
  152. package/dist/cli/chunks/{chunk-SSP2B2WR.js → chunk-VVK4ECVJ.js} +2 -2
  153. package/dist/cli/chunks/{chunk-T6W5APYP.js → chunk-VWRNG3UK.js} +1 -1
  154. package/dist/cli/chunks/{chunk-YFOBQSOW.js → chunk-VWSGWYRB.js} +2 -2
  155. package/dist/cli/chunks/{chunk-PYHYOKYT.js → chunk-W5A36V3Z.js} +2 -2
  156. package/dist/cli/chunks/{chunk-EB2PP6X2.js → chunk-WAWKAYPY.js} +1 -1
  157. package/dist/cli/chunks/{chunk-QWLTHFZW.js → chunk-WLXGUQOZ.js} +2 -2
  158. package/dist/cli/chunks/{chunk-JPHDMHFG.js → chunk-X3HM7SV4.js} +2 -2
  159. package/dist/cli/chunks/chunk-X6VYQVUM.js +2 -0
  160. package/dist/cli/chunks/{chunk-MKFQNCXI.js → chunk-X7ZQIFES.js} +2 -2
  161. package/dist/cli/chunks/{chunk-GY2SAIXP.js → chunk-XOOBLZXR.js} +2 -2
  162. package/dist/cli/chunks/{chunk-MQ6OF6DU.js → chunk-XZQVC3GD.js} +1 -1
  163. package/dist/cli/chunks/{chunk-M63QB466.js → chunk-Y5ZBF7MA.js} +2 -2
  164. package/dist/cli/chunks/{chunk-EDU72RTW.js → chunk-YNQPHRUZ.js} +1 -1
  165. package/dist/cli/chunks/{chunk-RRPYWBFX.js → chunk-YRH7KMTU.js} +2 -2
  166. package/dist/cli/chunks/{chunk-CG5DZCOZ.js → chunk-YTYS2XSY.js} +1 -1
  167. package/dist/cli/chunks/{chunk-G7YTZTGU.js → chunk-YUP3APSN.js} +1 -1
  168. package/dist/cli/chunks/{chunk-HXBAQKMH.js → chunk-YVWMJZ6O.js} +2 -2
  169. package/dist/cli/chunks/{chunk-QJE6ZW2X.js → chunk-Z3LDUPLQ.js} +2 -2
  170. package/dist/cli/chunks/{chunk-JVYPXW6Y.js → chunk-ZBI7PJFX.js} +2 -2
  171. package/dist/cli/chunks/{chunk-XNSQZ3O7.js → chunk-ZG7UKWBB.js} +2 -2
  172. package/dist/cli/chunks/{chunk-H4WHDFB5.js → chunk-ZOHS32SI.js} +2 -2
  173. package/dist/cli/chunks/{chunk-J26GADQE.js → chunk-ZOVAZTXE.js} +342 -342
  174. package/dist/cli/chunks/{chunk-VUFRTGML.js → chunk-ZWMFKZEQ.js} +2 -2
  175. package/dist/cli/chunks/{ci-5HEXJZ2C.js → ci-7NUCRGWO.js} +2 -2
  176. package/dist/cli/chunks/{ci-config-WU4NPDAM.js → ci-config-VQVECCFI.js} +2 -2
  177. package/dist/cli/chunks/{ci-output-BJQVXX5E.js → ci-output-P7GQ6TKF.js} +2 -2
  178. package/dist/cli/chunks/{circuit-breaker-3BMGTQCB.js → circuit-breaker-5YP6N6HE.js} +2 -2
  179. package/dist/cli/chunks/{claude-flow-setup-GVDGJWMU.js → claude-flow-setup-W5H7CMU6.js} +2 -2
  180. package/dist/cli/chunks/client-RFUSQRUZ.js +2 -0
  181. package/dist/cli/chunks/{cline-installer-V4MRGWVA.js → cline-installer-OYANSZ54.js} +2 -2
  182. package/dist/cli/chunks/{code-A3TGQPEO.js → code-OMT4UEZI.js} +3 -3
  183. package/dist/cli/chunks/{code-index-extractor-YJQSYWD3.js → code-index-extractor-M2JEWKNF.js} +2 -2
  184. package/dist/cli/chunks/{codex-installer-7N7UQPAH.js → codex-installer-YBS6N5O3.js} +2 -2
  185. package/dist/cli/chunks/{completions-PPGVYLZS.js → completions-U7GS5RG6.js} +2 -2
  186. package/dist/cli/chunks/{complexity-analyzer-XZTFLYV5.js → complexity-analyzer-QSXPIUIU.js} +2 -2
  187. package/dist/cli/chunks/{continuedev-installer-Z5I57RAH.js → continuedev-installer-W5TTT743.js} +2 -2
  188. package/dist/cli/chunks/{copilot-installer-F5YZ6BHB.js → copilot-installer-KC2RT24C.js} +2 -2
  189. package/dist/cli/chunks/core-handlers-ZC7QB432.js +2 -0
  190. package/dist/cli/chunks/{cost-tracker-GO33ZQAP.js → cost-tracker-OQPVR6V4.js} +2 -2
  191. package/dist/cli/chunks/{coverage-GSHKLY74.js → coverage-TCO2A2NX.js} +3 -3
  192. package/dist/cli/chunks/cross-domain-router-GRBK7YFZ.js +2 -0
  193. package/dist/cli/chunks/{cursor-installer-JJ7IVJZB.js → cursor-installer-MH7GWD4L.js} +2 -2
  194. package/dist/cli/chunks/daemon-JER6HE2J.js +12 -0
  195. package/dist/cli/chunks/{daemon-IRL7QRNE.js → daemon-UJEARJZ2.js} +3 -3
  196. package/dist/cli/chunks/{dag-attention-scheduler-ORXSUHPA.js → dag-attention-scheduler-F3SUJU5O.js} +2 -2
  197. package/dist/cli/chunks/{detect-RHU62KRI.js → detect-5QTCRB32.js} +2 -2
  198. package/dist/cli/chunks/{dist-node-3VKV4Z6C.js → dist-node-XKZPHDBO.js} +2 -2
  199. package/dist/cli/chunks/{domain-handler-SFIML4FK.js → domain-handler-V3UEADKW.js} +2 -2
  200. package/dist/cli/chunks/{domain-plugins-CJ4FA3OC.js → domain-plugins-7PES4UHZ.js} +2 -2
  201. package/dist/cli/chunks/{domain-transfer-BCRKPCAA.js → domain-transfer-NF7UJW7B.js} +2 -2
  202. package/dist/cli/chunks/dream-VALD726W.js +2 -0
  203. package/dist/cli/chunks/{embed-and-insert-pattern-VL3HFLPV.js → embed-and-insert-pattern-D2HWORHF.js} +2 -2
  204. package/dist/cli/chunks/{eval-GGKRI4P5.js → eval-UF2UBAUC.js} +2 -2
  205. package/dist/cli/chunks/{experience-capture-middleware-F72TIRQY.js → experience-capture-middleware-2OUCEHHM.js} +3 -3
  206. package/dist/cli/chunks/{fast-paths-7KOOF3MA.js → fast-paths-KV5DKKHC.js} +2 -2
  207. package/dist/cli/chunks/{feature-flags-FNHBTHBH.js → feature-flags-6YWMTNO5.js} +2 -2
  208. package/dist/cli/chunks/{feature-flags-IOZEWWFU.js → feature-flags-MTW6NMR3.js} +2 -2
  209. package/dist/cli/chunks/file-discovery-VL73ASNI.js +2 -0
  210. package/dist/cli/chunks/{fleet-QX5KXTRC.js → fleet-GJ66QFXK.js} +3 -3
  211. package/dist/cli/chunks/{gnn-wrapper-OH2DOQP7.js → gnn-wrapper-52V6ANOY.js} +2 -2
  212. package/dist/cli/chunks/{heartbeat-handler-W67NXTNE.js → heartbeat-handler-X7NHNRC7.js} +4 -4
  213. package/dist/cli/chunks/heartbeat-scheduler-FSX7A3ZA.js +2 -0
  214. package/dist/cli/chunks/hnsw-adapter-UX2QT6RL.js +2 -0
  215. package/dist/cli/chunks/hnsw-index-WRDDAMXH.js +2 -0
  216. package/dist/cli/chunks/{hnsw-legacy-bridge-6MLLOGOE.js → hnsw-legacy-bridge-DZBE3KMK.js} +2 -2
  217. package/dist/cli/chunks/{hnswlib-node-4UDISJ3G.js → hnswlib-node-2AWWUJAZ.js} +2 -2
  218. package/dist/cli/chunks/{hooks-NOQJWQ4P.js → hooks-XLPVROL3.js} +10 -10
  219. package/dist/cli/chunks/hybrid-backend-O67NGIB5.js +2 -0
  220. package/dist/cli/chunks/{hypergraph-engine-2OD3APVP.js → hypergraph-engine-6TI7YP6P.js} +2 -2
  221. package/dist/cli/chunks/{hypergraph-handler-5AZGMBUM.js → hypergraph-handler-DBIBBOXS.js} +3 -3
  222. package/dist/cli/chunks/impact-analyzer-6VXWWYWM.js +2 -0
  223. package/dist/cli/chunks/{init-guard-SMGJ45PW.js → init-guard-OSO6MIDD.js} +2 -2
  224. package/dist/cli/chunks/{init-handler-5T4MP2NM.js → init-handler-7S7IHMUF.js} +6 -6
  225. package/dist/cli/chunks/init-wizard-VH34J4TL.js +2 -0
  226. package/dist/cli/chunks/kernel-KJD24NO7.js +2 -0
  227. package/dist/cli/chunks/{kilocode-installer-RLZYLVQJ.js → kilocode-installer-2KBRFXMA.js} +2 -2
  228. package/dist/cli/chunks/{kiro-installer-LFZOC7VD.js → kiro-installer-5VFR4OQZ.js} +2 -2
  229. package/dist/cli/chunks/knowledge-graph-343O2HEZ.js +2 -0
  230. package/dist/cli/chunks/{learning-XRPGLUWR.js → learning-G5NHL3DV.js} +3 -3
  231. package/dist/cli/chunks/{llm-router-OMK5HYPH.js → llm-router-4EAPPMHS.js} +4 -4
  232. package/dist/cli/chunks/llm-router-service-2M4BT2AO.js +2 -0
  233. package/dist/cli/chunks/{load-XADC7KCU.js → load-UYMZPEY6.js} +2 -2
  234. package/dist/cli/chunks/load-test-OTQ2JQ5F.js +2 -0
  235. package/dist/cli/chunks/{mcp-PIBKSSVU.js → mcp-NOTDZBW5.js} +2 -2
  236. package/dist/cli/chunks/{memory-AP7EZERS.js → memory-QL53YIHP.js} +5 -5
  237. package/dist/cli/chunks/memory-backend-4QSNRRV6.js +2 -0
  238. package/dist/cli/chunks/{memory-handlers-MOFDNB6E.js → memory-handlers-YFFYRSM6.js} +2 -2
  239. package/dist/cli/chunks/{multi-model-executor-7JJ2FZ33.js → multi-model-executor-PDDDXF2B.js} +2 -2
  240. package/dist/cli/chunks/{opencode-installer-ZZZ6EBYJ.js → opencode-installer-75D2SKOT.js} +2 -2
  241. package/dist/cli/chunks/{orchestrator-2H2YKSGJ.js → orchestrator-3WIZBV4T.js} +5 -5
  242. package/dist/cli/chunks/pattern-null-store-5USH5MNR.js +2 -0
  243. package/dist/cli/chunks/{pattern-usage-recorder-7MJJWC2Z.js → pattern-usage-recorder-TEX2JGHA.js} +2 -2
  244. package/dist/cli/chunks/{pipeline-LIE5BWQY.js → pipeline-7ATPA6LU.js} +2 -2
  245. package/dist/cli/chunks/{platform-SMYUNLGX.js → platform-WPSKRJE7.js} +2 -2
  246. package/dist/cli/chunks/{plugin-LJDIXQNT.js → plugin-UUFOVVMU.js} +2 -2
  247. package/dist/cli/chunks/{prime-radiant-advanced-wasm-RIDNE5D2.js → prime-radiant-advanced-wasm-PDFSYWKZ.js} +2 -2
  248. package/dist/cli/chunks/project-root-SRTA6TBL.js +2 -0
  249. package/dist/cli/chunks/protocol-executor-4WYPCNBS.js +2 -0
  250. package/dist/cli/chunks/{protocol-handler-YVM66DLI.js → protocol-handler-3VRYRIQB.js} +2 -2
  251. package/dist/cli/chunks/{prove-ZBDT52GD.js → prove-2NAUROGF.js} +2 -2
  252. package/dist/cli/chunks/qe-reasoning-bank-I4D6SFS4.js +2 -0
  253. package/dist/cli/chunks/{quality-DUKXGDDO.js → quality-ZIEI2WGA.js} +2 -2
  254. package/dist/cli/chunks/{quality-gate-SM3RXF4V.js → quality-gate-KWJO4SWQ.js} +3 -3
  255. package/dist/cli/chunks/queen-coordinator-24UMTZTE.js +2 -0
  256. package/dist/cli/chunks/{real-embeddings-4QLQZDB5.js → real-embeddings-TSZ4UIAE.js} +2 -2
  257. package/dist/cli/chunks/{ref-validation-M3EO32YQ.js → ref-validation-DWFFRETJ.js} +2 -2
  258. package/dist/cli/chunks/{roocode-installer-S6Q5OLV5.js → roocode-installer-XTZHLUBO.js} +2 -2
  259. package/dist/cli/chunks/router-AUD4GATI.js +2 -0
  260. package/dist/cli/chunks/routing-feedback-2FE6SIKQ.js +2 -0
  261. package/dist/cli/chunks/{routing-handler-55FMUACP.js → routing-handler-GG525TDM.js} +2 -2
  262. package/dist/cli/chunks/{ruvector-commands-QATKAAPK.js → ruvector-commands-QKRJDM7Z.js} +2 -2
  263. package/dist/cli/chunks/rvf-dual-writer-P5LEUF25.js +2 -0
  264. package/dist/cli/chunks/rvf-migration-adapter-ZCYD5YJS.js +2 -0
  265. package/dist/cli/chunks/{rvf-migration-coordinator-RFXFU6JD.js → rvf-migration-coordinator-FF52OS6Q.js} +2 -2
  266. package/dist/cli/chunks/rvf-native-adapter-QGV6BW2W.js +2 -0
  267. package/dist/cli/chunks/{rvf-store-integrity-PKDVXQAW.js → rvf-store-integrity-M6DXTAZ4.js} +2 -2
  268. package/dist/cli/chunks/safe-db-Q6JUKG2A.js +2 -0
  269. package/dist/cli/chunks/schedule-44OSMGE5.js +2 -0
  270. package/dist/cli/chunks/scheduler-V3HO2QQT.js +2 -0
  271. package/dist/cli/chunks/{security-CMRB6WA3.js → security-EHXSW22U.js} +3 -3
  272. package/dist/cli/chunks/{shared-rvf-adapter-YHLLNFHF.js → shared-rvf-adapter-6EH7UVJL.js} +2 -2
  273. package/dist/cli/chunks/{shared-rvf-dual-writer-4BGDVPQ7.js → shared-rvf-dual-writer-WML274E7.js} +2 -2
  274. package/dist/cli/chunks/sqlite-persistence-N5T7DWMR.js +2 -0
  275. package/dist/cli/chunks/{standalone-memory-LUHKQAGM.js → standalone-memory-C7QKAXS4.js} +2 -2
  276. package/dist/cli/chunks/{status-handler-S6S5PNR7.js → status-handler-VLI7MRLM.js} +2 -2
  277. package/dist/cli/chunks/{structural-health-PQ7NZAJ4.js → structural-health-3LPG6MQN.js} +2 -2
  278. package/dist/cli/chunks/{sync-S744AEJC.js → sync-4IMMQEPT.js} +2 -2
  279. package/dist/cli/chunks/{sync-Q6KRQXU6.js → sync-JFJEJBVK.js} +2 -2
  280. package/dist/cli/chunks/{task-handler-GAMGEHUW.js → task-handler-IED3K6E4.js} +2 -2
  281. package/dist/cli/chunks/{task-handlers-6CRDEELN.js → task-handlers-FH6DNTHW.js} +3 -3
  282. package/dist/cli/chunks/{test-FNH67DBK.js → test-GPKT3CKZ.js} +4 -4
  283. package/dist/cli/chunks/{test-scheduling-NZA5SHK6.js → test-scheduling-Z42XXZP6.js} +3 -3
  284. package/dist/cli/chunks/{token-bootstrap-CXKG55JD.js → token-bootstrap-HMM3AHXM.js} +2 -2
  285. package/dist/cli/chunks/{token-usage-M7WWEDJX.js → token-usage-6Y2ERYIY.js} +2 -2
  286. package/dist/cli/chunks/{transformers-2IFMCK6A.js → transformers-MB63T2XO.js} +2 -2
  287. package/dist/cli/chunks/{tree-sitter-wasm-parser-NMNA6RJC.js → tree-sitter-wasm-parser-56GDQCMR.js} +2 -2
  288. package/dist/cli/chunks/{types-N7FWTOLD.js → types-J4J6QV3I.js} +2 -2
  289. package/dist/cli/chunks/unified-memory-RQ3Q4CU3.js +2 -0
  290. package/dist/cli/chunks/unified-memory-hnsw-ZOP5FEYX.js +2 -0
  291. package/dist/cli/chunks/unified-persistence-72OCJJKK.js +2 -0
  292. package/dist/cli/chunks/{upgrade-KDB5RGL7.js → upgrade-U4XU7LFM.js} +2 -2
  293. package/dist/cli/chunks/{validate-KMUV5FUA.js → validate-B57HA4YK.js} +2 -2
  294. package/dist/cli/chunks/{validate-swarm-ANZWRCJU.js → validate-swarm-UPPA4M6T.js} +2 -2
  295. package/dist/cli/chunks/visual-security-7F5UV23J.js +2 -0
  296. package/dist/cli/chunks/{web-tree-sitter-SXXC4NMS.js → web-tree-sitter-GDZMUKOZ.js} +2 -2
  297. package/dist/cli/chunks/{windsurf-installer-2LWSKMBU.js → windsurf-installer-VJRWCHXP.js} +2 -2
  298. package/dist/cli/chunks/witness-chain-KZ57QUFE.js +2 -0
  299. package/dist/cli/chunks/{witness-chain-JJMSJFZP.js → witness-chain-LFASSMZK.js} +2 -2
  300. package/dist/cli/chunks/{witness-chain-repair-OX7VFW6T.js → witness-chain-repair-TPHN4DXN.js} +2 -2
  301. package/dist/cli/chunks/{witness-chain-verifier-QLSMXHAZ.js → witness-chain-verifier-Z23FVABW.js} +2 -2
  302. package/dist/cli/chunks/{witness-key-manager-3DS4L7LE.js → witness-key-manager-745MJ7WO.js} +2 -2
  303. package/dist/cli/chunks/{workflow-ARWAMHD3.js → workflow-T245QNQM.js} +4 -4
  304. package/dist/cli/chunks/workflow-orchestrator-ZNWEUYBN.js +2 -0
  305. package/dist/cli/chunks/{wrappers-J6KGTUSJ.js → wrappers-WCAYIQUX.js} +2 -2
  306. package/dist/coordination/protocols/learning-consolidation.js +6 -12
  307. package/dist/domains/coverage-analysis/collected-metrics.js +2 -1
  308. package/dist/domains/learning-optimization/active-patterns.d.ts +55 -0
  309. package/dist/domains/learning-optimization/active-patterns.js +77 -0
  310. package/dist/domains/learning-optimization/coordinator.js +12 -9
  311. package/dist/domains/learning-optimization/services/learning-coordinator.js +15 -17
  312. package/dist/domains/test-execution/services/retry-handler.js +18 -2
  313. package/dist/learning/dream/dream-engine.d.ts +27 -1
  314. package/dist/learning/dream/dream-engine.js +56 -2
  315. package/dist/learning/dream/rvcow-branch-manager.d.ts +8 -0
  316. package/dist/learning/dream/rvcow-branch-manager.js +8 -0
  317. package/dist/learning/dream/speculative-dreamer.d.ts +8 -0
  318. package/dist/learning/dream/speculative-dreamer.js +8 -0
  319. package/dist/mcp/background-workers.d.ts +15 -0
  320. package/dist/mcp/background-workers.js +71 -0
  321. package/dist/mcp/bundle.js +409 -406
  322. package/dist/mcp/entry.js +4 -49
  323. package/dist/workers/daemon.d.ts +5 -0
  324. package/dist/workers/daemon.js +16 -2
  325. package/dist/workers/worker-env.d.ts +45 -0
  326. package/dist/workers/worker-env.js +76 -0
  327. package/dist/workers/workers/learning-consolidation.d.ts +20 -0
  328. package/dist/workers/workers/learning-consolidation.js +53 -22
  329. package/package.json +1 -1
  330. package/dist/cli/chunks/adapter-PEOUNYXJ.js +0 -2
  331. package/dist/cli/chunks/aqe-learning-engine-DHKZI5RX.js +0 -2
  332. package/dist/cli/chunks/base-QZWK3D5P.js +0 -2
  333. package/dist/cli/chunks/browser-workflow-ITPX72RX.js +0 -2
  334. package/dist/cli/chunks/chunk-VJRZFWR5.js +0 -2
  335. package/dist/cli/chunks/client-S7GNYTZ5.js +0 -2
  336. package/dist/cli/chunks/core-handlers-CUEPOQIO.js +0 -2
  337. package/dist/cli/chunks/cross-domain-router-CXN5QFEV.js +0 -2
  338. package/dist/cli/chunks/daemon-3DQCKRYO.js +0 -10
  339. package/dist/cli/chunks/dream-5AUNJW24.js +0 -2
  340. package/dist/cli/chunks/file-discovery-AYWF357I.js +0 -2
  341. package/dist/cli/chunks/heartbeat-scheduler-7ZIDVXIP.js +0 -2
  342. package/dist/cli/chunks/hnsw-adapter-P77OC7FM.js +0 -2
  343. package/dist/cli/chunks/hnsw-index-3LBOTQAW.js +0 -2
  344. package/dist/cli/chunks/hybrid-backend-LOM54PDD.js +0 -2
  345. package/dist/cli/chunks/impact-analyzer-QSDJVBPS.js +0 -2
  346. package/dist/cli/chunks/init-wizard-MK2325JJ.js +0 -2
  347. package/dist/cli/chunks/kernel-2NJQQ2KT.js +0 -2
  348. package/dist/cli/chunks/knowledge-graph-SDISHO62.js +0 -2
  349. package/dist/cli/chunks/llm-router-service-YTCMRBAN.js +0 -2
  350. package/dist/cli/chunks/load-test-RPKHLBCC.js +0 -2
  351. package/dist/cli/chunks/memory-backend-BZXFO4JZ.js +0 -2
  352. package/dist/cli/chunks/pattern-null-store-4PRPIOR6.js +0 -2
  353. package/dist/cli/chunks/project-root-NBIQF63D.js +0 -2
  354. package/dist/cli/chunks/protocol-executor-BRPGIYWQ.js +0 -2
  355. package/dist/cli/chunks/qe-reasoning-bank-GDZACWKW.js +0 -2
  356. package/dist/cli/chunks/queen-coordinator-LDKLBPD5.js +0 -2
  357. package/dist/cli/chunks/router-H5YSIRH2.js +0 -2
  358. package/dist/cli/chunks/routing-feedback-5R36TJDH.js +0 -2
  359. package/dist/cli/chunks/rvf-dual-writer-TT2DBQQQ.js +0 -2
  360. package/dist/cli/chunks/rvf-migration-adapter-BCLFJKSK.js +0 -2
  361. package/dist/cli/chunks/rvf-native-adapter-UXI66OQJ.js +0 -2
  362. package/dist/cli/chunks/safe-db-MSTD2GDH.js +0 -2
  363. package/dist/cli/chunks/schedule-KST6KIFD.js +0 -2
  364. package/dist/cli/chunks/scheduler-FTQS6YK3.js +0 -2
  365. package/dist/cli/chunks/sqlite-persistence-ZX5QFDMR.js +0 -2
  366. package/dist/cli/chunks/unified-memory-2Z2F446J.js +0 -2
  367. package/dist/cli/chunks/unified-memory-hnsw-A4EWYPJQ.js +0 -2
  368. package/dist/cli/chunks/unified-persistence-Z6N6JZFA.js +0 -2
  369. package/dist/cli/chunks/visual-security-GXYZV7KR.js +0 -2
  370. package/dist/cli/chunks/witness-chain-52PEIEGK.js +0 -2
  371. package/dist/cli/chunks/workflow-orchestrator-DORMQMG7.js +0 -2
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.7");process.exit(0)}
2
- import{a as nn}from"./chunk-HZFT3P5B.js";import{a as br}from"./chunk-SSP2B2WR.js";import{b as Er}from"./chunk-K7W55B7Q.js";import{a as la,c as ua,d as da}from"./chunk-GY2SAIXP.js";import{a as aa,b as oa,c as ca}from"./chunk-EB2PP6X2.js";import{a as Cr,b as Ys,c as Sr,d as Js,e as tn,f as Zs,g as ea,h as ta,i as na,j as ra,k as ia,l as sa,m as Tr}from"./chunk-QJE6ZW2X.js";import{a as Ws,b as Ks}from"./chunk-VNW5Q2CX.js";import{a as Xs}from"./chunk-YK3NOC2R.js";import{a as pa}from"./chunk-HXBAQKMH.js";import{a as ga}from"./chunk-DGK6GQMO.js";import{a as fa}from"./chunk-Z3VJLWRR.js";import{a as ha}from"./chunk-JK6B3ULP.js";import{b as Zt,c as en}from"./chunk-OJEZNLB6.js";import{a as Ge}from"./chunk-RORZ5O5Z.js";import{a as ma}from"./chunk-34JLY3U6.js";import{c as O,e as rn,i as U,j as sn,l as A}from"./chunk-6FEQ73BF.js";import{A as qs,B as $s,C as Gs,D as js,E as zs,F as qe,G as $e,H as Hs,a as Ji,b as Qt,c as is,d as bc,e as ss,f as ds,g as hs,h as ys,i as vs,j as bs,k as Xt,l as Cs,m as Ss,n as Ts,o as Es,p as ws,q as Rs,r as Ps,s as xs,t as As,u as Ms,v as _s,w as Os,x as Ns,y as Fs,z as Ls}from"./chunk-J26GADQE.js";import{a as rs,c as Vt}from"./chunk-REEIFA6A.js";import{g as Ee,h as us}from"./chunk-VUFRTGML.js";import{c as ls}from"./chunk-AAA4SHEG.js";import{a as Is,c as gt,d as Ds}from"./chunk-XXAVQACL.js";import{b as Te,c as Wt,e as Le,f as vr,g as os,j as Kt,l as cs}from"./chunk-5KS7HA37.js";import{a as pt,b as ms,c as ps,e as gs,f as fs}from"./chunk-EL75G2A3.js";import{c as Us,d as Bs}from"./chunk-QWLTHFZW.js";import{d as Vs}from"./chunk-YDZJWDR6.js";import{a as Qs}from"./chunk-M63QB466.js";import{a as Fe}from"./chunk-C2CUPJGR.js";import{b as Jt}from"./chunk-56ZKQYZY.js";import{a as ks}from"./chunk-HLZATDD2.js";import{c as Se,h as Yt}from"./chunk-G762PEFO.js";import{s as ns}from"./chunk-2YVJ5OUL.js";import{a as es,b as ts,c as be,d as Ce}from"./chunk-CWPRU7ZI.js";import{c as as}from"./chunk-IYQ7XNE5.js";import{d as yr}from"./chunk-WUV5RZUI.js";import{h as hr}from"./chunk-IC2WSSD5.js";import{e as pr}from"./chunk-DCJW2DPL.js";import{c as gr,d as fr}from"./chunk-ZRLNACPY.js";import{d as ve}from"./chunk-G7YTZTGU.js";import{a as Yi,b as ie,c as W}from"./chunk-PZG3542B.js";import{m as Xi,n as vc}from"./chunk-B7M323VL.js";import{c as Zi}from"./chunk-UBYCR3O4.js";import{o as Q,s as ue}from"./chunk-ZLVQSEZK.js";import{b as M,d as X}from"./chunk-4G2VNW4C.js";import{a as oe,c as ce,d as mt}from"./chunk-HTWIGQL4.js";import{g as Ne}from"./chunk-C2MDBBFF.js";import{a as Ht}from"./chunk-RNYX4CPI.js";import{i as G}from"./chunk-FTTFJ7SJ.js";import{a as mr,c as _,d as L}from"./chunk-CG5DZCOZ.js";import{a as Wi}from"./chunk-VJRZFWR5.js";import{e as Gt,f as ye,g as jt}from"./chunk-JYXOFN3E.js";import{a as E,b as z,c as ae,d as _e,e as k}from"./chunk-LVEX4GID.js";import{R as hc,S as $t,b as Oe}from"./chunk-LGBN7TKC.js";import{b as zt,c as Ut,d as Bt}from"./chunk-5Q22XPTH.js";import{a as Ki,b as yc}from"./chunk-IARSGAG7.js";import{a as pc,b as gc,d as fc,f as Qi}from"./chunk-HSDOOFV7.js";var Va={};fc(Va,{DEFAULT_QEC_CONFIG:()=>Ba,ReasoningQEC:()=>Mn,createReasoningQEC:()=>Ha,processReasoning:()=>yu});async function hu(){return Ua?za!==null:(za=null,Ua=!0,!1)}function Ha(o){return new Mn(o)}function yu(o,e){return Ha(e).process(o)}var Zr,Ba,gu,fu,za,Ua,Mn,Qa=gc(()=>{"use strict";jt();$t();Zr=ye("ReasoningQEC"),Ba={minPaths:3,confidenceThreshold:.5,majorityThreshold:.5,useNativeBackend:!0,votingMethod:"weighted"},gu={"test-generation":["specification-driven","boundary-analysis","mutation-testing"],"security-audit":["threat-modeling","attack-surface","defense-in-depth"],"defect-triage":["root-cause-analysis","impact-assessment","risk-prioritization"]},fu=["analytical","empirical","heuristic"],za=null,Ua=!1;Mn=class{config;nativeAvailable=!1;constructor(e={}){this.config={...Ba,...e}}async initialize(){if(this.config.useNativeBackend){let e=Oe();(e.useQEFlashAttention||e.useQEGNNIndex)&&(this.nativeAvailable=await hu())}}generatePaths(e){let t=Math.max(this.config.minPaths,3),n=gu[e.type]??fu,r=[];for(let i=0;i<t;i++){let s=n[i%n.length],a=this.generatePathSteps(e,i,s),c=this.deriveConclusion(a,s),l=this.calculatePathConfidence(a);r.push({id:i,steps:a,conclusion:c,confidence:l})}return Zr.debug(`Generated ${r.length} reasoning paths for problem type: ${e.type}`),r}extractSyndromes(e){if(e.length<2)return[];let t=[],n=Math.max(...e.map(i=>i.steps.length));for(let i=0;i<n;i++){let s=new Map;for(let l of e){let u=l.steps[i];if(!u)continue;let d=s.get(u.conclusion)??[];d.push(l.id),s.set(u.conclusion,d)}if(s.size<=1)continue;let a=[...s.entries()].map(([l,u])=>u.map(d=>({pathId:d,conclusion:l}))).flat(),c=this.classifySyndromeSeverity(s,e.length);t.push({stepIndex:i,disagreements:a,severity:c})}let r=new Map;for(let i of e){let s=r.get(i.conclusion)??[];s.push(i.id),r.set(i.conclusion,s)}if(r.size>1){let i=[...r.entries()].map(([a,c])=>c.map(l=>({pathId:l,conclusion:a}))).flat(),s=this.classifySyndromeSeverity(r,e.length);t.push({stepIndex:-1,disagreements:i,severity:s})}return Zr.debug(`Extracted ${t.length} syndromes: ${t.filter(i=>i.severity==="critical").length} critical, ${t.filter(i=>i.severity==="major").length} major, ${t.filter(i=>i.severity==="minor").length} minor`),t}correctErrors(e,t){if(e.length===0)return{steps:[],conclusion:"",confidence:0,corrections:[],syndromeCount:t.length};let n=new Set(t.filter(u=>u.stepIndex>=0).map(u=>u.stepIndex)),r=Math.max(...e.map(u=>u.steps.length)),i=[],s=[];for(let u=0;u<r;u++)if(n.has(u)){let{step:d,correction:m}=this.correctStep(e,u);i.push(d),m&&s.push(m)}else{let d=e[0].steps[u];d&&i.push({...d})}let a=this.correctConclusion(e),c=this.calculateCorrectedConfidence(e,t),l={steps:i,conclusion:a,confidence:c,corrections:s,syndromeCount:t.length};return Zr.debug(`Error correction applied: ${s.length} corrections, confidence: ${c.toFixed(3)}`),l}validate(e){let t=[];e.confidence<this.config.confidenceThreshold&&t.push({stepIndex:-1,type:"low-confidence",description:`Overall confidence ${e.confidence.toFixed(3)} is below threshold ${this.config.confidenceThreshold}`});for(let i of e.steps)i.evidence.length===0&&t.push({stepIndex:i.index,type:"inconsistent-evidence",description:`Step ${i.index} has no supporting evidence`});e.syndromeCount>0&&e.confidence<.3&&t.push({stepIndex:-1,type:"all-divergent",description:`${e.syndromeCount} syndromes with confidence ${e.confidence.toFixed(3)} suggests all paths diverged significantly`});for(let i of e.corrections)i.reason.includes("no clear majority")&&t.push({stepIndex:i.stepIndex,type:"no-majority",description:`Step ${i.stepIndex}: ${i.reason}`});let n=t.length===0,r=n?e.confidence:e.confidence*(1-t.length*.1);return{valid:n,confidence:Math.max(0,r),issues:t}}process(e){let t=this.generatePaths(e),n=this.extractSyndromes(t),r=this.correctErrors(t,n),i=this.validate(r);return{paths:t,syndromes:n,corrected:r,validation:i}}getConfig(){return{...this.config}}isNativeAvailable(){return this.nativeAvailable}generatePathSteps(e,t,n){return e.steps.map((r,i)=>{let s=this.generateStepConclusion(r,n,e.context,t),a=this.gatherEvidence(r,n,e.context);return{index:i,description:`[${n}] ${r}`,conclusion:s,evidence:a}})}generateStepConclusion(e,t,n,r){let i=Object.keys(n).sort(),s={0:l=>l.length>0?`Focused on ${l[0]}`:"Primary analysis",1:l=>l.length>1?`Focused on ${l[l.length-1]}`:"Secondary analysis",2:l=>l.length>0?`Cross-referencing ${l.join(" and ")}`:"Holistic analysis"},c=(s[r%3]??s[0])(i);return`[${t}] ${e}: ${c}`}gatherEvidence(e,t,n){let r=[];r.push(`Analysis via ${t}: ${e}`);for(let[i,s]of Object.entries(n))(typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&r.push(`Context[${i}]: ${String(s)}`);return r}deriveConclusion(e,t){if(e.length===0)return`No conclusion (${t})`;let n=e[e.length-1];return`${t}: ${n.conclusion}`}calculatePathConfidence(e){if(e.length===0)return 0;let t=e.reduce((n,r)=>n+r.evidence.length,0)/e.length;return Math.min(1,.5+t*.1)}classifySyndromeSeverity(e,t){let n=Math.max(...[...e.values()].map(r=>r.length));return n>=Math.ceil(t*2/3)?"minor":n>=Math.ceil(t/2)?"major":"critical"}correctStep(e,t){let n=new Map,r=new Map,i=this.config.votingMethod==="weighted";for(let g of e){let f=g.steps[t];if(!f)continue;let h=n.get(f.conclusion)??0,v=i?g.confidence:1;n.set(f.conclusion,h+v),r.set(f.conclusion,f)}if(n.size===0)return{step:{index:t,description:`Step ${t} (no data)`,conclusion:"",evidence:[]},correction:null};let s=[...n.entries()].sort((g,f)=>f[1]-g[1]||g[0].localeCompare(f[0])),[a,c]=s[0],l=r.get(a),u=new Set;for(let g of e){let f=g.steps[t];if(f)for(let h of f.evidence)u.add(h)}let d={index:t,description:l.description,conclusion:a,evidence:[...u]},m=e[0].steps[t]?.conclusion,p=null;if(m&&m!==a){let g=e.filter(C=>C.steps[t]).length,f=[...n.values()].reduce((C,b)=>C+b,0),v=c/f>this.config.majorityThreshold;p={stepIndex:t,original:m,corrected:a,reason:v?`${i?"Weighted vote":"Majority vote"} (${c.toFixed(2)}/${f.toFixed(2)} weight from ${g} paths)`:`Selected highest ${i?"weight":"count"} (${c.toFixed(2)}/${f.toFixed(2)}), no clear majority`}}return{step:d,correction:p}}correctConclusion(e){let t=new Map,n=this.config.votingMethod==="weighted";for(let i of e){let s=t.get(i.conclusion)??0,a=n?i.confidence:1;t.set(i.conclusion,s+a)}return[...t.entries()].sort((i,s)=>s[1]-i[1]||i[0].localeCompare(s[0]))[0]?.[0]??""}calculateCorrectedConfidence(e,t){let n=e.reduce((l,u)=>l+u.confidence,0)/e.length,r=t.filter(l=>l.severity==="critical").length,i=t.filter(l=>l.severity==="major").length,s=t.filter(l=>l.severity==="minor").length,a=r*.2+i*.1+s*.03,c=t.length===0?.1:0;return Math.max(0,Math.min(1,n-a+c))}}});k();X();Bt();import*as q from"fs/promises";import*as D from"path";import{createHash as ya,randomBytes as wr}from"crypto";var Cc=100;function Rr(o){return o.evidence?.completeness==="complete"?"completed":o.evidence?.completeness==="partial"?"partial":o.evidence?"unavailable":"unverified"}var Sc={typescript:{jest:".test.ts",vitest:".test.ts",mocha:".spec.ts",default:".test.ts"},javascript:{jest:".test.js",vitest:".test.js",mocha:".spec.js",default:".test.js"},python:{pytest:"test_",unittest:"_test",default:"test_"},java:{junit:"Test.java",testng:"Test.java",default:"Test.java"},go:{testing:"_test.go",default:"_test.go"},rust:{cargo:"_test.rs",default:"_test.rs"},ruby:{rspec:"_spec.rb",minitest:"_test.rb",default:"_spec.rb"},php:{phpunit:"Test.php",pest:".test.php",default:"Test.php"},csharp:{xunit:"Tests.cs",nunit:"Tests.cs",mstest:"Tests.cs",default:"Tests.cs"},kotlin:{junit:"Test.kt",kotest:"Spec.kt",default:"Test.kt"},swift:{xctest:"Tests.swift",default:"Tests.swift"}},Pr=class{baseDir;resultsDir;constructor(e=zt()){this.baseDir=e,this.resultsDir=D.join(e,"results")}async save(e,t,n,r={}){let i=new Date,s=[];if(process.env.AQE_MEMORY_BACKEND==="memory")return{taskId:e,taskType:t,timestamp:i,files:s,summary:this.extractSummary(t,n)};await this.ensureDirectories(t);let a=this.formatTimestamp(i),c=r.filenamePrefix||`${a}_${this.uniqueSuffix(e)}`;switch(t){case"generate-tests":s.push(...await this.saveTestGeneration(n,c,r));break;case"analyze-coverage":s.push(...await this.saveCoverage(n,c,r));break;case"scan-security":s.push(...await this.saveSecurityScan(n,c,r));break;case"assess-quality":s.push(...await this.saveQualityAssessment(n,c,r));break;case"index-code":s.push(...await this.saveCodeIndex(n,c,r));break;case"predict-defects":s.push(...await this.saveDefectPrediction(n,c,r));break;case"validate-contracts":s.push(...await this.saveContractValidation(n,c,r));break;case"test-accessibility":s.push(...await this.saveAccessibilityTest(n,c,r));break;case"run-chaos":s.push(...await this.saveChaosTest(n,c,r));break;default:s.push(...await this.saveGeneric(t,n,c))}let l=this.extractSummary(t,n);return await this.updateIndex(e,t,i,s,l),{taskId:e,taskType:t,timestamp:i,files:s,summary:l}}async saveTestGeneration(e,t,n){let r=[],i=e,s=D.join(this.resultsDir,"tests","generated");await q.mkdir(s,{recursive:!0});let a=D.join(this.resultsDir,"tests",`${t}_manifest.json`),c=JSON.stringify({generated:new Date().toISOString(),testsGenerated:i.testsGenerated,coverageEstimate:i.coverageEstimate,patternsUsed:i.patternsUsed,language:n.language||"typescript",framework:n.framework||"vitest",tests:i.tests},null,2);if(r.push(await this.writeNewFile(a,c,"json")),i.tests)for(let d of i.tests){let m=d.testCode??d.code;if(m){let p=this.getTestExtension(n.language||"typescript",n.framework||"vitest"),g=this.generatedTestFilename(d,p),f=D.join(s,g);try{r.push(await this.replaceFile(f,m,"source"))}catch(h){console.warn(`ResultSaver: could not write generated test ${g}: ${h.message}`)}}}let l=D.join(this.resultsDir,"tests",`${t}_report.md`),u=this.generateTestReport(i,n);return r.push(await this.writeNewFile(l,u,"markdown")),r}async saveCoverage(e,t,n){let r=[],i=e,s=D.join(this.resultsDir,"coverage"),a=D.join(s,`${t}_coverage.json`);if(r.push(await this.writeNewFile(a,JSON.stringify(i,null,2),"json")),n.includeSecondary!==!1&&i.measured===!0){let u=D.join(s,`${t}_coverage.lcov`),d=this.generateLcov(i);r.push(await this.writeNewFile(u,d,"lcov"))}let c=D.join(s,`${t}_report.md`),l=this.generateCoverageReport(i);return r.push(await this.writeNewFile(c,l,"markdown")),r}async saveSecurityScan(e,t,n){let r=[],i=e,s=D.join(this.resultsDir,"security"),a=D.join(s,`${t}_scan.json`);if(r.push(await this.writeNewFile(a,JSON.stringify(i,null,2),"json")),n.includeSecondary!==!1){let u=D.join(s,`${t}_scan.sarif`),d=this.generateSarif(i);r.push(await this.writeNewFile(u,d,"sarif"))}let c=D.join(s,`${t}_report.md`),l=this.generateSecurityReport(i);return r.push(await this.writeNewFile(c,l,"markdown")),r}async saveQualityAssessment(e,t,n){let r=[],i=e,s=D.join(this.resultsDir,"quality"),a=D.join(s,`${t}_assessment.json`);r.push(await this.writeNewFile(a,JSON.stringify(i,null,2),"json"));let c=D.join(s,`${t}_report.md`),l=this.generateQualityReport(i);return r.push(await this.writeNewFile(c,l,"markdown")),r}async saveCodeIndex(e,t,n){let r=[],i=e,s=D.join(this.resultsDir,"code-index");await q.mkdir(s,{recursive:!0});let a=D.join(s,`${t}_index.json`);return r.push(await this.writeNewFile(a,JSON.stringify(i,null,2),"json")),r}async saveDefectPrediction(e,t,n){let r=[],i=D.join(this.resultsDir,"defects");await q.mkdir(i,{recursive:!0});let s=D.join(i,`${t}_prediction.json`);return r.push(await this.writeNewFile(s,JSON.stringify(e,null,2),"json")),r}async saveContractValidation(e,t,n){let r=[],i=D.join(this.resultsDir,"contracts");await q.mkdir(i,{recursive:!0});let s=D.join(i,`${t}_validation.json`);return r.push(await this.writeNewFile(s,JSON.stringify(e,null,2),"json")),r}async saveAccessibilityTest(e,t,n){let r=[],i=D.join(this.resultsDir,"accessibility");await q.mkdir(i,{recursive:!0});let s=D.join(i,`${t}_test.json`);return r.push(await this.writeNewFile(s,JSON.stringify(e,null,2),"json")),r}async saveChaosTest(e,t,n){let r=[],i=D.join(this.resultsDir,"chaos");await q.mkdir(i,{recursive:!0});let s=D.join(i,`${t}_chaos.json`);return r.push(await this.writeNewFile(s,JSON.stringify(e,null,2),"json")),r}async saveGeneric(e,t,n){let r=[],i=D.join(this.resultsDir,"other");await q.mkdir(i,{recursive:!0});let s=D.join(i,`${n}_${e}.json`);return r.push(await this.writeNewFile(s,JSON.stringify(t,null,2),"json")),r}generateLcov(e){let t=Math.round(e.lineCoverage??0);return`TN:agentic-qe-coverage
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.8");process.exit(0)}
2
+ import{a as nn}from"./chunk-SFPGLUXS.js";import{a as br}from"./chunk-VVK4ECVJ.js";import{b as Er}from"./chunk-A6GCO6ZU.js";import{a as la,c as ua,d as da}from"./chunk-XOOBLZXR.js";import{a as aa,b as oa,c as ca}from"./chunk-WAWKAYPY.js";import{a as Cr,b as Ys,c as Sr,d as Js,e as tn,f as Zs,g as ea,h as ta,i as na,j as ra,k as ia,l as sa,m as Tr}from"./chunk-Z3LDUPLQ.js";import{a as Ws,b as Ks}from"./chunk-PZ7FJ4UG.js";import{a as Xs}from"./chunk-LHRVSK44.js";import{a as pa}from"./chunk-YVWMJZ6O.js";import{a as ga}from"./chunk-6GIC2263.js";import{a as fa}from"./chunk-OWBFVAEH.js";import{a as ha}from"./chunk-7DHSHD5B.js";import{b as Zt,c as en}from"./chunk-NW7HTOSN.js";import{a as Ge}from"./chunk-G77Q22EN.js";import{a as ma}from"./chunk-5MBNRTT5.js";import{c as O,e as rn,i as U,j as sn,l as A}from"./chunk-TC52M542.js";import{A as qs,B as $s,C as Gs,D as js,E as zs,F as qe,G as $e,H as Hs,a as Ji,b as Qt,c as is,d as bc,e as ss,f as ds,g as hs,h as ys,i as vs,j as bs,k as Xt,l as Cs,m as Ss,n as Ts,o as Es,p as ws,q as Rs,r as Ps,s as xs,t as As,u as Ms,v as _s,w as Os,x as Ns,y as Fs,z as Ls}from"./chunk-ZOVAZTXE.js";import{a as rs,c as Vt}from"./chunk-NZATJ2C6.js";import{g as Ee,h as us}from"./chunk-ZWMFKZEQ.js";import{c as ls}from"./chunk-VKFVJCIH.js";import{a as Is,c as gt,d as Ds}from"./chunk-GGSTLKY5.js";import{b as Te,c as Wt,e as Le,f as vr,g as os,j as Kt,l as cs}from"./chunk-DCYUHCPK.js";import{a as pt,b as ms,c as ps,e as gs,f as fs}from"./chunk-4GYFONJB.js";import{c as Us,d as Bs}from"./chunk-WLXGUQOZ.js";import{d as Vs}from"./chunk-I4U7YCXG.js";import{a as Qs}from"./chunk-Y5ZBF7MA.js";import{a as Fe}from"./chunk-UTNKMPTC.js";import{b as Jt}from"./chunk-V7VZSNDK.js";import{a as ks}from"./chunk-JFWQFB3S.js";import{c as Se,h as Yt}from"./chunk-GENNJRNK.js";import{s as ns}from"./chunk-PWA6XBW4.js";import{a as es,b as ts,c as be,d as Ce}from"./chunk-LVHZK7GW.js";import{c as as}from"./chunk-DAFMHM64.js";import{d as yr}from"./chunk-SWY6KGMF.js";import{h as hr}from"./chunk-P4UT4LBE.js";import{e as pr}from"./chunk-QFYUZYRA.js";import{c as gr,d as fr}from"./chunk-22DOS3PM.js";import{d as ve}from"./chunk-YUP3APSN.js";import{a as Yi,b as ie,c as W}from"./chunk-BLZEOGQE.js";import{m as Xi,n as vc}from"./chunk-SJMZZMHP.js";import{c as Zi}from"./chunk-PUYQ6EKC.js";import{o as Q,s as ue}from"./chunk-7XGM7Q2N.js";import{b as M,d as X}from"./chunk-FWXNFPLS.js";import{a as oe,c as ce,d as mt}from"./chunk-RG42LDOB.js";import{g as Ne}from"./chunk-BEVWCF3Q.js";import{a as Ht}from"./chunk-A2UGPKCS.js";import{i as G}from"./chunk-PICEGWGB.js";import{a as mr,c as _,d as L}from"./chunk-YTYS2XSY.js";import{a as Wi}from"./chunk-X6VYQVUM.js";import{e as Gt,f as ye,g as jt}from"./chunk-7H3GNRNA.js";import{a as E,b as z,c as ae,d as _e,e as k}from"./chunk-J7FLNP5L.js";import{R as hc,S as $t,b as Oe}from"./chunk-KVMKYUOE.js";import{b as zt,c as Ut,d as Bt}from"./chunk-SHEVM5PF.js";import{a as Ki,b as yc}from"./chunk-LPSMVBB3.js";import{a as pc,b as gc,d as fc,f as Qi}from"./chunk-K5R3WUJP.js";var Va={};fc(Va,{DEFAULT_QEC_CONFIG:()=>Ba,ReasoningQEC:()=>Mn,createReasoningQEC:()=>Ha,processReasoning:()=>yu});async function hu(){return Ua?za!==null:(za=null,Ua=!0,!1)}function Ha(o){return new Mn(o)}function yu(o,e){return Ha(e).process(o)}var Zr,Ba,gu,fu,za,Ua,Mn,Qa=gc(()=>{"use strict";jt();$t();Zr=ye("ReasoningQEC"),Ba={minPaths:3,confidenceThreshold:.5,majorityThreshold:.5,useNativeBackend:!0,votingMethod:"weighted"},gu={"test-generation":["specification-driven","boundary-analysis","mutation-testing"],"security-audit":["threat-modeling","attack-surface","defense-in-depth"],"defect-triage":["root-cause-analysis","impact-assessment","risk-prioritization"]},fu=["analytical","empirical","heuristic"],za=null,Ua=!1;Mn=class{config;nativeAvailable=!1;constructor(e={}){this.config={...Ba,...e}}async initialize(){if(this.config.useNativeBackend){let e=Oe();(e.useQEFlashAttention||e.useQEGNNIndex)&&(this.nativeAvailable=await hu())}}generatePaths(e){let t=Math.max(this.config.minPaths,3),n=gu[e.type]??fu,r=[];for(let i=0;i<t;i++){let s=n[i%n.length],a=this.generatePathSteps(e,i,s),c=this.deriveConclusion(a,s),l=this.calculatePathConfidence(a);r.push({id:i,steps:a,conclusion:c,confidence:l})}return Zr.debug(`Generated ${r.length} reasoning paths for problem type: ${e.type}`),r}extractSyndromes(e){if(e.length<2)return[];let t=[],n=Math.max(...e.map(i=>i.steps.length));for(let i=0;i<n;i++){let s=new Map;for(let l of e){let u=l.steps[i];if(!u)continue;let d=s.get(u.conclusion)??[];d.push(l.id),s.set(u.conclusion,d)}if(s.size<=1)continue;let a=[...s.entries()].map(([l,u])=>u.map(d=>({pathId:d,conclusion:l}))).flat(),c=this.classifySyndromeSeverity(s,e.length);t.push({stepIndex:i,disagreements:a,severity:c})}let r=new Map;for(let i of e){let s=r.get(i.conclusion)??[];s.push(i.id),r.set(i.conclusion,s)}if(r.size>1){let i=[...r.entries()].map(([a,c])=>c.map(l=>({pathId:l,conclusion:a}))).flat(),s=this.classifySyndromeSeverity(r,e.length);t.push({stepIndex:-1,disagreements:i,severity:s})}return Zr.debug(`Extracted ${t.length} syndromes: ${t.filter(i=>i.severity==="critical").length} critical, ${t.filter(i=>i.severity==="major").length} major, ${t.filter(i=>i.severity==="minor").length} minor`),t}correctErrors(e,t){if(e.length===0)return{steps:[],conclusion:"",confidence:0,corrections:[],syndromeCount:t.length};let n=new Set(t.filter(u=>u.stepIndex>=0).map(u=>u.stepIndex)),r=Math.max(...e.map(u=>u.steps.length)),i=[],s=[];for(let u=0;u<r;u++)if(n.has(u)){let{step:d,correction:m}=this.correctStep(e,u);i.push(d),m&&s.push(m)}else{let d=e[0].steps[u];d&&i.push({...d})}let a=this.correctConclusion(e),c=this.calculateCorrectedConfidence(e,t),l={steps:i,conclusion:a,confidence:c,corrections:s,syndromeCount:t.length};return Zr.debug(`Error correction applied: ${s.length} corrections, confidence: ${c.toFixed(3)}`),l}validate(e){let t=[];e.confidence<this.config.confidenceThreshold&&t.push({stepIndex:-1,type:"low-confidence",description:`Overall confidence ${e.confidence.toFixed(3)} is below threshold ${this.config.confidenceThreshold}`});for(let i of e.steps)i.evidence.length===0&&t.push({stepIndex:i.index,type:"inconsistent-evidence",description:`Step ${i.index} has no supporting evidence`});e.syndromeCount>0&&e.confidence<.3&&t.push({stepIndex:-1,type:"all-divergent",description:`${e.syndromeCount} syndromes with confidence ${e.confidence.toFixed(3)} suggests all paths diverged significantly`});for(let i of e.corrections)i.reason.includes("no clear majority")&&t.push({stepIndex:i.stepIndex,type:"no-majority",description:`Step ${i.stepIndex}: ${i.reason}`});let n=t.length===0,r=n?e.confidence:e.confidence*(1-t.length*.1);return{valid:n,confidence:Math.max(0,r),issues:t}}process(e){let t=this.generatePaths(e),n=this.extractSyndromes(t),r=this.correctErrors(t,n),i=this.validate(r);return{paths:t,syndromes:n,corrected:r,validation:i}}getConfig(){return{...this.config}}isNativeAvailable(){return this.nativeAvailable}generatePathSteps(e,t,n){return e.steps.map((r,i)=>{let s=this.generateStepConclusion(r,n,e.context,t),a=this.gatherEvidence(r,n,e.context);return{index:i,description:`[${n}] ${r}`,conclusion:s,evidence:a}})}generateStepConclusion(e,t,n,r){let i=Object.keys(n).sort(),s={0:l=>l.length>0?`Focused on ${l[0]}`:"Primary analysis",1:l=>l.length>1?`Focused on ${l[l.length-1]}`:"Secondary analysis",2:l=>l.length>0?`Cross-referencing ${l.join(" and ")}`:"Holistic analysis"},c=(s[r%3]??s[0])(i);return`[${t}] ${e}: ${c}`}gatherEvidence(e,t,n){let r=[];r.push(`Analysis via ${t}: ${e}`);for(let[i,s]of Object.entries(n))(typeof s=="string"||typeof s=="number"||typeof s=="boolean")&&r.push(`Context[${i}]: ${String(s)}`);return r}deriveConclusion(e,t){if(e.length===0)return`No conclusion (${t})`;let n=e[e.length-1];return`${t}: ${n.conclusion}`}calculatePathConfidence(e){if(e.length===0)return 0;let t=e.reduce((n,r)=>n+r.evidence.length,0)/e.length;return Math.min(1,.5+t*.1)}classifySyndromeSeverity(e,t){let n=Math.max(...[...e.values()].map(r=>r.length));return n>=Math.ceil(t*2/3)?"minor":n>=Math.ceil(t/2)?"major":"critical"}correctStep(e,t){let n=new Map,r=new Map,i=this.config.votingMethod==="weighted";for(let g of e){let f=g.steps[t];if(!f)continue;let h=n.get(f.conclusion)??0,v=i?g.confidence:1;n.set(f.conclusion,h+v),r.set(f.conclusion,f)}if(n.size===0)return{step:{index:t,description:`Step ${t} (no data)`,conclusion:"",evidence:[]},correction:null};let s=[...n.entries()].sort((g,f)=>f[1]-g[1]||g[0].localeCompare(f[0])),[a,c]=s[0],l=r.get(a),u=new Set;for(let g of e){let f=g.steps[t];if(f)for(let h of f.evidence)u.add(h)}let d={index:t,description:l.description,conclusion:a,evidence:[...u]},m=e[0].steps[t]?.conclusion,p=null;if(m&&m!==a){let g=e.filter(C=>C.steps[t]).length,f=[...n.values()].reduce((C,b)=>C+b,0),v=c/f>this.config.majorityThreshold;p={stepIndex:t,original:m,corrected:a,reason:v?`${i?"Weighted vote":"Majority vote"} (${c.toFixed(2)}/${f.toFixed(2)} weight from ${g} paths)`:`Selected highest ${i?"weight":"count"} (${c.toFixed(2)}/${f.toFixed(2)}), no clear majority`}}return{step:d,correction:p}}correctConclusion(e){let t=new Map,n=this.config.votingMethod==="weighted";for(let i of e){let s=t.get(i.conclusion)??0,a=n?i.confidence:1;t.set(i.conclusion,s+a)}return[...t.entries()].sort((i,s)=>s[1]-i[1]||i[0].localeCompare(s[0]))[0]?.[0]??""}calculateCorrectedConfidence(e,t){let n=e.reduce((l,u)=>l+u.confidence,0)/e.length,r=t.filter(l=>l.severity==="critical").length,i=t.filter(l=>l.severity==="major").length,s=t.filter(l=>l.severity==="minor").length,a=r*.2+i*.1+s*.03,c=t.length===0?.1:0;return Math.max(0,Math.min(1,n-a+c))}}});k();X();Bt();import*as q from"fs/promises";import*as D from"path";import{createHash as ya,randomBytes as wr}from"crypto";var Cc=100;function Rr(o){return o.evidence?.completeness==="complete"?"completed":o.evidence?.completeness==="partial"?"partial":o.evidence?"unavailable":"unverified"}var Sc={typescript:{jest:".test.ts",vitest:".test.ts",mocha:".spec.ts",default:".test.ts"},javascript:{jest:".test.js",vitest:".test.js",mocha:".spec.js",default:".test.js"},python:{pytest:"test_",unittest:"_test",default:"test_"},java:{junit:"Test.java",testng:"Test.java",default:"Test.java"},go:{testing:"_test.go",default:"_test.go"},rust:{cargo:"_test.rs",default:"_test.rs"},ruby:{rspec:"_spec.rb",minitest:"_test.rb",default:"_spec.rb"},php:{phpunit:"Test.php",pest:".test.php",default:"Test.php"},csharp:{xunit:"Tests.cs",nunit:"Tests.cs",mstest:"Tests.cs",default:"Tests.cs"},kotlin:{junit:"Test.kt",kotest:"Spec.kt",default:"Test.kt"},swift:{xctest:"Tests.swift",default:"Tests.swift"}},Pr=class{baseDir;resultsDir;constructor(e=zt()){this.baseDir=e,this.resultsDir=D.join(e,"results")}async save(e,t,n,r={}){let i=new Date,s=[];if(process.env.AQE_MEMORY_BACKEND==="memory")return{taskId:e,taskType:t,timestamp:i,files:s,summary:this.extractSummary(t,n)};await this.ensureDirectories(t);let a=this.formatTimestamp(i),c=r.filenamePrefix||`${a}_${this.uniqueSuffix(e)}`;switch(t){case"generate-tests":s.push(...await this.saveTestGeneration(n,c,r));break;case"analyze-coverage":s.push(...await this.saveCoverage(n,c,r));break;case"scan-security":s.push(...await this.saveSecurityScan(n,c,r));break;case"assess-quality":s.push(...await this.saveQualityAssessment(n,c,r));break;case"index-code":s.push(...await this.saveCodeIndex(n,c,r));break;case"predict-defects":s.push(...await this.saveDefectPrediction(n,c,r));break;case"validate-contracts":s.push(...await this.saveContractValidation(n,c,r));break;case"test-accessibility":s.push(...await this.saveAccessibilityTest(n,c,r));break;case"run-chaos":s.push(...await this.saveChaosTest(n,c,r));break;default:s.push(...await this.saveGeneric(t,n,c))}let l=this.extractSummary(t,n);return await this.updateIndex(e,t,i,s,l),{taskId:e,taskType:t,timestamp:i,files:s,summary:l}}async saveTestGeneration(e,t,n){let r=[],i=e,s=D.join(this.resultsDir,"tests","generated");await q.mkdir(s,{recursive:!0});let a=D.join(this.resultsDir,"tests",`${t}_manifest.json`),c=JSON.stringify({generated:new Date().toISOString(),testsGenerated:i.testsGenerated,coverageEstimate:i.coverageEstimate,patternsUsed:i.patternsUsed,language:n.language||"typescript",framework:n.framework||"vitest",tests:i.tests},null,2);if(r.push(await this.writeNewFile(a,c,"json")),i.tests)for(let d of i.tests){let m=d.testCode??d.code;if(m){let p=this.getTestExtension(n.language||"typescript",n.framework||"vitest"),g=this.generatedTestFilename(d,p),f=D.join(s,g);try{r.push(await this.replaceFile(f,m,"source"))}catch(h){console.warn(`ResultSaver: could not write generated test ${g}: ${h.message}`)}}}let l=D.join(this.resultsDir,"tests",`${t}_report.md`),u=this.generateTestReport(i,n);return r.push(await this.writeNewFile(l,u,"markdown")),r}async saveCoverage(e,t,n){let r=[],i=e,s=D.join(this.resultsDir,"coverage"),a=D.join(s,`${t}_coverage.json`);if(r.push(await this.writeNewFile(a,JSON.stringify(i,null,2),"json")),n.includeSecondary!==!1&&i.measured===!0){let u=D.join(s,`${t}_coverage.lcov`),d=this.generateLcov(i);r.push(await this.writeNewFile(u,d,"lcov"))}let c=D.join(s,`${t}_report.md`),l=this.generateCoverageReport(i);return r.push(await this.writeNewFile(c,l,"markdown")),r}async saveSecurityScan(e,t,n){let r=[],i=e,s=D.join(this.resultsDir,"security"),a=D.join(s,`${t}_scan.json`);if(r.push(await this.writeNewFile(a,JSON.stringify(i,null,2),"json")),n.includeSecondary!==!1){let u=D.join(s,`${t}_scan.sarif`),d=this.generateSarif(i);r.push(await this.writeNewFile(u,d,"sarif"))}let c=D.join(s,`${t}_report.md`),l=this.generateSecurityReport(i);return r.push(await this.writeNewFile(c,l,"markdown")),r}async saveQualityAssessment(e,t,n){let r=[],i=e,s=D.join(this.resultsDir,"quality"),a=D.join(s,`${t}_assessment.json`);r.push(await this.writeNewFile(a,JSON.stringify(i,null,2),"json"));let c=D.join(s,`${t}_report.md`),l=this.generateQualityReport(i);return r.push(await this.writeNewFile(c,l,"markdown")),r}async saveCodeIndex(e,t,n){let r=[],i=e,s=D.join(this.resultsDir,"code-index");await q.mkdir(s,{recursive:!0});let a=D.join(s,`${t}_index.json`);return r.push(await this.writeNewFile(a,JSON.stringify(i,null,2),"json")),r}async saveDefectPrediction(e,t,n){let r=[],i=D.join(this.resultsDir,"defects");await q.mkdir(i,{recursive:!0});let s=D.join(i,`${t}_prediction.json`);return r.push(await this.writeNewFile(s,JSON.stringify(e,null,2),"json")),r}async saveContractValidation(e,t,n){let r=[],i=D.join(this.resultsDir,"contracts");await q.mkdir(i,{recursive:!0});let s=D.join(i,`${t}_validation.json`);return r.push(await this.writeNewFile(s,JSON.stringify(e,null,2),"json")),r}async saveAccessibilityTest(e,t,n){let r=[],i=D.join(this.resultsDir,"accessibility");await q.mkdir(i,{recursive:!0});let s=D.join(i,`${t}_test.json`);return r.push(await this.writeNewFile(s,JSON.stringify(e,null,2),"json")),r}async saveChaosTest(e,t,n){let r=[],i=D.join(this.resultsDir,"chaos");await q.mkdir(i,{recursive:!0});let s=D.join(i,`${t}_chaos.json`);return r.push(await this.writeNewFile(s,JSON.stringify(e,null,2),"json")),r}async saveGeneric(e,t,n){let r=[],i=D.join(this.resultsDir,"other");await q.mkdir(i,{recursive:!0});let s=D.join(i,`${n}_${e}.json`);return r.push(await this.writeNewFile(s,JSON.stringify(t,null,2),"json")),r}generateLcov(e){let t=Math.round(e.lineCoverage??0);return`TN:agentic-qe-coverage
3
3
  SF:summary
4
4
  DA:1,${t}
5
5
  LF:100
@@ -358,7 +358,7 @@ ${e.recommendations.length===0?s:e.recommendations.map((a,c)=>`${c+1}. ${a}`).jo
358
358
  WHERE id = ?
359
359
  `).run(l,u,d,c.last_used_at,c.last_used_at,c.last_used_at,a.id);let m=this.prepared.get("insertRelationship");return m&&m.run(G(),c.id,a.id,"merged",1),this.db.prepare("UPDATE qe_patterns SET tier = 'archived' WHERE id = ?").run(c.id),await this.recordEvent(a.id,"merged",{absorbedFrom:c.id}),await this.recordEvent(c.id,"archived",{mergedInto:a.id}),this.stats.patternsMerged++,a.id}async autoConsolidate(e){this.ensureInitialized(),this.stats.consolidationRuns++;let t=0,n=0,r=await this.findMergeCandidates(e);for(let a of r.slice(0,5))await this.mergePatterns(a.patternId1,a.patternId2)&&t++;let i=await this.findPruneCandidates(e);for(let a of i)(a.reason==="low-quality"||a.reason==="obsolete")&&this.db&&(this.db.prepare("DELETE FROM qe_patterns WHERE id = ?").run(a.patternId),this.embeddingCache.delete(a.patternId),await this.recordEvent(a.patternId,"pruned",{reason:a.reason}),n++,this.stats.patternsPruned++);let s=this.db?.prepare(`
360
360
  SELECT COUNT(*) as count FROM qe_patterns WHERE qe_domain = ? AND tier != 'archived'
361
- `).get(e);return{merged:t,pruned:n,retained:s?.count??0}}async getEvolutionHistory(e,t=20){this.ensureInitialized();let i=(this.prepared.get("getVersionHistory")?.all(e,t)??[]).map(l=>({id:l.id,patternId:l.pattern_id,version:l.version,embedding:this.bufferToFloatArray(l.embedding,l.embedding_dimension),changes:M(l.changes||"[]"),qualityScore:l.quality_score,successRate:l.success_rate,timestamp:new Date(l.created_at),trigger:l.trigger})),c=(this.prepared.get("getEvents")?.all(e,t)??[]).map(l=>({id:l.id,patternId:l.pattern_id,eventType:l.event_type,details:M(l.details||"{}"),timestamp:new Date(l.created_at)}));return{versions:i,events:c}}async recordEvent(e,t,n){let r=this.prepared.get("insertEvent");if(r){let i={id:G(),patternId:e,eventType:t,details:n,timestamp:new Date};r.run(i.id,e,t,JSON.stringify(n)),this.recentEvents.push(i)}}getStats(){return{...this.stats,embeddingCacheSize:this.embeddingCache.size,recentEventsSize:this.recentEvents.length}}async dispose(){this.embeddingCache.clear(),this.recentEvents.clear(),this.prepared.clear(),this.db=null,this.unifiedMemory=null,this.initialized=!1,console.log("[PatternEvolution] Disposed")}ensureInitialized(){if(!this.initialized)throw new Error("PatternEvolution not initialized. Call initialize() first.")}floatArrayToBuffer(e){let t=Buffer.alloc(e.length*4);for(let n=0;n<e.length;n++)t.writeFloatLE(e[n],n*4);return t}bufferToFloatArray(e,t){let n=[];for(let r=0;r<t;r++)n.push(e.readFloatLE(r*4));return n}};function kr(o={}){return new un(o)}k();var Vc={base:{},trajectoryTracker:{},experienceReplay:{},patternEvolution:{},enableTrajectories:!0,enableExperienceReplay:!0,enablePatternEvolution:!0,autoStoreExperiences:!0,autoConsolidate:!0,consolidationIntervalMs:3600*1e3},Mr=class{config;reasoningBank=null;trajectoryTracker=null;experienceReplay=null;patternEvolution=null;initialized=!1;consolidationTimer=null;stats={tasksRouted:0,trajectoriesCompleted:0,experiencesApplied:0,tokensSavedEstimate:0,avgTaskSpeedupPercent:0,successRate:0,totalSuccesses:0,totalTasks:0};constructor(e={}){this.config={...Vc,...e}}async initialize(){if(this.initialized)return;let e=performance.now();this.reasoningBank=br(this.config.base),await this.reasoningBank.initialize(),this.config.enableTrajectories&&(this.trajectoryTracker=xr(this.config.trajectoryTracker),await this.trajectoryTracker.initialize()),this.config.enableExperienceReplay&&(this.experienceReplay=Ar(this.config.experienceReplay),await this.experienceReplay.initialize()),this.config.enablePatternEvolution&&(this.patternEvolution=kr(this.config.patternEvolution),await this.patternEvolution.initialize()),this.config.autoConsolidate&&this.patternEvolution&&this.startConsolidationTimer(),this.initialized=!0;let t=performance.now()-e;console.log(`[EnhancedReasoningBank] Initialized in ${t.toFixed(0)}ms`)}async routeTaskWithExperience(e){this.ensureInitialized(),this.stats.tasksRouted++;try{let t=await this.reasoningBank.routeTask(e);if(!t.success)return t;let n={...t.value};if(this.experienceReplay){let r=await this.experienceReplay.getGuidance(e.task,e.domain);r&&(n.experienceGuidance=r,n.guidance=[`Strategy: ${r.recommendedStrategy}`,...r.suggestedActions.map(i=>`Action: ${i}`),...n.guidance])}if(this.trajectoryTracker){let r=await this.trajectoryTracker.findSimilarTrajectories(e.task,3);r.length>0&&(n.similarTrajectories=r.map(i=>({id:i.id,task:i.task,outcome:i.outcome,similarity:.8})))}return _(n)}catch(t){return L(z(t))}}async startTaskTrajectory(e,t={}){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");return this.trajectoryTracker.startTrajectory(e,t)}async recordTaskStep(e,t,n,r){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");await this.trajectoryTracker.recordStep(e,t,n,r)}async endTaskTrajectory(e,t,n){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");let r=await this.trajectoryTracker.endTrajectory(e,t,n);if(this.stats.trajectoriesCompleted++,this.stats.totalTasks++,t&&this.stats.totalSuccesses++,this.stats.successRate=this.stats.totalSuccesses/this.stats.totalTasks,this.config.autoStoreExperiences&&t&&this.experienceReplay){let i=this.deriveStrategy(r);await this.experienceReplay.storeExperience(r,i)}return r}async getTrajectory(e){return this.ensureInitialized(),this.trajectoryTracker?.getTrajectory(e)??null}async getExperienceGuidance(e,t){return this.ensureInitialized(),this.experienceReplay?this.experienceReplay.getGuidance(e,t):null}async recordExperienceApplication(e,t,n,r=0){this.ensureInitialized(),this.experienceReplay&&(await this.experienceReplay.recordApplication(e,t,n,r),this.stats.experiencesApplied++,this.stats.tokensSavedEstimate+=r)}async storePattern(e){this.ensureInitialized();let t=await this.reasoningBank.storeQEPattern(e);return t.success&&this.patternEvolution&&t.value.embedding&&await this.patternEvolution.trackVersion(t.value.id,t.value.embedding,["Initial version"],"initial"),t}async searchPatterns(e,t){return this.ensureInitialized(),this.reasoningBank.searchQEPatterns(e,t)}async recordPatternOutcome(e){this.ensureInitialized();let t=await this.reasoningBank.recordOutcome(e);if(this.patternEvolution&&e.success!==void 0){let n=await this.patternEvolution.detectDrift(e.patternId);n?.hasSignificantDrift&&console.log(`[EnhancedReasoningBank] Pattern drift detected: ${e.patternId}, recommendation: ${n.recommendation}`)}return t}async detectPatternDrift(e){return this.ensureInitialized(),this.patternEvolution?.detectDrift(e)??null}async findMergeCandidates(e){return this.ensureInitialized(),this.patternEvolution?.findMergeCandidates(e)??[]}async consolidatePatterns(e){return this.ensureInitialized(),this.patternEvolution?this.patternEvolution.autoConsolidate(e):{merged:0,pruned:0,retained:0}}async getPatternHistory(e){return this.ensureInitialized(),this.patternEvolution?.getEvolutionHistory(e)??null}async getStats(){return this.ensureInitialized(),{adapter:this.stats,reasoningBank:await this.reasoningBank.getQEStats(),trajectoryTracker:this.trajectoryTracker?.getStats(),experienceReplay:this.experienceReplay?.getStats(),patternEvolution:this.patternEvolution?.getStats()}}async dispose(){this.consolidationTimer&&(clearInterval(this.consolidationTimer),this.consolidationTimer=null),await this.patternEvolution?.dispose(),await this.experienceReplay?.dispose(),await this.trajectoryTracker?.dispose(),await this.reasoningBank?.dispose(),this.patternEvolution=null,this.experienceReplay=null,this.trajectoryTracker=null,this.reasoningBank=null,this.initialized=!1,console.log("[EnhancedReasoningBank] Disposed")}ensureInitialized(){if(!this.initialized||!this.reasoningBank)throw new Error("EnhancedReasoningBankAdapter not initialized. Call initialize() first.")}startConsolidationTimer(){this.consolidationTimer=setInterval(async()=>{try{let e=["test-generation","coverage-analysis","test-execution","quality-assessment"];for(let t of e){let n=await this.patternEvolution.autoConsolidate(t);(n.merged>0||n.pruned>0)&&console.log(`[EnhancedReasoningBank] Consolidated ${t}: merged=${n.merged}, pruned=${n.pruned}, retained=${n.retained}`)}}catch(e){console.error("[EnhancedReasoningBank] Consolidation error:",e)}},this.config.consolidationIntervalMs)}deriveStrategy(e){let t=e.steps.filter(n=>n.result.outcome==="success").map(n=>n.action);return t.length===0?`Attempted ${e.steps.length} actions for: ${e.task}`:`Used ${t.join(" -> ")} pattern for: ${e.task.substring(0,50)}`}};function Fp(o={}){return new Mr(o)}import{randomUUID as il}from"crypto";var N=class extends Error{constructor(t,n,r){super(n);this.type=t;this.details=r;this.name="EmbeddingError"}type;details};var dn=class{cache;maxSize;hits=0;misses=0;constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);if(t)return this.hits++,this.cache.delete(e),this.cache.set(e,t),t;this.misses++}set(e,t){if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,t)}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){return{hits:this.hits,misses:this.misses,size:this.cache.size}}},je=class{config;cache;totalGenerated=0;generationTimes=[];isInitialized=!1;onnxRuntime=null;constructor(e={}){this.config={model:e.model??"all-MiniLM-L6-v2",normalize:e.normalize??!0,hyperbolic:e.hyperbolic??!1,cacheSize:e.cacheSize??256,curvature:e.curvature??-1},this.cache=new dn(this.config.cacheSize)}async initialize(){if(!this.isInitialized)try{let{computeRealEmbedding:e}=await import("./real-embeddings-4QLQZDB5.js");this.onnxRuntime={generateEmbedding:async(t,n)=>{let r=await e(t);if(this.config.normalize){let i=Math.sqrt(r.reduce((s,a)=>s+a*a,0));if(i>0)return r.map(s=>s/i)}return r},isAvailable:()=>!0},this.isInitialized=!0}catch(e){throw new N("RUNTIME_UNAVAILABLE","Failed to initialize ONNX runtime",e)}}async generate(e){if(this.isInitialized||await this.initialize(),!e||e.trim().length===0)throw new N("INVALID_INPUT","Text cannot be empty");let t=this.getCacheKey(e),n=this.cache.get(t);if(n)return n;let r=Date.now();try{if(!this.onnxRuntime)throw new N("RUNTIME_UNAVAILABLE","ONNX runtime not available");let i=await this.onnxRuntime.generateEmbedding(e,this.config.model),s=i,a=!1;this.config.hyperbolic&&(s=this.euclideanToPoincare(i),a=!0);let c={vector:s,dimensions:s.length,model:this.config.model,isHyperbolic:a};return this.cache.set(t,c),this.totalGenerated++,this.generationTimes.push(Date.now()-r),this.generationTimes.length>100&&this.generationTimes.shift(),c}catch(i){throw new N("MODEL_LOAD_FAILED",`Failed to generate embedding: ${i instanceof Error?i.message:"Unknown error"}`,i)}}async generateBatch(e){if(!e.texts||e.texts.length===0)throw new N("INVALID_INPUT","Batch request must contain at least one text");let t=Date.now(),n=0,r=[],i={...this.config};e.config&&(this.config={...this.config,...e.config});try{for(let s of e.texts){let a=this.getCacheKey(s),c=this.cache.get(a);if(c)r.push(c),n++;else{let l=await this.generate(s);r.push(l)}}return{embeddings:r,duration:Date.now()-t,cacheHits:n}}finally{this.config=i}}getStats(){let e=this.cache.getStats(),t=this.generationTimes.length>0?this.generationTimes.reduce((n,r)=>n+r,0)/this.generationTimes.length:0;return{totalGenerated:this.totalGenerated,cacheHits:e.hits,cacheMisses:e.misses,avgGenerationTime:t,currentModel:this.config.model,vectorsStored:e.size}}clearCache(){this.cache.clear()}updateConfig(e){let t=e.model&&e.model!==this.config.model;this.config={...this.config,...e},e.cacheSize!==void 0&&e.cacheSize!==this.cache.getStats().size&&(this.cache=new dn(e.cacheSize)),t&&(this.isInitialized=!1)}getCacheKey(e){let{model:t,hyperbolic:n,normalize:r,curvature:i}=this.config;return JSON.stringify([t,n,r,i,e])}euclideanToPoincare(e){let t=Math.sqrt(e.reduce((s,a)=>s+a*a,0));if(t===0)return e;let n=Math.abs(this.config.curvature),r=Math.sqrt(n),i=Math.tanh(r*t/2)/(r*t);return e.map(s=>s*i)}isReady(){return this.isInitialized&&this.onnxRuntime!==null}};var ze=class{embeddings;searchCount=0;searchTimes=[];constructor(){this.embeddings=new Map}store(e){this.embeddings.set(e.id,e)}storeBatch(e){for(let t of e)this.store(t)}remove(e){return this.embeddings.delete(e)}clear(){this.embeddings.clear()}async search(e,t={}){let n=Date.now(),r={metric:t.metric??"cosine",topK:t.topK??5,threshold:t.threshold??.5,namespace:t.namespace};try{let i=Array.from(this.embeddings.values());r.namespace&&(i=i.filter(u=>u.namespace===r.namespace));let s=[];for(let u of i){if(u.embedding.dimensions!==e.dimensions)continue;let d=this.calculateSimilarity(e.vector,u.embedding.vector,r.metric);(r.metric==="cosine"?d>=r.threshold:d<=r.threshold)&&s.push({stored:u,score:d})}let a=r.metric==="cosine"?-1:1;s.sort((u,d)=>a*(u.score-d.score));let l=s.slice(0,r.topK).map(({stored:u,score:d})=>({text:u.text,embedding:u.embedding,score:d,metadata:u.metadata}));return this.searchCount++,this.searchTimes.push(Date.now()-n),this.searchTimes.length>100&&this.searchTimes.shift(),l}catch(i){throw new N("DIMENSION_MISMATCH",`Search failed: ${i instanceof Error?i.message:"Unknown error"}`,i)}}async findMostSimilar(e,t={}){let n=await this.search(e,{...t,topK:1});return n.length>0?n[0]:null}calculateSimilarity(e,t,n){if(e.length!==t.length)throw new N("DIMENSION_MISMATCH",`Vector dimensions do not match: ${e.length} vs ${t.length}`);switch(n){case"cosine":return this.cosineSimilarity(e,t);case"euclidean":return this.euclideanDistance(e,t);case"poincare":return this.poincareDistance(e,t);default:throw new N("INVALID_INPUT",`Unknown similarity metric: ${n}`)}}getStats(){let e=this.searchTimes.length>0?this.searchTimes.reduce((t,n)=>t+n,0)/this.searchTimes.length:0;return{searchCount:this.searchCount,avgSearchTime:e,storedCount:this.embeddings.size}}getAll(e){let t=Array.from(this.embeddings.values());return e?t.filter(n=>n.namespace===e):t}get(e){return this.embeddings.get(e)}cosineSimilarity(e,t){let n=0,r=0,i=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],i+=t[a]*t[a];let s=Math.sqrt(r)*Math.sqrt(i);return s===0?0:n/s}euclideanDistance(e,t){let n=0;for(let r=0;r<e.length;r++){let i=e[r]-t[r];n+=i*i}return Math.sqrt(n)}poincareDistance(e,t,n=-1){let r=Math.abs(n),i=Math.sqrt(r),s=e.reduce((p,g)=>p+g*g,0),a=t.reduce((p,g)=>p+g*g,0),c=0;for(let p=0;p<e.length;p++){let g=e[p]-t[p];c+=g*g}let l=2*c,u=(1-s)*(1-a);if(u<=0)return 1/0;let d=l/u;return Math.acosh(1+d)/i}async searchBatch(e,t={}){let n=[];for(let r of e){let i=await this.search(r,t);n.push(i)}return n}async findInRadius(e,t,n="cosine"){return this.search(e,{metric:n,threshold:t,topK:this.embeddings.size})}};var Ue=class{config;constructor(e={}){if(this.config={curvature:e.curvature??-1,epsilon:e.epsilon??1e-7},this.config.curvature>=0)throw new N("HYPERBOLIC_ERROR","Curvature must be negative for hyperbolic space")}euclideanToPoincare(e){if(e.isHyperbolic)return e;let t=e.vector,n=this.norm(t);if(n<this.config.epsilon)return{...e,isHyperbolic:!0};let r=Math.abs(this.config.curvature),i=Math.sqrt(r),s=Math.tanh(i*n/2)/(i*n),a=t.map(l=>l*s),c=this.norm(a);if(c>=1-this.config.epsilon)throw new N("HYPERBOLIC_ERROR",`Poincar\xE9 ball constraint violated: norm = ${c}`);return{vector:a,dimensions:e.dimensions,model:e.model,isHyperbolic:!0}}poincareToEuclidean(e){if(!e.isHyperbolic)return e;let t=e.vector,n=this.norm(t);if(n<this.config.epsilon)return{...e,isHyperbolic:!1};let r=Math.abs(this.config.curvature),i=Math.sqrt(r),s=i*n;if(s>=1)throw new N("HYPERBOLIC_ERROR","Point is on or outside Poincar\xE9 ball boundary");let a=2/i*Math.atanh(s)/n;return{vector:t.map(l=>l*a),dimensions:e.dimensions,model:e.model,isHyperbolic:!1}}distance(e,t){if(e.dimensions!==t.dimensions)throw new N("DIMENSION_MISMATCH","Embeddings must have same dimensions");if(!e.isHyperbolic||!t.isHyperbolic)throw new N("HYPERBOLIC_ERROR","Both embeddings must be in hyperbolic space");let n=e.vector,r=t.vector,i=Math.abs(this.config.curvature),s=Math.sqrt(i),a=this.normSquared(n),c=this.normSquared(r),u=2*this.euclideanDistanceSquared(n,r),d=(1-a)*(1-c);if(d<=this.config.epsilon)return 1/0;let m=u/d;return Math.acosh(1+m)/s}midpoint(e,t){if(e.dimensions!==t.dimensions)throw new N("DIMENSION_MISMATCH","Embeddings must have same dimensions");if(!e.isHyperbolic||!t.isHyperbolic)throw new N("HYPERBOLIC_ERROR","Both embeddings must be in hyperbolic space");let n=e.vector,r=t.vector;return{vector:this.mobiusAddition(n,this.mobiusScalarMultiply(this.mobiusAddition(this.mobiusNegate(n),r),.5)),dimensions:e.dimensions,model:e.model,isHyperbolic:!0}}mobiusAddition(e,t){let n=Math.abs(this.config.curvature),r=this.dot(e,t),i=this.normSquared(e),s=this.normSquared(t),a=1+2*n*r+n*s,c=1-n*i,l=1+2*n*r+n*n*i*s;if(Math.abs(l)<this.config.epsilon)throw new N("HYPERBOLIC_ERROR","M\xF6bius addition denominator is zero");return e.map((d,m)=>(a*d+c*t[m])/l)}mobiusScalarMultiply(e,t){let n=Math.abs(this.config.curvature),r=Math.sqrt(n),i=this.norm(e);if(i<this.config.epsilon)return e;let s=r*i;if(Math.abs(s)>=1)throw new N("HYPERBOLIC_ERROR","M\xF6bius scalar multiplication out of bounds");let a=Math.tanh(t*Math.atanh(s))/(r*i);return e.map(c=>c*a)}mobiusNegate(e){return e.map(t=>-t)}projectToBall(e){let t=this.norm(e);if(t>=1-this.config.epsilon){let n=(1-this.config.epsilon)/t;return e.map(r=>r*n)}return e}norm(e){return Math.sqrt(this.normSquared(e))}normSquared(e){return e.reduce((t,n)=>t+n*n,0)}dot(e,t){return e.reduce((n,r,i)=>n+r*t[i],0)}euclideanDistanceSquared(e,t){return e.reduce((n,r,i)=>{let s=r-t[i];return n+s*s},0)}updateConfig(e){if(e.curvature!==void 0&&e.curvature>=0)throw new N("HYPERBOLIC_ERROR","Curvature must be negative");this.config={...this.config,...e}}getConfig(){return{...this.config}}};ue();var ht=class{generator;search;hyperbolic;isInitialized=!1;constructor(e={}){this.generator=new je(e.embedding),this.search=new ze,this.hyperbolic=new Ue(e.hyperbolic),e.autoInitialize!==!1&&this.initialize().catch(t=>{console.error("Failed to auto-initialize ONNX embeddings:",t)})}async initialize(){if(!this.isInitialized)try{await this.generator.initialize(),this.isInitialized=!0}catch(e){throw new N("RUNTIME_UNAVAILABLE","Failed to initialize ONNX embeddings adapter",e)}}async getHealth(){try{let e=this.generator.isReady();return{available:e,modelLoaded:e?this.getStats().currentModel:null,system:{memory:process.memoryUsage().heapUsed,threads:1}}}catch(e){return{available:!1,modelLoaded:null,error:e instanceof Error?e.message:"Unknown error",system:{memory:process.memoryUsage().heapUsed,threads:0}}}}async generateEmbedding(e){return await this.ensureInitialized(),this.generator.generate(e)}async generateBatch(e){return await this.ensureInitialized(),this.generator.generateBatch(e)}async generateAndStore(e,t){let n=await this.generateEmbedding(e),r={id:t?.id??this.generateId(),text:e,embedding:n,namespace:t?.namespace,metadata:t?.customData,createdAt:Date.now()};this.search.store(r);try{let i=Q();await i.initialize(),await i.vectorStore(r.id,r.embedding.vector,r.namespace??"onnx",{text:r.text,customData:r.metadata,createdAt:r.createdAt})}catch{}return r}async searchByText(e,t){let n=await this.generateEmbedding(e);return this.search.search(n,t)}async searchByEmbedding(e,t){return this.search.search(e,t)}async findMostSimilar(e,t){let n=await this.generateEmbedding(e);return this.search.findMostSimilar(n,t)}async compareSimilarity(e,t,n="cosine"){let[r,i]=await this.generateBatch({texts:[e,t]}).then(s=>s.embeddings);return this.search.calculateSimilarity(r.vector,i.vector,n)}storeEmbedding(e){this.search.store(e)}storeBatch(e){this.search.storeBatch(e)}removeEmbedding(e){return this.search.remove(e)}getEmbedding(e){return this.search.get(e)}getAllEmbeddings(e){return this.search.getAll(e)}clearEmbeddings(){this.search.clear()}toHyperbolic(e){return this.hyperbolic.euclideanToPoincare(e)}toEuclidean(e){return this.hyperbolic.poincareToEuclidean(e)}hyperbolicDistance(e,t){return this.hyperbolic.distance(e,t)}hyperbolicMidpoint(e,t){return this.hyperbolic.midpoint(e,t)}projectToBall(e){return this.hyperbolic.projectToBall(e)}getStats(){let e=this.generator.getStats(),t=this.search.getStats();return{totalGenerated:e.totalGenerated??0,cacheHits:e.cacheHits??0,cacheMisses:e.cacheMisses??0,totalSearches:t.searchCount,avgGenerationTime:e.avgGenerationTime??0,avgSearchTime:t.avgSearchTime,currentModel:e.currentModel??"all-MiniLM-L6-v2",vectorsStored:t.storedCount}}updateEmbeddingConfig(e){this.generator.updateConfig(e)}updateHyperbolicConfig(e){this.hyperbolic.updateConfig(e)}clearCaches(){this.generator.clearCache()}reset(){this.clearCaches(),this.clearEmbeddings()}async bridgeToMCPGenerate(e,t=!1){let n=await this.generateEmbedding(e);return t?this.toHyperbolic(n):n}async bridgeToMCPSearch(e,t){return this.searchByText(e,t)}async bridgeToMCPCompare(e,t,n="cosine"){return this.compareSimilarity(e,t,n)}async ensureInitialized(){this.isInitialized||await this.initialize()}generateId(){return`emb_${Date.now()}_${il().slice(0,9)}`}isReady(){return this.isInitialized&&this.generator.isReady()}};function gn(o){return new ht(o)}var Ir={enabled:!0,dbPath:".agentic-qe/memory.db",maxOutcomes:1e5,retentionDays:90,autoCleanup:!0,cleanupIntervalMs:3600*1e3};ue();k();X();var ml={enabled:!0,haikuThreshold:.8,sonnetThreshold:.4,includeHealthSnapshot:!1,enableLogging:!0},Dr=class{config;minCutService;constructor(e){this.config={...ml,...e},this.minCutService=Xs()}route(e){let t=Date.now();if(!this.config.enabled)return this.createFallbackResult(e,t,"MinCut routing disabled");let n=e.agentTopology||this.config.defaultTopology;if(!n||n.length===0)return this.createFallbackResult(e,t,"No agent topology available for mincut analysis");try{let r=this.minCutService.computeRoutingTier(e.task,n),i=this.routingTierToModelTier(r.tier);e.isCritical&&i<2&&(i=2);let s=this.modelTierToLabel(i),a;if(this.config.includeHealthSnapshot){let u=e.taskGraph||this.minCutService.buildTaskGraphFromTopology(n);a=this.minCutService.getStructuralHealth(u)}let c=Date.now()-t,l={modelTier:i,tierLabel:s,lambda:r.lambda,normalizedLambda:r.normalizedLambda,confidence:r.confidence,rationale:r.rationale,usedMinCut:!0,healthSnapshot:a,decisionTimeMs:c};return this.config.enableLogging&&this.logDecision(l),l}catch(r){return this.createFallbackResult(e,t,`MinCut routing error: ${r instanceof Error?r.message:String(r)}`)}}getMinCutService(){return this.minCutService}isEnabled(){return this.config.enabled}routingTierToModelTier(e){switch(e){case 1:return 1;case 2:return 2;case 3:return 4;default:return 2}}modelTierToLabel(e){switch(e){case 0:return"Booster";case 1:return"Haiku";case 2:return"Sonnet";case 3:return"Sonnet-Extended";case 4:return"Opus";default:return"Sonnet"}}createFallbackResult(e,t,n){return{modelTier:(e.isCritical,2),tierLabel:"Sonnet",lambda:0,normalizedLambda:0,confidence:.3,rationale:`Fallback to Sonnet: ${n}`,usedMinCut:!1,decisionTimeMs:Date.now()-t}}logDecision(e){let t=e.usedMinCut?"MinCut":"Fallback";console.error(`[MinCutRouter] [${t}] Tier ${e.modelTier} (${e.tierLabel}) | Lambda: ${e.normalizedLambda.toFixed(3)} | Confidence: ${(e.confidence*100).toFixed(0)}% | Time: ${e.decisionTimeMs}ms`)}};function Sa(o){return new Dr(o)}import{existsSync as pl}from"fs";import{join as gl}from"path";var fn=class{id="memory";name="Pattern Memory";priority=80;maxTokens=2e3;async gather(e){let t=[];try{let n=gl(process.cwd(),".agentic-qe","memory.db");if(!pl(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-MSTD2GDH.js"),i=r(n,{readonly:!0});try{let s=this.extractDomainKeywords(e.taskDescription);if(s.length>0){let a=s.map(()=>"domain LIKE ?").join(" OR "),c=s.map(d=>`%${d}%`),u=i.prepare(`SELECT name, domain, description, confidence
361
+ `).get(e);return{merged:t,pruned:n,retained:s?.count??0}}async getEvolutionHistory(e,t=20){this.ensureInitialized();let i=(this.prepared.get("getVersionHistory")?.all(e,t)??[]).map(l=>({id:l.id,patternId:l.pattern_id,version:l.version,embedding:this.bufferToFloatArray(l.embedding,l.embedding_dimension),changes:M(l.changes||"[]"),qualityScore:l.quality_score,successRate:l.success_rate,timestamp:new Date(l.created_at),trigger:l.trigger})),c=(this.prepared.get("getEvents")?.all(e,t)??[]).map(l=>({id:l.id,patternId:l.pattern_id,eventType:l.event_type,details:M(l.details||"{}"),timestamp:new Date(l.created_at)}));return{versions:i,events:c}}async recordEvent(e,t,n){let r=this.prepared.get("insertEvent");if(r){let i={id:G(),patternId:e,eventType:t,details:n,timestamp:new Date};r.run(i.id,e,t,JSON.stringify(n)),this.recentEvents.push(i)}}getStats(){return{...this.stats,embeddingCacheSize:this.embeddingCache.size,recentEventsSize:this.recentEvents.length}}async dispose(){this.embeddingCache.clear(),this.recentEvents.clear(),this.prepared.clear(),this.db=null,this.unifiedMemory=null,this.initialized=!1,console.log("[PatternEvolution] Disposed")}ensureInitialized(){if(!this.initialized)throw new Error("PatternEvolution not initialized. Call initialize() first.")}floatArrayToBuffer(e){let t=Buffer.alloc(e.length*4);for(let n=0;n<e.length;n++)t.writeFloatLE(e[n],n*4);return t}bufferToFloatArray(e,t){let n=[];for(let r=0;r<t;r++)n.push(e.readFloatLE(r*4));return n}};function kr(o={}){return new un(o)}k();var Vc={base:{},trajectoryTracker:{},experienceReplay:{},patternEvolution:{},enableTrajectories:!0,enableExperienceReplay:!0,enablePatternEvolution:!0,autoStoreExperiences:!0,autoConsolidate:!0,consolidationIntervalMs:3600*1e3},Mr=class{config;reasoningBank=null;trajectoryTracker=null;experienceReplay=null;patternEvolution=null;initialized=!1;consolidationTimer=null;stats={tasksRouted:0,trajectoriesCompleted:0,experiencesApplied:0,tokensSavedEstimate:0,avgTaskSpeedupPercent:0,successRate:0,totalSuccesses:0,totalTasks:0};constructor(e={}){this.config={...Vc,...e}}async initialize(){if(this.initialized)return;let e=performance.now();this.reasoningBank=br(this.config.base),await this.reasoningBank.initialize(),this.config.enableTrajectories&&(this.trajectoryTracker=xr(this.config.trajectoryTracker),await this.trajectoryTracker.initialize()),this.config.enableExperienceReplay&&(this.experienceReplay=Ar(this.config.experienceReplay),await this.experienceReplay.initialize()),this.config.enablePatternEvolution&&(this.patternEvolution=kr(this.config.patternEvolution),await this.patternEvolution.initialize()),this.config.autoConsolidate&&this.patternEvolution&&this.startConsolidationTimer(),this.initialized=!0;let t=performance.now()-e;console.log(`[EnhancedReasoningBank] Initialized in ${t.toFixed(0)}ms`)}async routeTaskWithExperience(e){this.ensureInitialized(),this.stats.tasksRouted++;try{let t=await this.reasoningBank.routeTask(e);if(!t.success)return t;let n={...t.value};if(this.experienceReplay){let r=await this.experienceReplay.getGuidance(e.task,e.domain);r&&(n.experienceGuidance=r,n.guidance=[`Strategy: ${r.recommendedStrategy}`,...r.suggestedActions.map(i=>`Action: ${i}`),...n.guidance])}if(this.trajectoryTracker){let r=await this.trajectoryTracker.findSimilarTrajectories(e.task,3);r.length>0&&(n.similarTrajectories=r.map(i=>({id:i.id,task:i.task,outcome:i.outcome,similarity:.8})))}return _(n)}catch(t){return L(z(t))}}async startTaskTrajectory(e,t={}){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");return this.trajectoryTracker.startTrajectory(e,t)}async recordTaskStep(e,t,n,r){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");await this.trajectoryTracker.recordStep(e,t,n,r)}async endTaskTrajectory(e,t,n){if(this.ensureInitialized(),!this.trajectoryTracker)throw new Error("Trajectory tracking not enabled");let r=await this.trajectoryTracker.endTrajectory(e,t,n);if(this.stats.trajectoriesCompleted++,this.stats.totalTasks++,t&&this.stats.totalSuccesses++,this.stats.successRate=this.stats.totalSuccesses/this.stats.totalTasks,this.config.autoStoreExperiences&&t&&this.experienceReplay){let i=this.deriveStrategy(r);await this.experienceReplay.storeExperience(r,i)}return r}async getTrajectory(e){return this.ensureInitialized(),this.trajectoryTracker?.getTrajectory(e)??null}async getExperienceGuidance(e,t){return this.ensureInitialized(),this.experienceReplay?this.experienceReplay.getGuidance(e,t):null}async recordExperienceApplication(e,t,n,r=0){this.ensureInitialized(),this.experienceReplay&&(await this.experienceReplay.recordApplication(e,t,n,r),this.stats.experiencesApplied++,this.stats.tokensSavedEstimate+=r)}async storePattern(e){this.ensureInitialized();let t=await this.reasoningBank.storeQEPattern(e);return t.success&&this.patternEvolution&&t.value.embedding&&await this.patternEvolution.trackVersion(t.value.id,t.value.embedding,["Initial version"],"initial"),t}async searchPatterns(e,t){return this.ensureInitialized(),this.reasoningBank.searchQEPatterns(e,t)}async recordPatternOutcome(e){this.ensureInitialized();let t=await this.reasoningBank.recordOutcome(e);if(this.patternEvolution&&e.success!==void 0){let n=await this.patternEvolution.detectDrift(e.patternId);n?.hasSignificantDrift&&console.log(`[EnhancedReasoningBank] Pattern drift detected: ${e.patternId}, recommendation: ${n.recommendation}`)}return t}async detectPatternDrift(e){return this.ensureInitialized(),this.patternEvolution?.detectDrift(e)??null}async findMergeCandidates(e){return this.ensureInitialized(),this.patternEvolution?.findMergeCandidates(e)??[]}async consolidatePatterns(e){return this.ensureInitialized(),this.patternEvolution?this.patternEvolution.autoConsolidate(e):{merged:0,pruned:0,retained:0}}async getPatternHistory(e){return this.ensureInitialized(),this.patternEvolution?.getEvolutionHistory(e)??null}async getStats(){return this.ensureInitialized(),{adapter:this.stats,reasoningBank:await this.reasoningBank.getQEStats(),trajectoryTracker:this.trajectoryTracker?.getStats(),experienceReplay:this.experienceReplay?.getStats(),patternEvolution:this.patternEvolution?.getStats()}}async dispose(){this.consolidationTimer&&(clearInterval(this.consolidationTimer),this.consolidationTimer=null),await this.patternEvolution?.dispose(),await this.experienceReplay?.dispose(),await this.trajectoryTracker?.dispose(),await this.reasoningBank?.dispose(),this.patternEvolution=null,this.experienceReplay=null,this.trajectoryTracker=null,this.reasoningBank=null,this.initialized=!1,console.log("[EnhancedReasoningBank] Disposed")}ensureInitialized(){if(!this.initialized||!this.reasoningBank)throw new Error("EnhancedReasoningBankAdapter not initialized. Call initialize() first.")}startConsolidationTimer(){this.consolidationTimer=setInterval(async()=>{try{let e=["test-generation","coverage-analysis","test-execution","quality-assessment"];for(let t of e){let n=await this.patternEvolution.autoConsolidate(t);(n.merged>0||n.pruned>0)&&console.log(`[EnhancedReasoningBank] Consolidated ${t}: merged=${n.merged}, pruned=${n.pruned}, retained=${n.retained}`)}}catch(e){console.error("[EnhancedReasoningBank] Consolidation error:",e)}},this.config.consolidationIntervalMs)}deriveStrategy(e){let t=e.steps.filter(n=>n.result.outcome==="success").map(n=>n.action);return t.length===0?`Attempted ${e.steps.length} actions for: ${e.task}`:`Used ${t.join(" -> ")} pattern for: ${e.task.substring(0,50)}`}};function Fp(o={}){return new Mr(o)}import{randomUUID as il}from"crypto";var N=class extends Error{constructor(t,n,r){super(n);this.type=t;this.details=r;this.name="EmbeddingError"}type;details};var dn=class{cache;maxSize;hits=0;misses=0;constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);if(t)return this.hits++,this.cache.delete(e),this.cache.set(e,t),t;this.misses++}set(e,t){if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,t)}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){return{hits:this.hits,misses:this.misses,size:this.cache.size}}},je=class{config;cache;totalGenerated=0;generationTimes=[];isInitialized=!1;onnxRuntime=null;constructor(e={}){this.config={model:e.model??"all-MiniLM-L6-v2",normalize:e.normalize??!0,hyperbolic:e.hyperbolic??!1,cacheSize:e.cacheSize??256,curvature:e.curvature??-1},this.cache=new dn(this.config.cacheSize)}async initialize(){if(!this.isInitialized)try{let{computeRealEmbedding:e}=await import("./real-embeddings-TSZ4UIAE.js");this.onnxRuntime={generateEmbedding:async(t,n)=>{let r=await e(t);if(this.config.normalize){let i=Math.sqrt(r.reduce((s,a)=>s+a*a,0));if(i>0)return r.map(s=>s/i)}return r},isAvailable:()=>!0},this.isInitialized=!0}catch(e){throw new N("RUNTIME_UNAVAILABLE","Failed to initialize ONNX runtime",e)}}async generate(e){if(this.isInitialized||await this.initialize(),!e||e.trim().length===0)throw new N("INVALID_INPUT","Text cannot be empty");let t=this.getCacheKey(e),n=this.cache.get(t);if(n)return n;let r=Date.now();try{if(!this.onnxRuntime)throw new N("RUNTIME_UNAVAILABLE","ONNX runtime not available");let i=await this.onnxRuntime.generateEmbedding(e,this.config.model),s=i,a=!1;this.config.hyperbolic&&(s=this.euclideanToPoincare(i),a=!0);let c={vector:s,dimensions:s.length,model:this.config.model,isHyperbolic:a};return this.cache.set(t,c),this.totalGenerated++,this.generationTimes.push(Date.now()-r),this.generationTimes.length>100&&this.generationTimes.shift(),c}catch(i){throw new N("MODEL_LOAD_FAILED",`Failed to generate embedding: ${i instanceof Error?i.message:"Unknown error"}`,i)}}async generateBatch(e){if(!e.texts||e.texts.length===0)throw new N("INVALID_INPUT","Batch request must contain at least one text");let t=Date.now(),n=0,r=[],i={...this.config};e.config&&(this.config={...this.config,...e.config});try{for(let s of e.texts){let a=this.getCacheKey(s),c=this.cache.get(a);if(c)r.push(c),n++;else{let l=await this.generate(s);r.push(l)}}return{embeddings:r,duration:Date.now()-t,cacheHits:n}}finally{this.config=i}}getStats(){let e=this.cache.getStats(),t=this.generationTimes.length>0?this.generationTimes.reduce((n,r)=>n+r,0)/this.generationTimes.length:0;return{totalGenerated:this.totalGenerated,cacheHits:e.hits,cacheMisses:e.misses,avgGenerationTime:t,currentModel:this.config.model,vectorsStored:e.size}}clearCache(){this.cache.clear()}updateConfig(e){let t=e.model&&e.model!==this.config.model;this.config={...this.config,...e},e.cacheSize!==void 0&&e.cacheSize!==this.cache.getStats().size&&(this.cache=new dn(e.cacheSize)),t&&(this.isInitialized=!1)}getCacheKey(e){let{model:t,hyperbolic:n,normalize:r,curvature:i}=this.config;return JSON.stringify([t,n,r,i,e])}euclideanToPoincare(e){let t=Math.sqrt(e.reduce((s,a)=>s+a*a,0));if(t===0)return e;let n=Math.abs(this.config.curvature),r=Math.sqrt(n),i=Math.tanh(r*t/2)/(r*t);return e.map(s=>s*i)}isReady(){return this.isInitialized&&this.onnxRuntime!==null}};var ze=class{embeddings;searchCount=0;searchTimes=[];constructor(){this.embeddings=new Map}store(e){this.embeddings.set(e.id,e)}storeBatch(e){for(let t of e)this.store(t)}remove(e){return this.embeddings.delete(e)}clear(){this.embeddings.clear()}async search(e,t={}){let n=Date.now(),r={metric:t.metric??"cosine",topK:t.topK??5,threshold:t.threshold??.5,namespace:t.namespace};try{let i=Array.from(this.embeddings.values());r.namespace&&(i=i.filter(u=>u.namespace===r.namespace));let s=[];for(let u of i){if(u.embedding.dimensions!==e.dimensions)continue;let d=this.calculateSimilarity(e.vector,u.embedding.vector,r.metric);(r.metric==="cosine"?d>=r.threshold:d<=r.threshold)&&s.push({stored:u,score:d})}let a=r.metric==="cosine"?-1:1;s.sort((u,d)=>a*(u.score-d.score));let l=s.slice(0,r.topK).map(({stored:u,score:d})=>({text:u.text,embedding:u.embedding,score:d,metadata:u.metadata}));return this.searchCount++,this.searchTimes.push(Date.now()-n),this.searchTimes.length>100&&this.searchTimes.shift(),l}catch(i){throw new N("DIMENSION_MISMATCH",`Search failed: ${i instanceof Error?i.message:"Unknown error"}`,i)}}async findMostSimilar(e,t={}){let n=await this.search(e,{...t,topK:1});return n.length>0?n[0]:null}calculateSimilarity(e,t,n){if(e.length!==t.length)throw new N("DIMENSION_MISMATCH",`Vector dimensions do not match: ${e.length} vs ${t.length}`);switch(n){case"cosine":return this.cosineSimilarity(e,t);case"euclidean":return this.euclideanDistance(e,t);case"poincare":return this.poincareDistance(e,t);default:throw new N("INVALID_INPUT",`Unknown similarity metric: ${n}`)}}getStats(){let e=this.searchTimes.length>0?this.searchTimes.reduce((t,n)=>t+n,0)/this.searchTimes.length:0;return{searchCount:this.searchCount,avgSearchTime:e,storedCount:this.embeddings.size}}getAll(e){let t=Array.from(this.embeddings.values());return e?t.filter(n=>n.namespace===e):t}get(e){return this.embeddings.get(e)}cosineSimilarity(e,t){let n=0,r=0,i=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],i+=t[a]*t[a];let s=Math.sqrt(r)*Math.sqrt(i);return s===0?0:n/s}euclideanDistance(e,t){let n=0;for(let r=0;r<e.length;r++){let i=e[r]-t[r];n+=i*i}return Math.sqrt(n)}poincareDistance(e,t,n=-1){let r=Math.abs(n),i=Math.sqrt(r),s=e.reduce((p,g)=>p+g*g,0),a=t.reduce((p,g)=>p+g*g,0),c=0;for(let p=0;p<e.length;p++){let g=e[p]-t[p];c+=g*g}let l=2*c,u=(1-s)*(1-a);if(u<=0)return 1/0;let d=l/u;return Math.acosh(1+d)/i}async searchBatch(e,t={}){let n=[];for(let r of e){let i=await this.search(r,t);n.push(i)}return n}async findInRadius(e,t,n="cosine"){return this.search(e,{metric:n,threshold:t,topK:this.embeddings.size})}};var Ue=class{config;constructor(e={}){if(this.config={curvature:e.curvature??-1,epsilon:e.epsilon??1e-7},this.config.curvature>=0)throw new N("HYPERBOLIC_ERROR","Curvature must be negative for hyperbolic space")}euclideanToPoincare(e){if(e.isHyperbolic)return e;let t=e.vector,n=this.norm(t);if(n<this.config.epsilon)return{...e,isHyperbolic:!0};let r=Math.abs(this.config.curvature),i=Math.sqrt(r),s=Math.tanh(i*n/2)/(i*n),a=t.map(l=>l*s),c=this.norm(a);if(c>=1-this.config.epsilon)throw new N("HYPERBOLIC_ERROR",`Poincar\xE9 ball constraint violated: norm = ${c}`);return{vector:a,dimensions:e.dimensions,model:e.model,isHyperbolic:!0}}poincareToEuclidean(e){if(!e.isHyperbolic)return e;let t=e.vector,n=this.norm(t);if(n<this.config.epsilon)return{...e,isHyperbolic:!1};let r=Math.abs(this.config.curvature),i=Math.sqrt(r),s=i*n;if(s>=1)throw new N("HYPERBOLIC_ERROR","Point is on or outside Poincar\xE9 ball boundary");let a=2/i*Math.atanh(s)/n;return{vector:t.map(l=>l*a),dimensions:e.dimensions,model:e.model,isHyperbolic:!1}}distance(e,t){if(e.dimensions!==t.dimensions)throw new N("DIMENSION_MISMATCH","Embeddings must have same dimensions");if(!e.isHyperbolic||!t.isHyperbolic)throw new N("HYPERBOLIC_ERROR","Both embeddings must be in hyperbolic space");let n=e.vector,r=t.vector,i=Math.abs(this.config.curvature),s=Math.sqrt(i),a=this.normSquared(n),c=this.normSquared(r),u=2*this.euclideanDistanceSquared(n,r),d=(1-a)*(1-c);if(d<=this.config.epsilon)return 1/0;let m=u/d;return Math.acosh(1+m)/s}midpoint(e,t){if(e.dimensions!==t.dimensions)throw new N("DIMENSION_MISMATCH","Embeddings must have same dimensions");if(!e.isHyperbolic||!t.isHyperbolic)throw new N("HYPERBOLIC_ERROR","Both embeddings must be in hyperbolic space");let n=e.vector,r=t.vector;return{vector:this.mobiusAddition(n,this.mobiusScalarMultiply(this.mobiusAddition(this.mobiusNegate(n),r),.5)),dimensions:e.dimensions,model:e.model,isHyperbolic:!0}}mobiusAddition(e,t){let n=Math.abs(this.config.curvature),r=this.dot(e,t),i=this.normSquared(e),s=this.normSquared(t),a=1+2*n*r+n*s,c=1-n*i,l=1+2*n*r+n*n*i*s;if(Math.abs(l)<this.config.epsilon)throw new N("HYPERBOLIC_ERROR","M\xF6bius addition denominator is zero");return e.map((d,m)=>(a*d+c*t[m])/l)}mobiusScalarMultiply(e,t){let n=Math.abs(this.config.curvature),r=Math.sqrt(n),i=this.norm(e);if(i<this.config.epsilon)return e;let s=r*i;if(Math.abs(s)>=1)throw new N("HYPERBOLIC_ERROR","M\xF6bius scalar multiplication out of bounds");let a=Math.tanh(t*Math.atanh(s))/(r*i);return e.map(c=>c*a)}mobiusNegate(e){return e.map(t=>-t)}projectToBall(e){let t=this.norm(e);if(t>=1-this.config.epsilon){let n=(1-this.config.epsilon)/t;return e.map(r=>r*n)}return e}norm(e){return Math.sqrt(this.normSquared(e))}normSquared(e){return e.reduce((t,n)=>t+n*n,0)}dot(e,t){return e.reduce((n,r,i)=>n+r*t[i],0)}euclideanDistanceSquared(e,t){return e.reduce((n,r,i)=>{let s=r-t[i];return n+s*s},0)}updateConfig(e){if(e.curvature!==void 0&&e.curvature>=0)throw new N("HYPERBOLIC_ERROR","Curvature must be negative");this.config={...this.config,...e}}getConfig(){return{...this.config}}};ue();var ht=class{generator;search;hyperbolic;isInitialized=!1;constructor(e={}){this.generator=new je(e.embedding),this.search=new ze,this.hyperbolic=new Ue(e.hyperbolic),e.autoInitialize!==!1&&this.initialize().catch(t=>{console.error("Failed to auto-initialize ONNX embeddings:",t)})}async initialize(){if(!this.isInitialized)try{await this.generator.initialize(),this.isInitialized=!0}catch(e){throw new N("RUNTIME_UNAVAILABLE","Failed to initialize ONNX embeddings adapter",e)}}async getHealth(){try{let e=this.generator.isReady();return{available:e,modelLoaded:e?this.getStats().currentModel:null,system:{memory:process.memoryUsage().heapUsed,threads:1}}}catch(e){return{available:!1,modelLoaded:null,error:e instanceof Error?e.message:"Unknown error",system:{memory:process.memoryUsage().heapUsed,threads:0}}}}async generateEmbedding(e){return await this.ensureInitialized(),this.generator.generate(e)}async generateBatch(e){return await this.ensureInitialized(),this.generator.generateBatch(e)}async generateAndStore(e,t){let n=await this.generateEmbedding(e),r={id:t?.id??this.generateId(),text:e,embedding:n,namespace:t?.namespace,metadata:t?.customData,createdAt:Date.now()};this.search.store(r);try{let i=Q();await i.initialize(),await i.vectorStore(r.id,r.embedding.vector,r.namespace??"onnx",{text:r.text,customData:r.metadata,createdAt:r.createdAt})}catch{}return r}async searchByText(e,t){let n=await this.generateEmbedding(e);return this.search.search(n,t)}async searchByEmbedding(e,t){return this.search.search(e,t)}async findMostSimilar(e,t){let n=await this.generateEmbedding(e);return this.search.findMostSimilar(n,t)}async compareSimilarity(e,t,n="cosine"){let[r,i]=await this.generateBatch({texts:[e,t]}).then(s=>s.embeddings);return this.search.calculateSimilarity(r.vector,i.vector,n)}storeEmbedding(e){this.search.store(e)}storeBatch(e){this.search.storeBatch(e)}removeEmbedding(e){return this.search.remove(e)}getEmbedding(e){return this.search.get(e)}getAllEmbeddings(e){return this.search.getAll(e)}clearEmbeddings(){this.search.clear()}toHyperbolic(e){return this.hyperbolic.euclideanToPoincare(e)}toEuclidean(e){return this.hyperbolic.poincareToEuclidean(e)}hyperbolicDistance(e,t){return this.hyperbolic.distance(e,t)}hyperbolicMidpoint(e,t){return this.hyperbolic.midpoint(e,t)}projectToBall(e){return this.hyperbolic.projectToBall(e)}getStats(){let e=this.generator.getStats(),t=this.search.getStats();return{totalGenerated:e.totalGenerated??0,cacheHits:e.cacheHits??0,cacheMisses:e.cacheMisses??0,totalSearches:t.searchCount,avgGenerationTime:e.avgGenerationTime??0,avgSearchTime:t.avgSearchTime,currentModel:e.currentModel??"all-MiniLM-L6-v2",vectorsStored:t.storedCount}}updateEmbeddingConfig(e){this.generator.updateConfig(e)}updateHyperbolicConfig(e){this.hyperbolic.updateConfig(e)}clearCaches(){this.generator.clearCache()}reset(){this.clearCaches(),this.clearEmbeddings()}async bridgeToMCPGenerate(e,t=!1){let n=await this.generateEmbedding(e);return t?this.toHyperbolic(n):n}async bridgeToMCPSearch(e,t){return this.searchByText(e,t)}async bridgeToMCPCompare(e,t,n="cosine"){return this.compareSimilarity(e,t,n)}async ensureInitialized(){this.isInitialized||await this.initialize()}generateId(){return`emb_${Date.now()}_${il().slice(0,9)}`}isReady(){return this.isInitialized&&this.generator.isReady()}};function gn(o){return new ht(o)}var Ir={enabled:!0,dbPath:".agentic-qe/memory.db",maxOutcomes:1e5,retentionDays:90,autoCleanup:!0,cleanupIntervalMs:3600*1e3};ue();k();X();var ml={enabled:!0,haikuThreshold:.8,sonnetThreshold:.4,includeHealthSnapshot:!1,enableLogging:!0},Dr=class{config;minCutService;constructor(e){this.config={...ml,...e},this.minCutService=Xs()}route(e){let t=Date.now();if(!this.config.enabled)return this.createFallbackResult(e,t,"MinCut routing disabled");let n=e.agentTopology||this.config.defaultTopology;if(!n||n.length===0)return this.createFallbackResult(e,t,"No agent topology available for mincut analysis");try{let r=this.minCutService.computeRoutingTier(e.task,n),i=this.routingTierToModelTier(r.tier);e.isCritical&&i<2&&(i=2);let s=this.modelTierToLabel(i),a;if(this.config.includeHealthSnapshot){let u=e.taskGraph||this.minCutService.buildTaskGraphFromTopology(n);a=this.minCutService.getStructuralHealth(u)}let c=Date.now()-t,l={modelTier:i,tierLabel:s,lambda:r.lambda,normalizedLambda:r.normalizedLambda,confidence:r.confidence,rationale:r.rationale,usedMinCut:!0,healthSnapshot:a,decisionTimeMs:c};return this.config.enableLogging&&this.logDecision(l),l}catch(r){return this.createFallbackResult(e,t,`MinCut routing error: ${r instanceof Error?r.message:String(r)}`)}}getMinCutService(){return this.minCutService}isEnabled(){return this.config.enabled}routingTierToModelTier(e){switch(e){case 1:return 1;case 2:return 2;case 3:return 4;default:return 2}}modelTierToLabel(e){switch(e){case 0:return"Booster";case 1:return"Haiku";case 2:return"Sonnet";case 3:return"Sonnet-Extended";case 4:return"Opus";default:return"Sonnet"}}createFallbackResult(e,t,n){return{modelTier:(e.isCritical,2),tierLabel:"Sonnet",lambda:0,normalizedLambda:0,confidence:.3,rationale:`Fallback to Sonnet: ${n}`,usedMinCut:!1,decisionTimeMs:Date.now()-t}}logDecision(e){let t=e.usedMinCut?"MinCut":"Fallback";console.error(`[MinCutRouter] [${t}] Tier ${e.modelTier} (${e.tierLabel}) | Lambda: ${e.normalizedLambda.toFixed(3)} | Confidence: ${(e.confidence*100).toFixed(0)}% | Time: ${e.decisionTimeMs}ms`)}};function Sa(o){return new Dr(o)}import{existsSync as pl}from"fs";import{join as gl}from"path";var fn=class{id="memory";name="Pattern Memory";priority=80;maxTokens=2e3;async gather(e){let t=[];try{let n=gl(process.cwd(),".agentic-qe","memory.db");if(!pl(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-Q6JUKG2A.js"),i=r(n,{readonly:!0});try{let s=this.extractDomainKeywords(e.taskDescription);if(s.length>0){let a=s.map(()=>"domain LIKE ?").join(" OR "),c=s.map(d=>`%${d}%`),u=i.prepare(`SELECT name, domain, description, confidence
362
362
  FROM qe_patterns
363
363
  WHERE ${a}
364
364
  ORDER BY confidence DESC
@@ -371,7 +371,7 @@ ${r}`;t.push({sourceId:this.id,title:`Git history: ${n}`,content:i,estimatedToke
371
371
  ${a.join(`
372
372
  `)}`;t.push({sourceId:this.id,title:`Tests: ${_r(n)}`,content:c,estimatedTokens:Math.ceil(c.length/3.5),relevance:.8})}}catch{}}return t}findTestPaths(e){let t=_r(e).replace(/\.(ts|js|tsx|jsx)$/,""),n=vl(e),r=[".test.ts",".spec.ts",".test.js",".spec.js"],i=[];for(let s of r)i.push(Or(n,`${t}${s}`)),i.push(Or(n,"__tests__",`${t}${s}`)),i.push(Or(n,"..","tests",`${t}${s}`));return i}};import{existsSync as bl,readFileSync as Cl}from"fs";import{join as Nr,basename as Sl}from"path";var vn=class{id="coverage";name="Coverage Data";priority=50;maxTokens=1e3;async gather(e){let t=[],n=[Nr(process.cwd(),"coverage","coverage-summary.json"),Nr(process.cwd(),"coverage","coverage-final.json"),Nr(process.cwd(),".coverage","coverage-summary.json")];for(let r of n)if(bl(r))try{let i=Cl(r,"utf-8"),s=JSON.parse(i),a=[];for(let c of e.targetFiles){let l=Sl(c);for(let[u,d]of Object.entries(s))if(u.includes(l)&&d&&typeof d=="object"){let m=d,p=m.lines?.pct??m.statements?.pct,g=m.branches?.pct,f=m.functions?.pct;p!==void 0&&a.push(`${l}: lines=${p}%${g!==void 0?`, branches=${g}%`:""}${f!==void 0?`, functions=${f}%`:""}`)}}if(a.length>0){let c=`Coverage for target files:
373
373
  ${a.join(`
374
- `)}`;t.push({sourceId:this.id,title:"File Coverage Data",content:c,estimatedTokens:Math.ceil(c.length/3.5),relevance:.6})}if(s.total&&typeof s.total=="object"){let c=s.total,l=`Project coverage: lines=${c.lines?.pct??"?"}%, branches=${c.branches?.pct??"?"}%, functions=${c.functions?.pct??"?"}%`;t.push({sourceId:this.id,title:"Project Coverage Summary",content:l,estimatedTokens:Math.ceil(l.length/3.5),relevance:.4})}break}catch{continue}return t}};import{existsSync as Tl}from"fs";import{join as El}from"path";var bn=class{id="requirements";name="Requirements Traceability";priority=75;maxTokens=2e3;async gather(e){let t=[];try{let n=El(process.cwd(),".agentic-qe","memory.db");if(!Tl(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-MSTD2GDH.js"),i=r(n,{readonly:!0});try{if(!i.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_patterns'").get())return this.fallbackGather(e);let a=e.targetFiles.map(l=>`%${l.split("/").pop()}%`);if(a.length>0){let l=a.map(()=>"description LIKE ?").join(" OR "),d=i.prepare(`SELECT name, domain, description, confidence
374
+ `)}`;t.push({sourceId:this.id,title:"File Coverage Data",content:c,estimatedTokens:Math.ceil(c.length/3.5),relevance:.6})}if(s.total&&typeof s.total=="object"){let c=s.total,l=`Project coverage: lines=${c.lines?.pct??"?"}%, branches=${c.branches?.pct??"?"}%, functions=${c.functions?.pct??"?"}%`;t.push({sourceId:this.id,title:"Project Coverage Summary",content:l,estimatedTokens:Math.ceil(l.length/3.5),relevance:.4})}break}catch{continue}return t}};import{existsSync as Tl}from"fs";import{join as El}from"path";var bn=class{id="requirements";name="Requirements Traceability";priority=75;maxTokens=2e3;async gather(e){let t=[];try{let n=El(process.cwd(),".agentic-qe","memory.db");if(!Tl(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-Q6JUKG2A.js"),i=r(n,{readonly:!0});try{if(!i.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_patterns'").get())return this.fallbackGather(e);let a=e.targetFiles.map(l=>`%${l.split("/").pop()}%`);if(a.length>0){let l=a.map(()=>"description LIKE ?").join(" OR "),d=i.prepare(`SELECT name, domain, description, confidence
375
375
  FROM qe_patterns
376
376
  WHERE domain LIKE '%requirement%'
377
377
  AND (${l})
@@ -387,7 +387,7 @@ ${m}`,estimatedTokens:Math.ceil(m.length/3.5),relevance:.75})}}let c=this.extrac
387
387
  LIMIT 5`).all(...u);if(m.length>0){let p=m.map(g=>`- **${g.name}**: ${g.description||"No description"}`).join(`
388
388
  `);t.push({sourceId:this.id,title:"Related Requirements",content:`Requirements related to task:
389
389
 
390
- ${p}`,estimatedTokens:Math.ceil(p.length/3.5),relevance:.6})}}}finally{i.close()}}catch{return this.fallbackGather(e)}return t.length===0?this.fallbackGather(e):t}fallbackGather(e){let n=`No requirements traceability data found for: ${e.targetFiles.join(", ")}. Consider running requirements validation to establish traceability.`;return[{sourceId:this.id,title:"Requirements Context",content:n,estimatedTokens:Math.ceil(n.length/3.5),relevance:.3}]}extractRequirementKeywords(e){let t=[],n=e.toLowerCase(),r=n.match(/(?:req|us|story|epic|feat)-?\d+/gi)||[];t.push(...r);let i=["authentication","authorization","payment","registration","notification","search","api","login","user","admin","report","dashboard","import","export","integration"];for(let s of i)n.includes(s)&&t.push(s);return t.slice(0,5)}};import{existsSync as wl}from"fs";import{join as Rl}from"path";var Cn=class{id="defects";name="Defect Intelligence";priority=65;maxTokens=1500;async gather(e){let t=[];try{let n=Rl(process.cwd(),".agentic-qe","memory.db");if(!wl(n))return[];let{openDatabase:r}=await import("./safe-db-MSTD2GDH.js"),i=r(n,{readonly:!0});try{if(!i.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_patterns'").get())return[];let a=e.targetFiles.map(l=>`%${l.split("/").pop()}%`);if(a.length>0){let l=a.map(()=>"description LIKE ?").join(" OR "),d=i.prepare(`SELECT name, domain, description, confidence
390
+ ${p}`,estimatedTokens:Math.ceil(p.length/3.5),relevance:.6})}}}finally{i.close()}}catch{return this.fallbackGather(e)}return t.length===0?this.fallbackGather(e):t}fallbackGather(e){let n=`No requirements traceability data found for: ${e.targetFiles.join(", ")}. Consider running requirements validation to establish traceability.`;return[{sourceId:this.id,title:"Requirements Context",content:n,estimatedTokens:Math.ceil(n.length/3.5),relevance:.3}]}extractRequirementKeywords(e){let t=[],n=e.toLowerCase(),r=n.match(/(?:req|us|story|epic|feat)-?\d+/gi)||[];t.push(...r);let i=["authentication","authorization","payment","registration","notification","search","api","login","user","admin","report","dashboard","import","export","integration"];for(let s of i)n.includes(s)&&t.push(s);return t.slice(0,5)}};import{existsSync as wl}from"fs";import{join as Rl}from"path";var Cn=class{id="defects";name="Defect Intelligence";priority=65;maxTokens=1500;async gather(e){let t=[];try{let n=Rl(process.cwd(),".agentic-qe","memory.db");if(!wl(n))return[];let{openDatabase:r}=await import("./safe-db-Q6JUKG2A.js"),i=r(n,{readonly:!0});try{if(!i.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_patterns'").get())return[];let a=e.targetFiles.map(l=>`%${l.split("/").pop()}%`);if(a.length>0){let l=a.map(()=>"description LIKE ?").join(" OR "),d=i.prepare(`SELECT name, domain, description, confidence
391
391
  FROM qe_patterns
392
392
  WHERE domain LIKE '%defect%'
393
393
  AND (${l})
@@ -413,9 +413,9 @@ ${d.slice(0,4e3)}`))}catch(n){return L(z(n))}})}k();import{randomUUID as Zl}from
413
413
  ${e.trim()}`}function Gl(o,e,t=e,n=10){let r=$.resolve(o);for(let i=0;i<=n;i++){let s=$.join(r,"node_modules",e);try{let c=JSON.parse(j.readFileSync($.join(s,"package.json"),"utf-8")),l=typeof c.bin=="string"?c.bin:c.bin?.[t];if(l){let u=$.join(s,l);if(j.existsSync(u))return u}}catch{}let a=$.dirname(r);if(a===r)break;r=a}return null}function jl(o){try{let e=M(j.readFileSync($.join(o,"package.json"),"utf-8"));return{...e.devDependencies||{},...e.dependencies||{}}}catch{return{}}}var zl=["jest","@jest/core","mocha","nyc","vitest"];function zr(o,e=10){let t=[],n=null;try{n=j.realpathSync(Pn.homedir())}catch{n=null}let r=$.resolve(o);for(let i=0;i<=e&&!(i>0&&n!==null&&r===n||(t.push(r),j.existsSync($.join(r,".git"))||Ul(r)));i++){let s=$.dirname(r);if(s===r)break;r=s}return t}function Ul(o){try{return JSON.parse(j.readFileSync($.join(o,"package.json"),"utf-8")).workspaces!==void 0}catch{return!1}}function Bl(o){for(let e of zr(o)){let t=jl(e);if(zl.some(n=>t[n]))return t}return{}}function Hl(o){return zr(o).map(e=>$.join(e,"node_modules",".bin")).filter(e=>j.existsSync(e))}function Vl(o){return zr(o).some(e=>j.existsSync($.join(e,".pnp.cjs"))||j.existsSync($.join(e,".pnp.js")))}function Ql(o,e){let t=$.join(e,Fl),n=Bl(o),r="vitest",i,s=t;n.jest||n["@jest/core"]?(r="jest",i=["--coverage",`--coverageDirectory=${e}`,"--coverageReporters=json","--json",`--outputFile=${t}`]):n.mocha||n.nyc?(r="nyc",i=[`--report-dir=${e}`,`--temp-dir=${$.join(e,".nyc_output")}`,"--reporter=json","mocha"],s=null):i=["run","--coverage",`--coverage.reportsDirectory=${e}`,"--coverage.reporter=json","--coverage.reportOnFailure=true","--reporter=json",`--outputFile=${t}`];let a=Gl(o,r==="jest"?"jest":r);return{runner:r,command:a?process.execPath:null,args:a?[a,...i]:i,resultsFile:s}}var Gr={numTotalTests:null,numPassedTests:null,numFailedTests:null,numPendingTests:null,numFailedTestSuites:null};function Wl(o){if(!o)return Gr;try{let e=JSON.parse(j.readFileSync(o,"utf-8")),t=n=>typeof e[n]=="number"?e[n]:null;return{numTotalTests:t("numTotalTests"),numPassedTests:t("numPassedTests"),numFailedTests:t("numFailedTests"),numPendingTests:t("numPendingTests"),numFailedTestSuites:t("numFailedTestSuites")}}catch{return Gr}}async function Kl(o){let e=await Zs(o);if(e)return e;try{let t=JSON.parse(j.readFileSync(o,"utf-8"));if(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0)return{files:[],summary:{line:0,branch:0,function:0,statement:0,files:0}}}catch{}return null}var Rn=new Map,xa=!1;function yt(o,e){if(process.platform==="win32"){try{Nl("taskkill",["/pid",String(o),"/T","/F"],{stdio:"ignore"})}catch{}return}try{process.kill(-o,e)}catch{}}function Xl(){for(let[o,e]of Rn)if(yt(o,"SIGKILL"),e)try{j.rmSync(e,{recursive:!0,force:!0})}catch{}Rn.clear()}function Yl(){xa||(process.on("exit",Xl),xa=!0)}function jr(o){try{return process.kill(-o,0),!0}catch{return!1}}async function Aa(o,e){if(process.platform==="win32")return;let t=Date.now()+e;for(;jr(o)&&Date.now()<t;)await new Promise(n=>setTimeout(n,50))}async function Jl(o,e,t){let n=t.graceMs??3e3,r=process.platform==="win32";return Yl(),new Promise(i=>{let s=!1,a=!1,c="",l="",u=0,d=Ol(o,e,{cwd:t.cwd,env:t.env??process.env,detached:!r,shell:!1,stdio:["ignore","ignore","pipe"],windowsHide:!0});d.pid!==void 0&&Rn.set(d.pid,t.cleanupDir),d.stderr?.on("data",g=>{let f=g.toString("utf-8");u+=g.length,l.length<Pa&&(l=(l+f).slice(0,Pa)),c=(c+f).slice(-Ma)}),d.stderr?.on("error",()=>{});let m=async(g,f)=>{a||(a=!0,clearTimeout(p),d.pid!==void 0&&!r&&jr(d.pid)&&(yt(d.pid,"SIGTERM"),await Aa(d.pid,n),jr(d.pid)&&yt(d.pid,"SIGKILL"),await Aa(d.pid,n)),d.stderr?.destroy(),d.pid!==void 0&&Rn.delete(d.pid),i({exitCode:g,timedOut:s,spawnError:f,pid:d.pid,stderrTail:$l(l,c,u)}))},p=setTimeout(()=>{s=!0,d.pid!==void 0&&(yt(d.pid,"SIGTERM"),setTimeout(()=>{!a&&d.pid!==void 0&&yt(d.pid,"SIGKILL")},n).unref())},t.timeoutMs);d.on("error",()=>{m(null,!0)}),d.on("exit",g=>{m(g,!1)})})}async function Ia(o,e={}){let t=e.timeoutMs??12e4,n=j.mkdtempSync($.join(Pn.tmpdir(),"aqe-js-cov-"));try{let r=Ql(o,n);if(!r.command)return{runner:r.runner,missing:!0,exitCode:null,exitedCleanly:!1,timedOut:!1,timeoutMs:t,data:null,numTotalTests:null,stderrTail:""};let i=Hl(o),s=$.join(n,"tmp");j.mkdirSync(s);let a={...process.env,PATH:[...i,process.env.PATH??""].join($.delimiter),TMPDIR:s,TMP:s,TEMP:s},c=await Jl(r.command,r.args,{cwd:o,timeoutMs:t,cleanupDir:n,env:a}),l=c.timedOut?null:await Kl($.join(n,"coverage-final.json"));return{runner:r.runner,missing:!1,exitCode:c.exitCode,exitedCleanly:c.exitCode===0&&!c.timedOut,timedOut:c.timedOut,timeoutMs:t,data:l,...c.timedOut?Gr:Wl(r.resultsFile),stderrTail:c.stderrTail}}finally{try{j.rmSync(n,{recursive:!0,force:!0})}catch{}}}function Da(o,e){if(o.missing&&Vl(e))return`${o.runner} could not be resolved for ${e}: this project uses Yarn Plug'n'Play, and agentic-qe resolves test runners only from node_modules. Nothing was run and nothing was downloaded. Generate a coverage report (e.g. \`yarn ${o.runner} --coverage\`) and pass it as the target, or use the node-modules linker.`;if(o.missing)return`${o.runner} is not installed in ${e} (no node_modules/${o.runner} found); nothing was run and nothing was downloaded. Install it, or generate a coverage report and pass it as the target.`;if(o.timedOut)return`The coverage run timed out after ${Math.round(o.timeoutMs/1e3)}s and was stopped.`;if(o.exitCode!==0){let t=o.stderrTail?`: ${o.stderrTail}`:"";return`Test runner (${o.runner}) exited with code ${o.exitCode??"unknown"} without a coverage report${t}`}return`Test runner (${o.runner}) exited cleanly but wrote no coverage report. Ensure a coverage provider is configured (e.g., @vitest/coverage-v8, istanbul).`}function eu(o=process.env){let e=Number.parseInt(o.AQE_COVERAGE_TIMEOUT_MS??"",10);return Number.isFinite(e)&&e>0?e:12e4}function Oa(o){let e=s=>o.reduce((a,c)=>a+s(c),0),t=(s,a)=>a>0?Math.round(s/a*100):0,n=e(s=>s.lines.total),r=e(s=>s.lines.covered),i=e(s=>s.statements.total);return{line:t(r,n),branch:t(e(s=>s.branches.covered),e(s=>s.branches.total)),function:t(e(s=>s.functions.covered),e(s=>s.functions.total)),statement:i>0?t(e(s=>s.statements.covered),i):t(r,n),files:o.length}}function tu(o){return{data:{files:o,summary:Oa(o)},provenance:{method:"instrumented-report",estimated:!1,branchDataCollected:o.some(e=>e.branches.total>0),functionDataCollected:o.some(e=>e.functions.total>0),notes:[]}}}function _a(o,e,t){return o.status==="measured"?{collected:tu(o.files),ranTests:e,projectRoot:t}:{collected:null,ranTests:e,noData:o.reason,projectRoot:t}}async function nu(o){let e=await na(o);if(e.status==="target-missing")return{collected:null,ranTests:!1,noData:"target-missing",projectRoot:null};if(e.status==="evaluated")return _a(e.evaluation,!1,e.projectRoot);let{target:t,projectRoot:n}=e;if(Sr(t)){let c=await Js(t);if(c){let l=Ys(t)??n,u=ea(c.data,l,t);return u.length===0?{collected:null,ranTests:!0,noData:"target-not-covered",projectRoot:l}:{collected:u.length===c.data.files.length?c:{data:{files:u,summary:Oa(u)},provenance:c.provenance},ranTests:!0,projectRoot:l}}return{collected:tn(t),ranTests:!1,projectRoot:n}}if(Cr())return{collected:tn(t),ranTests:!1,projectRoot:n};let r=await Ia(n,{timeoutMs:eu()}),i=r.data!==null&&r.data.files.length===0&&r.numTotalTests===null&&!r.exitedCleanly;if(r.data&&!i||r.numTotalTests===0){let c=r.data?ta(r.data,n,t,{numTotalTests:r.numTotalTests}):{status:"no-data",reason:"no-tests-ran"},l=_a(c,r.exitedCleanly||r.data!==null,n);return l.collected&&(l.runStatus=ka(r),typeof r.numPassedTests=="number"&&typeof r.numFailedTests=="number"&&(l.testRun={runId:Zl(),passed:r.numPassedTests,failed:r.numFailedTests,skipped:r.numPendingTests??0})),l}let s=tn(t),a=Da(r,n);return s&&(s.provenance.notes=[`${a} These numbers are a STATIC ESTIMATE derived from source shape \u2014 not measured coverage, and must not be reported as such.`,...s.provenance.notes.filter(c=>!/^No instrumentation ran/.test(c))]),{collected:s,ranTests:r.exitedCleanly,projectRoot:n,notes:s?[]:[a]}}function ru(o,e,t,n){return o?Tr(o,t,n):e?"Tests ran but no coverage output was generated. Ensure a coverage provider is configured (e.g., @vitest/coverage-v8, istanbul).":"No coverage data found and could not run tests automatically. "+Na(t)}function Na(o){return Cr()?"Coverage tooling execution is disabled (AQE_COVERAGE_NO_EXEC). No tests were run and no build tooling was invoked. Unset it, or generate a coverage report yourself and re-run, to get real measurements.":Sr(o)?"To get real measurements for this Rust crate, install cargo-llvm-cov (`cargo install cargo-llvm-cov`) and re-run; agentic-qe will invoke it automatically.":"To get real measurements, run your tests with coverage enabled (e.g. `npm test -- --coverage`, `pytest --cov`) and re-run this analysis."}function Ur(o){o.registerHandler("analyze-coverage",async e=>{let t=e.payload;try{let n=o.getCoverageAnalyzer(),r=t.target||process.cwd(),i=t.threshold||80,{collected:s,ranTests:a,noData:c,projectRoot:l,notes:u,runStatus:d,testRun:m}=await nu(r);if(c==="target-missing")return L(new Error(Tr("target-missing",r,null)));if(!s){let F=c!==void 0&&sa(c);return _({lineCoverage:null,branchCoverage:null,functionCoverage:null,statementCoverage:null,totalFiles:0,coverageByFile:[],gaps:[],estimated:!1,measured:!1,coverageMethod:"none",...F?{unmeasured:!0}:{},algorithm:"sublinear-O(log n)",warning:u?.length?u.join(" "):ru(c,a,r,l)})}let{data:p,provenance:g}=s,f=await n.analyze({coverageData:p,threshold:i,includeFileDetails:t.detectGaps,measured:!g.estimated,...l?{projectRoot:l}:{},...d&&!g.estimated?{runStatus:d}:{},...m&&!g.estimated?{testRun:m}:{}});if(!f.success)return f;let h=f.value,v=[];if(t.detectGaps){let F=await n.findGaps(p,i);F.success&&(v=F.value.gaps.map(B=>({file:B.file,lines:B.lines,risk:B.severity,estimated:g.estimated,...g.estimated?{confidence:.2,reason:"Possible coverage gap (STATIC ESTIMATE \u2014 no instrumentation ran)"}:{}})))}let y=F=>Math.round(F*10)/10,C=(F,B)=>B>0?Math.round(F/B*1e3)/10:null,b=[...g.notes,...u??[]];g.estimated&&b.push(Na(r));let w=g.estimated||ds(p.files).statement,T={branch:g.branchDataCollected,function:g.functionDataCollected,statement:w},S=ra(h.summary,i,T),x=ia(h.recommendations,S,i,T);return _({lineCoverage:y(h.summary.line),branchCoverage:g.branchDataCollected?y(h.summary.branch):null,functionCoverage:g.functionDataCollected?y(h.summary.function):null,statementCoverage:w?y(h.summary.statement):null,totalFiles:h.summary.files,coverageByFile:p.files.map(F=>({file:F.path,lineCoverage:C(F.lines.covered,F.lines.total)??0,branchCoverage:g.branchDataCollected?C(F.branches.covered,F.branches.total):null,functionCoverage:g.functionDataCollected?C(F.functions.covered,F.functions.total):null})),gaps:v,meetsThreshold:S.meetsThreshold,delta:h.delta,recommendations:x,algorithm:"sublinear-O(log n)",estimated:g.estimated,measured:!g.estimated,coverageMethod:g.method,branchDataCollected:g.branchDataCollected,functionDataCollected:g.functionDataCollected,statementDataCollected:w,...d&&!g.estimated?{runStatus:d}:{},...b.length>0?{warning:b.join(" ")}:{}})}catch(n){return L(z(n))}})}import*as Br from"fs/promises";import*as we from"path";k();import{createHash as xn}from"node:crypto";function Vr(o){o.registerHandler("scan-security",async e=>{let t=e.payload;try{let n=we.resolve(t.target||process.cwd()),r=t.sast!==!1,i=r?await oa(n):void 0,s=i?.files??[],a=[],c=[],l=new Map,u=[],d=[],m=new Map,p=[],g=s.filter(P=>/\.(ts|tsx|js|jsx|mjs|cjs)$/i.test(P)),f=s.filter(P=>!/\.(ts|tsx|js|jsx|mjs|cjs)$/i.test(P)),h=[];for(let P of s){if(!aa(P)){a.push({path:P,engineId:"generic-patterns",status:"unsupported",readLines:0,analyzedLines:0,reason:"Outside the declared source-language policy."});continue}try{let K=await Br.readFile(P),H=K.toString("utf-8"),V=H.split(`
414
414
  `);a.push({path:P,engineId:"generic-patterns",status:"analyzed",sourceDigest:xn("sha256").update(K).digest("hex"),readLines:V.length,analyzedLines:V.length});let ne=we.relative(n,P)||we.basename(P),ur=[{regex:/\w*(?:secret|password|passwd|api_key|apikey|private_key|jwt_secret)\w*\s*[=:]\s*['"][^'"]{4,}['"]/gi,title:"Hardcoded secret",severity:"critical"},{regex:/\w*(?:token|auth_token|access_key|secret_key)\w*\s*[=:]\s*['"][^'"]{8,}['"]/gi,title:"Hardcoded credential",severity:"critical"},{regex:/(?:AWS_SECRET|GITHUB_TOKEN|SLACK_TOKEN|OPENAI_API_KEY)\s*[=:]\s*['"][^'"]+['"]/gi,title:"Hardcoded cloud credential",severity:"critical"}];for(let[Y,he]of ur.entries()){l.set(`secret-${Y}`,he.regex.toString());for(let xe=0;xe<V.length;xe++){let mc=[...V[xe].matchAll(he.regex)];for(let Hm of mc)h.push({title:he.title,severity:he.severity,location:{file:ne,line:xe+1},description:`Potential hardcoded secret found at line ${xe+1}`,category:"sensitive-data"})}}let re=/(?:execute|query|cursor\.execute)\s*\(\s*(?:f['"]|['"].*%s|['"].*\+\s*\w)/gi;l.set("sql-interpolation",re.toString());for(let Y=0;Y<V.length;Y++)re.test(V[Y])&&h.push({title:"Potential SQL injection",severity:"high",location:{file:ne,line:Y+1},description:"String interpolation in SQL query \u2014 use parameterized queries",category:"injection"}),re.lastIndex=0;let dr=[/allow_origins\s*=\s*\[?\s*['"]?\*['"]?\s*\]?/i,/cors\(\s*\{[^}]*origin:\s*['"]?\*['"]?/i,/Access-Control-Allow-Origin['":\s]+\*/i,/@CrossOrigin\(\s*origins?\s*=\s*["']\*["']/i,/\.Header\(\)\.Set\(["']Access-Control-Allow-Origin["'],\s*["']\*["']/i];for(let[Y,he]of dr.entries())if(l.set(`cors-${Y}`,he.toString()),he.test(H)){h.push({title:"CORS wildcard origin",severity:"high",location:{file:ne,line:V.findIndex(xe=>he.test(xe))+1},description:"CORS configured with wildcard (*) origin \u2014 restrict to specific domains",category:"security-misconfiguration"});break}l.set("debug-mode","/(?:DEBUG|debug)\\s*[=:]\\s*(?:True|true|1)/i"),/(?:DEBUG|debug)\s*[=:]\s*(?:True|true|1)/i.test(H)&&h.push({title:"Debug mode enabled",severity:"medium",location:{file:ne,line:V.findIndex(Y=>/DEBUG\s*[=:]\s*(?:True|true|1)/i.test(Y))+1},description:"Debug mode should be disabled in production",category:"security-misconfiguration"}),l.set("eval-exec","/\\b(?:eval|exec)\\s*\\(/i"),/\b(?:eval|exec)\s*\(/i.test(H)&&h.push({title:"Dangerous eval/exec usage",severity:"high",location:{file:ne,line:V.findIndex(Y=>/\b(?:eval|exec)\s*\(/.test(Y))+1},description:"eval/exec can lead to code injection \u2014 avoid using with user input",category:"injection"})}catch(K){let H=`Source read failed: ${Hr(K)}`;u.push(`${P}: ${H}`),a.push({path:P,engineId:"generic-patterns",status:"unreadable",readLines:0,analyzedLines:0,reason:H})}}let v=["requirements.txt","pyproject.toml","Gemfile","go.mod","Cargo.toml"];for(let P of r?v:[]){let K=we.join(n,P);try{let H=await Br.readFile(K),V=H.toString("utf-8"),ne=V.split(`
415
415
  `).length;if(a.push({path:K,engineId:"dependency-manifest-patterns",status:"analyzed",sourceDigest:xn("sha256").update(H).digest("hex"),readLines:ne,analyzedLines:ne}),m.set("dependency-audit-advisory","Presence of a supported dependency manifest"),h.push({title:"Dependency audit recommended",severity:"informational",location:{file:P,line:1},description:`Found ${P} \u2014 run language-specific dependency audit (e.g., pip-audit, npm audit, cargo audit)`,category:"dependencies"}),P==="requirements.txt"||P==="pyproject.toml"){let ur=[{pkg:"python-jose",pattern:/python-jose/i,cve:"CVE-2024-33663",severity:"high",title:"python-jose ECDSA key confusion (CVE-2024-33663)",description:"python-jose allows ECDSA key confusion \u2014 upgrade to >=3.3.0 or switch to PyJWT"},{pkg:"python-jose",pattern:/python-jose/i,cve:"CVE-2024-33664",severity:"high",title:"python-jose JWT algorithm confusion (CVE-2024-33664)",description:"python-jose JWT algorithm confusion vulnerability \u2014 upgrade or switch to PyJWT"},{pkg:"python-multipart",pattern:/python-multipart/i,cve:"CVE-2026-24486",severity:"critical",title:"python-multipart DoS (CVE-2026-24486)",description:"python-multipart denial of service via crafted multipart data \u2014 upgrade to >=0.0.18"}];for(let re of ur)m.set(re.cve,re.pattern.toString()),re.pattern.test(V)&&h.push({title:re.title,severity:re.severity,location:{file:P,line:V.split(`
416
- `).findIndex(dr=>re.pattern.test(dr))+1},description:re.description,category:"dependencies"})}}catch(H){let V=H.code;if(V!=="ENOENT"&&V!=="ENOTDIR"){let ne=`Manifest read failed: ${Hr(H)}`;d.push(`${K}: ${ne}`),a.push({path:K,engineId:"dependency-manifest-patterns",status:"unreadable",readLines:0,analyzedLines:0,reason:ne})}}}let y=a.filter(P=>P.engineId==="generic-patterns"&&P.status==="analyzed").length,C=a.filter(P=>P.engineId==="dependency-manifest-patterns"&&P.status==="analyzed").length;c.push({id:"dependency-manifest-patterns",requested:r,required:!1,status:r?d.length>0?C>0?"partial":"failed":C>0?"completed":"not-run":"disabled",scope:"parent-directory",target:n,analyzedFiles:C,ruleIds:[...m.keys()].sort(),rulesetDigest:xn("sha256").update(JSON.stringify([...m.entries()].sort())).digest("hex"),ruleCoverage:"known",errors:d,limitations:["Manifest name patterns are advisories, not a resolved dependency or version audit."]});let b=["Generic text patterns do not establish language-specific or dependency vulnerability coverage."];c.push({id:"generic-patterns",requested:r,required:r,status:r?u.length>0?y>0?"partial":"failed":y===s.length&&y>0?"completed":y>0?"partial":s.length>0?"unavailable":"not-run":"disabled",scope:"requested-files",analyzedFiles:y,ruleIds:[...l.keys()].sort(),rulesetDigest:xn("sha256").update(JSON.stringify([...l.entries()].sort())).digest("hex"),ruleCoverage:"known",errors:u,limitations:b});let w=g.map(P=>Is.create(P)),T=null;if(r&&w.length>0)try{let P=await o.getSecurityScanner().scanFiles(w);P.success?(T=P.value,T.evidence?(a.push(...T.evidence.files),c.push(...T.evidence.engines),p.push(...T.evidence.limitations)):c.push(Fa("sast","requested-files"))):c.push(An("sast","requested-files",P.error))}catch(P){c.push(An("sast","requested-files",P))}else c.push({id:"sast",requested:r,required:!1,status:r?"not-run":"disabled",scope:"requested-files",analyzedFiles:0,ruleCoverage:"unknown",errors:[],limitations:r?["No JS/TS files were available for language-specific SAST."]:[]});let S=null;if(t.dast&&t.targetUrl)try{let P=await o.getSecurityScanner().scanUrl(t.targetUrl,{activeScanning:!0,maxDepth:3,timeout:3e4});P.success?(S=P.value,c.push({...Fa("dast","url"),target:t.targetUrl})):c.push({...An("dast","url",P.error),target:t.targetUrl})}catch(P){c.push({...An("dast","url",P),target:t.targetUrl})}else c.push({id:"dast",requested:t.dast===!0,required:t.dast===!0,status:t.dast?"not-run":"disabled",scope:"url",ruleCoverage:"unknown",errors:t.dast?["DAST was requested without targetUrl."]:[],limitations:[]});let x=null;t.dependencies===!0&&(x=await ca(o.getSecurityScanner(),n),c.push(x.engine)),t.compliance?.length&&c.push({id:"compliance",requested:!0,required:!0,status:"not-run",scope:"requested-files",ruleCoverage:"unknown",errors:[],limitations:["Requested compliance checks are not executed by this task handler."]});let F=new Set(s),B=new Set(a.filter(P=>P.status==="analyzed"&&F.has(P.path)).map(P=>P.path)),pe=c.filter(P=>P.requested&&P.required),ge=B.size>0||(x?.report.packagesChecked??0)>0,ot={schemaVersion:1,completeness:ge&&pe.every(P=>P.status==="completed")&&(!i||i.discovery.status==="complete")?"complete":ge?"partial":"none",requestedFiles:s.length,requestedPaths:s,duplicateInputs:0,files:a,engines:c,limitations:[...new Set([...p,...c.flatMap(P=>[...P.limitations,...P.errors]),...i?.discovery.issues.map(P=>`${P.path}: ${P.reason}`)??[]])],...i?{discovery:i.discovery}:{}},lr=!!T?.evidence?.engines.some(P=>P.id==="patterns"&&(P.status==="completed"||P.status==="partial")&&(P.analyzedFiles??0)>0),ct={critical:h.filter(P=>P.severity==="critical").length,high:h.filter(P=>P.severity==="high").length,medium:h.filter(P=>P.severity==="medium").length,low:h.filter(P=>P.severity==="low").length,informational:h.filter(P=>P.severity==="informational").length},Hi=x?.vulnerabilities??[],lt=P=>Hi.filter(K=>K.severity===P).length,ut={critical:(T?.summary?.critical||0)+(S?.summary?.critical||0)+ct.critical+lt("critical"),high:(T?.summary?.high||0)+(S?.summary?.high||0)+ct.high+lt("high"),medium:(T?.summary?.medium||0)+(S?.summary?.medium||0)+ct.medium+lt("medium"),low:(T?.summary?.low||0)+(S?.summary?.low||0)+ct.low+lt("low"),informational:(T?.summary?.informational||0)+(S?.summary?.informational||0)+ct.informational+lt("informational")},dt=[...T?.vulnerabilities||[],...S?.vulnerabilities||[],...h,...Hi],dc=dt.sort((P,K)=>{let H={critical:0,high:1,medium:2,low:3,informational:4};return H[P.severity]-H[K.severity]}).slice(0,10).map(P=>({type:P.title,severity:P.severity,file:P.location.file,line:P.location.line,description:P.description})),Vi=dt.length===0&&ot.completeness!=="complete"?["No findings reported; requested analysis is incomplete or unverified. Inspect execution receipts."]:us(dt);return x&&x.report.status!=="complete"&&Vi.unshift(x.report.message),_({vulnerabilities:dt.length,critical:ut.critical,high:ut.high,medium:ut.medium,low:ut.low,informational:ut.informational,topVulnerabilities:dc,findings:dt,recommendations:Vi,scanTypes:{sast:t.sast!==!1,dast:t.dast||!1,dependencies:t.dependencies===!0},...x?{dependencyScan:x.report}:{},status:ot.completeness==="complete"?"completed":ot.completeness==="partial"?"partial":"unavailable",evidence:ot,limitations:ot.limitations,filesScanned:B.size,jstsFilesScanned:g.filter(P=>B.has(P)).length,otherFilesScanned:f.filter(P=>B.has(P)).length,...T?.evidence?{coverage:T.coverage}:{},deepAnalysisPerformed:lr,analysisDepth:lr?f.length>0?"sast-patterns-on-js-ts; generic-patterns-on-other-languages":"sast-patterns":y>0?"pattern-matching-only":"none",...lr?{}:{note:"No verified language-specific SAST ran. Generic pattern matches and partial findings do not establish that the target is free of vulnerabilities."}})}catch(n){return L(z(n))}})}function An(o,e,t){let n=o==="sast"&&t instanceof Error&&t.message.startsWith("No valid rule sets found:")?"No valid rule sets configured.":`${o} execution failed (${Hr(t)}).`;return{id:o,requested:!0,required:!0,status:"failed",scope:e,ruleCoverage:"unknown",errors:[n],limitations:[]}}function Hr(o){let e=o?.code;return typeof e=="string"&&/^[A-Z0-9_]{1,32}$/.test(e)?e:"UNKNOWN"}function Fa(o,e){return{id:o,requested:!0,required:!0,status:"unverified",scope:e,ruleCoverage:"unknown",errors:[],limitations:[`${o} returned no execution receipt; coverage is unverified.`]}}import*as le from"node:path";import{existsSync as iu,promises as Qr}from"node:fs";k();Bt();var su=["coverage","complexity","maintainability","testability"],Be=-1,La="Static analysis only; no quality gate was evaluated. Call quality_assess with runGate: true (or `aqe quality --gate`) for a pass/fail gate on measured evidence.";function vt(o){return bs(o)?o:Be}function au(o,e){let t=new Map((e??[]).map(n=>[n.metric,n.reason]));return Object.fromEntries(o.map(n=>[n,t.get(n)??(n==="security"?"static analysis never measures security":"the static analyzer produced no measured value")]))}var ou=50;function qa(o,e){let t=le.relative(o,e);return t===""||t!==".."&&!t.startsWith(`..${le.sep}`)&&!le.isAbsolute(t)}async function $a(o,e,t){let n=le.resolve(e,o);if(o.includes("\0")||!qa(e,n))throw new ae(`${t} ${JSON.stringify(o)} is outside the project root (${e}).`);let r;try{r=await Qr.realpath(n)}catch{return n}let i=await Qr.realpath(e).catch(()=>e);if(!qa(i,r))throw new ae(`${t} ${JSON.stringify(o)} resolves outside the project root (${e}).`);return n}async function cu(o){let e=Ut();if(Array.isArray(o.sourceFiles)&&o.sourceFiles.length>0){let r=[];for(let i of o.sourceFiles){if(typeof i!="string"||i.trim()==="")throw new ae("sourceFiles must be a non-empty array of file paths.");r.push(await $a(i,e,"sourceFile"))}return{sourceFiles:r,explicitFiles:r,scope:"sourceFiles"}}if(typeof o.target=="string"&&o.target.trim()!==""){let r=await $a(o.target,e,"target"),i=await Qr.stat(r).catch(()=>null);if(!i)throw new ae(`target ${JSON.stringify(o.target)} does not exist.`);return i.isFile()?{sourceFiles:[r],explicitFiles:[r],scope:r}:{sourceFiles:await Ee(r,{includeTests:!1}),explicitFiles:[],scope:r}}let t=le.join(e,"src"),n=iu(t)?t:e;return{sourceFiles:await Ee(n,{includeTests:!1}),explicitFiles:[],scope:n}}function lu(o){return(o??[]).map(e=>`Partial evidence: ${e.metric} measured over ${e.analysedFiles} of ${e.totalFiles} file(s) (${Math.round(e.coverageOfScope*1e3)/10}%); not analysed: `+e.failed.slice(0,3).map(t=>t.reason).join("; ")+(e.failed.length>3?`; and ${e.failed.length-3} more`:"")+".")}function uu(o){if(o===void 0)return su;try{return Xt(o)}catch(e){throw new ae(z(e).message)}}async function du(o){try{let{findCIConfigFile:e,parseCIConfigFile:t}=await import("./ci-config-WU4NPDAM.js"),n=e(o);if(!n)return;let r=t(n);return r.success?r.config?.qualityGate.thresholds.coverage:void 0}catch{return}}async function mu(o){let e=o.thresholdSource==="default"?void 0:o.threshold;if(e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0||e>100))throw new ae("threshold must be a finite number between 0 and 100.");return vs(e,e===void 0?await du(process.cwd()):void 0)}function Wr(o){o.registerHandler("assess-quality",async e=>{let t=e.payload;try{if(t.runGate===!0){let y=await Kt(o.memory);return _({...cs(y),metrics:y,evidenceStatus:"measured",unmeasured:[],gateEvaluated:!0})}let n=uu(t.metrics),r=await mu(t),i=o.getQualityAnalyzer(),s=t.threshold||80,{sourceFiles:a,explicitFiles:c,scope:l}=await cu(t);if(a.length===0)return _({qualityScore:Be,passed:!1,threshold:s,metrics:{coverage:Be,complexity:Be,maintainability:Be,testability:Be},recommendations:[...vr(n),"No source files found for quality assessment"],warning:"No source files found",evidenceStatus:Le,unmeasured:n,unmeasuredReasons:Object.fromEntries(n.map(y=>[y,"no source files found to analyse"])),measuredFailures:[],gateEvaluated:!1,confidence:0,note:La});let u=await i.analyzeQuality({sourceFiles:a,includeMetrics:n,explicitFiles:c});if(!u.success)return u;let d=u.value,m={};for(let y of d.metrics)m[y.name]=y.value;let p=Cs(n,m),g=Ss(p.measured,m,{coverage:r}),f=p.evidenceStatus!=="measured",h=!f&&g.length===0&&d.score.overall>=s,v=d.recommendations.map(y=>`[${y.type}] ${y.title}: ${y.description}`);return _({qualityScore:d.score.overall,passed:h,threshold:s,metrics:{coverage:vt(m.coverage),complexity:vt(m.complexity),maintainability:vt(m.maintainability),security:vt(m.security),...Object.fromEntries(n.map(y=>[y,vt(m[y])])),...m},unmeasuredReasons:au(p.unmeasured,d.unmeasured),...f||(d.partial?.length??0)>0?{scoreBasis:d.metrics.map(y=>y.name)}:{},recommendations:[...g.map(Ts),...vr(p.unmeasured),...lu(d.partial),...v],...d.partial&&d.partial.length>0?{partialMetrics:d.partial}:{},...d.excluded&&d.excluded.length>0?{excludedFiles:d.excluded.slice(0,ou),excludedCount:d.excluded.length}:{},scope:l,evidenceStatus:p.evidenceStatus,unmeasured:p.unmeasured,measuredFailures:g,gateEvaluated:!1,confidence:p.confidence,note:La,trends:d.trends.map(y=>({metric:y.metric,direction:y.direction,dataPoints:y.dataPoints.length})),filesAnalyzed:a.length})}catch(n){return L(z(n))}})}import*as Ga from"fs/promises";k();function Kr(o){o.registerHandler("validate-requirements",async e=>{let t=e.payload;try{let n=t.requirementsPath||process.cwd(),r=await Ee(n,{includeTests:!1,languages:[]}),i=[".md",".feature",".gherkin",".txt",".rst"],s=[];for(let a of r)i.some(c=>a.endsWith(c))&&s.push(a);return _({requirementsAnalyzed:s.length,testable:0,ambiguous:0,untestable:0,coverage:0,bddScenarios:[],warning:s.length===0?"No requirement files (.md, .feature, .gherkin) found. Provide requirementsPath or add requirement docs.":"Requirements validation requires LLM analysis. File inventory returned \u2014 use task_orchestrate for deep analysis.",files:s.map(a=>a.startsWith(n)?a.slice(n.length+1):a).slice(0,20)})}catch(n){return L(z(n))}}),o.registerHandler("validate-contracts",async e=>{let t=e.payload;try{if(!t.contractPath)return _({contractPath:"",valid:!1,breakingChanges:[],warnings:[],coverage:0,error:"contractPath is required. Provide a path to an OpenAPI spec, JSON Schema, or Protocol Buffer file."});try{let n=await Ga.readFile(t.contractPath,"utf-8"),r=t.contractPath.endsWith(".json"),i=t.contractPath.endsWith(".yaml")||t.contractPath.endsWith(".yml");return r&&JSON.parse(n),_({contractPath:t.contractPath,valid:!0,format:r?"json":i?"yaml":"unknown",breakingChanges:[],warnings:[],linesAnalyzed:n.split(`
416
+ `).findIndex(dr=>re.pattern.test(dr))+1},description:re.description,category:"dependencies"})}}catch(H){let V=H.code;if(V!=="ENOENT"&&V!=="ENOTDIR"){let ne=`Manifest read failed: ${Hr(H)}`;d.push(`${K}: ${ne}`),a.push({path:K,engineId:"dependency-manifest-patterns",status:"unreadable",readLines:0,analyzedLines:0,reason:ne})}}}let y=a.filter(P=>P.engineId==="generic-patterns"&&P.status==="analyzed").length,C=a.filter(P=>P.engineId==="dependency-manifest-patterns"&&P.status==="analyzed").length;c.push({id:"dependency-manifest-patterns",requested:r,required:!1,status:r?d.length>0?C>0?"partial":"failed":C>0?"completed":"not-run":"disabled",scope:"parent-directory",target:n,analyzedFiles:C,ruleIds:[...m.keys()].sort(),rulesetDigest:xn("sha256").update(JSON.stringify([...m.entries()].sort())).digest("hex"),ruleCoverage:"known",errors:d,limitations:["Manifest name patterns are advisories, not a resolved dependency or version audit."]});let b=["Generic text patterns do not establish language-specific or dependency vulnerability coverage."];c.push({id:"generic-patterns",requested:r,required:r,status:r?u.length>0?y>0?"partial":"failed":y===s.length&&y>0?"completed":y>0?"partial":s.length>0?"unavailable":"not-run":"disabled",scope:"requested-files",analyzedFiles:y,ruleIds:[...l.keys()].sort(),rulesetDigest:xn("sha256").update(JSON.stringify([...l.entries()].sort())).digest("hex"),ruleCoverage:"known",errors:u,limitations:b});let w=g.map(P=>Is.create(P)),T=null;if(r&&w.length>0)try{let P=await o.getSecurityScanner().scanFiles(w);P.success?(T=P.value,T.evidence?(a.push(...T.evidence.files),c.push(...T.evidence.engines),p.push(...T.evidence.limitations)):c.push(Fa("sast","requested-files"))):c.push(An("sast","requested-files",P.error))}catch(P){c.push(An("sast","requested-files",P))}else c.push({id:"sast",requested:r,required:!1,status:r?"not-run":"disabled",scope:"requested-files",analyzedFiles:0,ruleCoverage:"unknown",errors:[],limitations:r?["No JS/TS files were available for language-specific SAST."]:[]});let S=null;if(t.dast&&t.targetUrl)try{let P=await o.getSecurityScanner().scanUrl(t.targetUrl,{activeScanning:!0,maxDepth:3,timeout:3e4});P.success?(S=P.value,c.push({...Fa("dast","url"),target:t.targetUrl})):c.push({...An("dast","url",P.error),target:t.targetUrl})}catch(P){c.push({...An("dast","url",P),target:t.targetUrl})}else c.push({id:"dast",requested:t.dast===!0,required:t.dast===!0,status:t.dast?"not-run":"disabled",scope:"url",ruleCoverage:"unknown",errors:t.dast?["DAST was requested without targetUrl."]:[],limitations:[]});let x=null;t.dependencies===!0&&(x=await ca(o.getSecurityScanner(),n),c.push(x.engine)),t.compliance?.length&&c.push({id:"compliance",requested:!0,required:!0,status:"not-run",scope:"requested-files",ruleCoverage:"unknown",errors:[],limitations:["Requested compliance checks are not executed by this task handler."]});let F=new Set(s),B=new Set(a.filter(P=>P.status==="analyzed"&&F.has(P.path)).map(P=>P.path)),pe=c.filter(P=>P.requested&&P.required),ge=B.size>0||(x?.report.packagesChecked??0)>0,ot={schemaVersion:1,completeness:ge&&pe.every(P=>P.status==="completed")&&(!i||i.discovery.status==="complete")?"complete":ge?"partial":"none",requestedFiles:s.length,requestedPaths:s,duplicateInputs:0,files:a,engines:c,limitations:[...new Set([...p,...c.flatMap(P=>[...P.limitations,...P.errors]),...i?.discovery.issues.map(P=>`${P.path}: ${P.reason}`)??[]])],...i?{discovery:i.discovery}:{}},lr=!!T?.evidence?.engines.some(P=>P.id==="patterns"&&(P.status==="completed"||P.status==="partial")&&(P.analyzedFiles??0)>0),ct={critical:h.filter(P=>P.severity==="critical").length,high:h.filter(P=>P.severity==="high").length,medium:h.filter(P=>P.severity==="medium").length,low:h.filter(P=>P.severity==="low").length,informational:h.filter(P=>P.severity==="informational").length},Hi=x?.vulnerabilities??[],lt=P=>Hi.filter(K=>K.severity===P).length,ut={critical:(T?.summary?.critical||0)+(S?.summary?.critical||0)+ct.critical+lt("critical"),high:(T?.summary?.high||0)+(S?.summary?.high||0)+ct.high+lt("high"),medium:(T?.summary?.medium||0)+(S?.summary?.medium||0)+ct.medium+lt("medium"),low:(T?.summary?.low||0)+(S?.summary?.low||0)+ct.low+lt("low"),informational:(T?.summary?.informational||0)+(S?.summary?.informational||0)+ct.informational+lt("informational")},dt=[...T?.vulnerabilities||[],...S?.vulnerabilities||[],...h,...Hi],dc=dt.sort((P,K)=>{let H={critical:0,high:1,medium:2,low:3,informational:4};return H[P.severity]-H[K.severity]}).slice(0,10).map(P=>({type:P.title,severity:P.severity,file:P.location.file,line:P.location.line,description:P.description})),Vi=dt.length===0&&ot.completeness!=="complete"?["No findings reported; requested analysis is incomplete or unverified. Inspect execution receipts."]:us(dt);return x&&x.report.status!=="complete"&&Vi.unshift(x.report.message),_({vulnerabilities:dt.length,critical:ut.critical,high:ut.high,medium:ut.medium,low:ut.low,informational:ut.informational,topVulnerabilities:dc,findings:dt,recommendations:Vi,scanTypes:{sast:t.sast!==!1,dast:t.dast||!1,dependencies:t.dependencies===!0},...x?{dependencyScan:x.report}:{},status:ot.completeness==="complete"?"completed":ot.completeness==="partial"?"partial":"unavailable",evidence:ot,limitations:ot.limitations,filesScanned:B.size,jstsFilesScanned:g.filter(P=>B.has(P)).length,otherFilesScanned:f.filter(P=>B.has(P)).length,...T?.evidence?{coverage:T.coverage}:{},deepAnalysisPerformed:lr,analysisDepth:lr?f.length>0?"sast-patterns-on-js-ts; generic-patterns-on-other-languages":"sast-patterns":y>0?"pattern-matching-only":"none",...lr?{}:{note:"No verified language-specific SAST ran. Generic pattern matches and partial findings do not establish that the target is free of vulnerabilities."}})}catch(n){return L(z(n))}})}function An(o,e,t){let n=o==="sast"&&t instanceof Error&&t.message.startsWith("No valid rule sets found:")?"No valid rule sets configured.":`${o} execution failed (${Hr(t)}).`;return{id:o,requested:!0,required:!0,status:"failed",scope:e,ruleCoverage:"unknown",errors:[n],limitations:[]}}function Hr(o){let e=o?.code;return typeof e=="string"&&/^[A-Z0-9_]{1,32}$/.test(e)?e:"UNKNOWN"}function Fa(o,e){return{id:o,requested:!0,required:!0,status:"unverified",scope:e,ruleCoverage:"unknown",errors:[],limitations:[`${o} returned no execution receipt; coverage is unverified.`]}}import*as le from"node:path";import{existsSync as iu,promises as Qr}from"node:fs";k();Bt();var su=["coverage","complexity","maintainability","testability"],Be=-1,La="Static analysis only; no quality gate was evaluated. Call quality_assess with runGate: true (or `aqe quality --gate`) for a pass/fail gate on measured evidence.";function vt(o){return bs(o)?o:Be}function au(o,e){let t=new Map((e??[]).map(n=>[n.metric,n.reason]));return Object.fromEntries(o.map(n=>[n,t.get(n)??(n==="security"?"static analysis never measures security":"the static analyzer produced no measured value")]))}var ou=50;function qa(o,e){let t=le.relative(o,e);return t===""||t!==".."&&!t.startsWith(`..${le.sep}`)&&!le.isAbsolute(t)}async function $a(o,e,t){let n=le.resolve(e,o);if(o.includes("\0")||!qa(e,n))throw new ae(`${t} ${JSON.stringify(o)} is outside the project root (${e}).`);let r;try{r=await Qr.realpath(n)}catch{return n}let i=await Qr.realpath(e).catch(()=>e);if(!qa(i,r))throw new ae(`${t} ${JSON.stringify(o)} resolves outside the project root (${e}).`);return n}async function cu(o){let e=Ut();if(Array.isArray(o.sourceFiles)&&o.sourceFiles.length>0){let r=[];for(let i of o.sourceFiles){if(typeof i!="string"||i.trim()==="")throw new ae("sourceFiles must be a non-empty array of file paths.");r.push(await $a(i,e,"sourceFile"))}return{sourceFiles:r,explicitFiles:r,scope:"sourceFiles"}}if(typeof o.target=="string"&&o.target.trim()!==""){let r=await $a(o.target,e,"target"),i=await Qr.stat(r).catch(()=>null);if(!i)throw new ae(`target ${JSON.stringify(o.target)} does not exist.`);return i.isFile()?{sourceFiles:[r],explicitFiles:[r],scope:r}:{sourceFiles:await Ee(r,{includeTests:!1}),explicitFiles:[],scope:r}}let t=le.join(e,"src"),n=iu(t)?t:e;return{sourceFiles:await Ee(n,{includeTests:!1}),explicitFiles:[],scope:n}}function lu(o){return(o??[]).map(e=>`Partial evidence: ${e.metric} measured over ${e.analysedFiles} of ${e.totalFiles} file(s) (${Math.round(e.coverageOfScope*1e3)/10}%); not analysed: `+e.failed.slice(0,3).map(t=>t.reason).join("; ")+(e.failed.length>3?`; and ${e.failed.length-3} more`:"")+".")}function uu(o){if(o===void 0)return su;try{return Xt(o)}catch(e){throw new ae(z(e).message)}}async function du(o){try{let{findCIConfigFile:e,parseCIConfigFile:t}=await import("./ci-config-VQVECCFI.js"),n=e(o);if(!n)return;let r=t(n);return r.success?r.config?.qualityGate.thresholds.coverage:void 0}catch{return}}async function mu(o){let e=o.thresholdSource==="default"?void 0:o.threshold;if(e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0||e>100))throw new ae("threshold must be a finite number between 0 and 100.");return vs(e,e===void 0?await du(process.cwd()):void 0)}function Wr(o){o.registerHandler("assess-quality",async e=>{let t=e.payload;try{if(t.runGate===!0){let y=await Kt(o.memory);return _({...cs(y),metrics:y,evidenceStatus:"measured",unmeasured:[],gateEvaluated:!0})}let n=uu(t.metrics),r=await mu(t),i=o.getQualityAnalyzer(),s=t.threshold||80,{sourceFiles:a,explicitFiles:c,scope:l}=await cu(t);if(a.length===0)return _({qualityScore:Be,passed:!1,threshold:s,metrics:{coverage:Be,complexity:Be,maintainability:Be,testability:Be},recommendations:[...vr(n),"No source files found for quality assessment"],warning:"No source files found",evidenceStatus:Le,unmeasured:n,unmeasuredReasons:Object.fromEntries(n.map(y=>[y,"no source files found to analyse"])),measuredFailures:[],gateEvaluated:!1,confidence:0,note:La});let u=await i.analyzeQuality({sourceFiles:a,includeMetrics:n,explicitFiles:c});if(!u.success)return u;let d=u.value,m={};for(let y of d.metrics)m[y.name]=y.value;let p=Cs(n,m),g=Ss(p.measured,m,{coverage:r}),f=p.evidenceStatus!=="measured",h=!f&&g.length===0&&d.score.overall>=s,v=d.recommendations.map(y=>`[${y.type}] ${y.title}: ${y.description}`);return _({qualityScore:d.score.overall,passed:h,threshold:s,metrics:{coverage:vt(m.coverage),complexity:vt(m.complexity),maintainability:vt(m.maintainability),security:vt(m.security),...Object.fromEntries(n.map(y=>[y,vt(m[y])])),...m},unmeasuredReasons:au(p.unmeasured,d.unmeasured),...f||(d.partial?.length??0)>0?{scoreBasis:d.metrics.map(y=>y.name)}:{},recommendations:[...g.map(Ts),...vr(p.unmeasured),...lu(d.partial),...v],...d.partial&&d.partial.length>0?{partialMetrics:d.partial}:{},...d.excluded&&d.excluded.length>0?{excludedFiles:d.excluded.slice(0,ou),excludedCount:d.excluded.length}:{},scope:l,evidenceStatus:p.evidenceStatus,unmeasured:p.unmeasured,measuredFailures:g,gateEvaluated:!1,confidence:p.confidence,note:La,trends:d.trends.map(y=>({metric:y.metric,direction:y.direction,dataPoints:y.dataPoints.length})),filesAnalyzed:a.length})}catch(n){return L(z(n))}})}import*as Ga from"fs/promises";k();function Kr(o){o.registerHandler("validate-requirements",async e=>{let t=e.payload;try{let n=t.requirementsPath||process.cwd(),r=await Ee(n,{includeTests:!1,languages:[]}),i=[".md",".feature",".gherkin",".txt",".rst"],s=[];for(let a of r)i.some(c=>a.endsWith(c))&&s.push(a);return _({requirementsAnalyzed:s.length,testable:0,ambiguous:0,untestable:0,coverage:0,bddScenarios:[],warning:s.length===0?"No requirement files (.md, .feature, .gherkin) found. Provide requirementsPath or add requirement docs.":"Requirements validation requires LLM analysis. File inventory returned \u2014 use task_orchestrate for deep analysis.",files:s.map(a=>a.startsWith(n)?a.slice(n.length+1):a).slice(0,20)})}catch(n){return L(z(n))}}),o.registerHandler("validate-contracts",async e=>{let t=e.payload;try{if(!t.contractPath)return _({contractPath:"",valid:!1,breakingChanges:[],warnings:[],coverage:0,error:"contractPath is required. Provide a path to an OpenAPI spec, JSON Schema, or Protocol Buffer file."});try{let n=await Ga.readFile(t.contractPath,"utf-8"),r=t.contractPath.endsWith(".json"),i=t.contractPath.endsWith(".yaml")||t.contractPath.endsWith(".yml");return r&&JSON.parse(n),_({contractPath:t.contractPath,valid:!0,format:r?"json":i?"yaml":"unknown",breakingChanges:[],warnings:[],linesAnalyzed:n.split(`
417
417
  `).length,note:"Structural validation passed. For semantic contract testing, use consumer-driven contract tests."})}catch(n){return _({contractPath:t.contractPath,valid:!1,breakingChanges:[],warnings:[],error:`Could not read or parse contract file: ${E(n)}`})}}catch(n){return L(z(n))}})}import*as ja from"fs/promises";import*as kn from"path";k();jt();var Xr=ye("CodeIntelligenceHandlers");async function pu(o,e,t){if(!o.getCodeIntelligenceCoordinator)return;let n=ws(t,{target:kn.resolve(e)});if(!n){Xr.debug("Skipping project metrics: no project root resolved (filesystem root or no paths)");return}try{let r=await o.getCodeIntelligenceCoordinator();if(!r)return;let i=await r.collectProjectMetrics(n);if(!i.success){Xr.debug(`Project metrics unavailable: ${i.error.message}`);return}return{root:n,loc:i.value.loc.total,locByLanguage:i.value.loc.byLanguage,tests:i.value.tests.total,toolsUsed:i.value.toolsUsed}}catch(r){Xr.debug(`Project metrics unavailable: ${z(r).message}`);return}}function Yr(o){o.registerHandler("index-code",async e=>{let t=e.payload;try{let n=o.getKnowledgeGraph(),r=t.target||process.cwd(),i=Date.now(),s=await Ee(r,{includeTests:t.includeTests!==!1,languages:t.languages});if(s.length===0)return _({filesIndexed:0,nodesCreated:0,edgesCreated:0,target:r,incremental:t.incremental||!1,languages:t.languages||[],duration:Date.now()-i,warning:`No source files found in ${r}. Searched for: TypeScript, JavaScript, Python, Go, Rust, Java, Ruby, C/C++, and more.`});let a=await n.index({paths:s,incremental:t.incremental||!1,includeTests:t.includeTests!==!1,languages:t.languages});if(!a.success)return a;let c=a.value,l=await pu(o,r,s),u=new Set,d={ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",py:"python",pyw:"python",go:"go",rs:"rust",java:"java",kt:"kotlin",kts:"kotlin",rb:"ruby",cs:"csharp",php:"php",swift:"swift",c:"c",h:"c",cpp:"cpp",hpp:"cpp",cc:"cpp",scala:"scala"};for(let m of s){let p=kn.extname(m).slice(1),g=d[p];g&&u.add(g)}return _({filesIndexed:c.filesIndexed,nodesCreated:c.nodesCreated,edgesCreated:c.edgesCreated,symbolsExtracted:c.nodesCreated,relationsFound:c.edgesCreated,target:r,incremental:t.incremental||!1,languages:Array.from(u),duration:c.duration,errors:c.errors,warnings:c.warnings,...l?{projectMetrics:l}:{}})}catch(n){return L(z(n))}}),o.registerHandler("predict-defects",async e=>{let t=e.payload;try{let n=t.target||process.cwd(),r=t.minConfidence||.5,i=await Ee(n,{includeTests:!1});if(i.length===0)return _({predictedDefects:[],riskScore:0,recommendations:[`No source files found in ${n}. Ensure the path contains source code files.`],warning:`No source files found in ${n}`,filesAnalyzed:0});let s=[];for(let u of i)try{let d=await ja.readFile(u,"utf-8"),m=d.split(`
418
- `),p=m.length,g=0,f=[];p>500?(g+=.25,f.push(`Large file (${p} lines)`)):p>300&&(g+=.15,f.push(`Medium-large file (${p} lines)`));let h=d.match(/\b(if|else|switch|case|for|while|catch|&&|\|\|)\b/g)||[],v=h.length/Math.max(p,1);v>.15?(g+=.25,f.push(`High branch density (${h.length} branches in ${p} lines)`)):v>.08&&(g+=.1,f.push("Moderate branch complexity")),Math.max(...m.map(w=>{let T=w.match(/^(\s*)/);return T?T[1].length:0}))>20&&(g+=.15,f.push("Deep nesting detected"));let C=(d.match(/\b(TODO|FIXME|HACK|XXX|WORKAROUND)\b/gi)||[]).length;C>3&&(g+=.15,f.push(`${C} technical debt markers`));let b=(d.match(/\b(function|def|func|async)\b/g)||[]).length;if(b>0&&p/b>80&&(g+=.1,f.push("Potentially long functions")),g=Math.min(g,.95),g>=r){let w=u.startsWith(n)?u.slice(n.length).replace(/^\//,""):u;s.push({file:w,probability:Math.round(g*100)/100,reason:f.join("; ")})}}catch{}s.sort((u,d)=>d.probability-u.probability);let a=s.length>0?s.reduce((u,d)=>u+d.probability,0)/s.length:0,c=Math.round(a*100),l=[];if(s.length>0){l.push(`${s.length} files flagged for potential defects out of ${i.length} analyzed`);let u=s[0];l.push(`Highest risk: ${u.file} (${Math.round(u.probability*100)}%) \u2014 ${u.reason}`)}return s.some(u=>u.reason.includes("Large file"))&&l.push("Consider splitting large files to reduce complexity"),s.some(u=>u.reason.includes("technical debt"))&&l.push("Address TODO/FIXME comments to reduce technical debt"),s.length===0&&l.push("No files exceeded the defect probability threshold \u2014 code looks healthy"),_({predictedDefects:s.slice(0,20),riskScore:c,recommendations:l,filesAnalyzed:i.length})}catch(n){return L(z(n))}})}function Jr(o){o.registerHandler("test-accessibility",async e=>{let t=e.payload;return _({url:t.url||"",standard:t.standard||"wcag21-aa",passed:!1,violations:[],warnings:[],score:0,note:"Accessibility testing requires a browser environment (Puppeteer/Playwright). Use tools like axe-core, pa11y, or Lighthouse CLI for WCAG compliance testing. Example: npx pa11y "+(t.url||"<url>")})}),o.registerHandler("run-chaos",async e=>{let t=e.payload;return _({faultType:t.faultType||"unknown",target:t.target||"unknown",dryRun:t.dryRun??!0,duration:t.duration||0,systemBehavior:"not-executed",resilience:null,note:"Chaos engineering requires infrastructure-level fault injection. Use tools like Chaos Monkey, Litmus, or toxiproxy for real resilience testing. For Node.js apps, consider: nock (HTTP faults), testcontainers (dependency failures)."})}),o.registerHandler("optimize-learning",async e=>{try{let t=await import("./unified-memory-hnsw-A4EWYPJQ.js");return _({patternsLearned:0,modelsUpdated:0,memoryConsolidated:!1,note:'Learning optimization runs during the dream cycle (SessionEnd hook). Use "npx agentic-qe hooks session-end --save-state" to trigger pattern consolidation.'})}catch{return _({patternsLearned:0,modelsUpdated:0,memoryConsolidated:!1,note:'Learning system not initialized. Run "aqe init --auto" first.'})}})}var se=ye("TaskExecutor");function vu(o){return $e.resolve(qe.CoverageAnalyzerService)(o)}function bu(o){return $e.resolve(qe.SecurityScannerService)(o)}function Wa(o,e){return $e.resolve(qe.createTestGeneratorService)(o,e)}function Cu(o){return $e.resolve(qe.KnowledgeGraphService)(o)}function Su(o){return $e.resolve(qe.QualityAnalyzerService)(o)}function Ka(o){return o instanceof os?{...o.toDetails()}:_e(o)?{callerError:!0}:void 0}function Xa(o){return o===0?"agent-booster":Xi(o)}function Tu(o){if(["generate-tests","analyze-coverage","scan-security","execute-tests","assess-quality","validate-contracts","test-accessibility","chaos-test","predict-defects","validate-requirements","index-code"].includes(o.type))return null;let t=o.payload?.codeContext||"",n=o.payload?.sourceCode||"",r=t||n;return r?r.includes("var ")&&!r.includes("const ")&&!r.includes("let ")?"var-to-const":r.includes("console.log")||r.includes("console.warn")||r.includes("console.error")?"remove-console":r.includes(".then(")&&r.includes(".catch(")?"promise-to-async":r.includes("require(")&&!r.includes("import ")?"cjs-to-esm":r.includes("function ")&&!r.includes("=>")?"func-to-arrow":null:null}var ei=class{constructor(e,t,n){this.kernel=e;this.eventBus=t;this._config={timeout:n?.timeout??3e5,maxRetries:n?.maxRetries??3,enableCaching:n?.enableCaching??!0,saveResults:n?.saveResults??!0,resultsDir:n?.resultsDir??zt(),defaultLanguage:n?.defaultLanguage??"typescript",defaultFramework:n?.defaultFramework??"vitest"},this.resultSaver=va(this._config.resultsDir),this.registerHandlers()}kernel;eventBus;_config;resultSaver;coverageAnalyzer=null;securityScanner=null;testGenerator=null;deterministicTestGenerator=null;knowledgeGraph=null;qualityAnalyzer=null;agentBooster=null;taskRouter=null;qualityFeedbackLoop=null;coherenceActionGate=null;taskHandlers=new Map;get memory(){return this.kernel.memory}get config(){return this._config}registerHandler(e,t){this.taskHandlers.set(e,t)}setQualityFeedbackLoop(e){this.qualityFeedbackLoop=e}getCoverageAnalyzer(){return this.coverageAnalyzer||(this.coverageAnalyzer=vu(this.kernel.memory)),this.coverageAnalyzer}getSecurityScanner(){return this.securityScanner||(this.securityScanner=bu(this.kernel.memory)),this.securityScanner}async getTestGenerator(e=!0){return e?(this.testGenerator||(this.testGenerator=Wa(this.kernel.memory,await this.resolveLLMRouter())),this.testGenerator):(this.deterministicTestGenerator||(this.deterministicTestGenerator=Wa(this.kernel.memory)),this.deterministicTestGenerator)}async resolveLLMRouter(){if(this.kernel.llmRouter)return this.kernel.llmRouter;try{let{getSharedLLMRouter:e}=await import("./base-QZWK3D5P.js");return await e()??void 0}catch(e){se.debug("LLM router unavailable; using deterministic generation",{error:E(e)});return}}getKnowledgeGraph(){return this.knowledgeGraph||(this.knowledgeGraph=Cu(this.kernel.memory)),this.knowledgeGraph}async getCodeIntelligenceCoordinator(){try{let e=this.kernel.getDomainAPIAsync?await this.kernel.getDomainAPIAsync("code-intelligence"):this.kernel.getDomainAPI("code-intelligence");return typeof e?.getCoordinator=="function"?e.getCoordinator():void 0}catch(e){se.debug("code-intelligence coordinator unavailable for project metrics",{error:e instanceof Error?e.message:String(e)});return}}getQualityAnalyzer(){return this.qualityAnalyzer||(this.qualityAnalyzer=Su(this.kernel.memory)),this.qualityAnalyzer}registerHandlers(){$r(this),Ur(this),Vr(this),Wr(this),Kr(this),Yr(this),Jr(this)}async getAgentBooster(){return this.agentBooster||(this.agentBooster=await Jt({enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7})),this.agentBooster}async getTaskRouterInstance(){if(!this.taskRouter)try{this.taskRouter=await Tn()}catch{return null}return this.taskRouter}async executeWithAgentBooster(e,t,n){let r=Tu(e);if(!r)return console.debug(`[TaskExecutor] No applicable Agent Booster transform for task ${e.id}`),null;try{let i=await this.getAgentBooster(),s=e.payload?.codeContext||e.payload?.sourceCode||"",a=await i.transform(s,r);return a.success&&a.confidence>=.7?(console.debug(`[TaskExecutor] Agent Booster transform succeeded: ${r}, confidence=${a.confidence}`),{taskId:e.id,success:!0,data:{transformed:!0,transformType:r,originalCode:a.originalCode,transformedCode:a.transformedCode,confidence:a.confidence,implementationUsed:a.implementationUsed,durationMs:a.durationMs,changeCount:a.changeCount,tier:0,model:"agent-booster"},duration:Date.now()-t,domain:n}):(console.debug(`[TaskExecutor] Agent Booster low confidence (${a.confidence}), falling back to Tier 1`),null)}catch(i){return console.warn(`[TaskExecutor] Agent Booster error, falling back: ${i}`),null}}async recordOutcome(e,t,n,r){try{if(!await this.getTaskRouterInstance())return;if(console.debug(`[TaskExecutor] Outcome recorded: task=${e.id}, tier=${t}, model=${Xa(t)}, success=${n}, duration=${r}ms`),this.qualityFeedbackLoop){let s=e.targetDomains||[],a=n?1:0,c=r<100?1:r<500?.8:r<2e3?.6:r<5e3?.4:r<1e4?.2:.1,l=.25*a+.325+.1*c;await this.qualityFeedbackLoop.recordRoutingOutcome({taskId:e.id,taskDescription:e.type,recommendedAgent:String(t),usedAgent:String(t),followedRecommendation:!0,success:n,qualityScore:l,durationMs:r,timestamp:new Date,error:n?void 0:"Task execution failed"})}}catch(i){console.warn("[TaskExecutor] Failed to record outcome:",i)}}async execute(e){let t=Date.now(),n=this.getTaskDomain(e.type),r=e.payload,i=r?.routingTier??2,s=r?.useAgentBooster??!1,a=r?.compiledContext??void 0,c=Xa(i);a&&e.payload&&(e.payload.__compiledContext=a),console.debug(`[TaskExecutor] Executing task ${e.id}: type=${e.type}, tier=${i}, model=${c}, useAgentBooster=${s}${a?", hasContext=true":""}`);let l=this.evaluateCoherenceGate(e,n);l&&console.debug(`[TaskExecutor] Coherence gate: task=${e.id}, decision=${l.decision}, combined=${l.combinedScore.toFixed(3)}, advisory=${l.advisory}`),this.validateWithReasoningQEC(e,n);try{if(i===0||s){let p=await this.executeWithAgentBooster(e,t,n);if(p)return this.recordOutcome(e,0,!0,Date.now()-t).catch(g=>{se.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),await this.publishTaskCompleted(e.id,p.data,n),p;console.debug(`[TaskExecutor] Agent Booster fallback to Tier 1 for task ${e.id}`)}let u=this.taskHandlers.get(e.type);if(!u){let p={taskId:e.id,success:!1,error:`No handler registered for task type: ${e.type}`,duration:Date.now()-t,domain:n};return this.recordOutcome(e,i,!1,Date.now()-t).catch(g=>{se.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),p}let d=await Promise.race([u(e),this.timeout(e.timeout||this._config.timeout)]);if(!d.success){let p="error"in d?d.error.message:"Unknown error";await this.publishTaskFailed(e.id,p,n,"error"in d&&_e(d.error)),this.recordOutcome(e,i,!1,Date.now()-t).catch(f=>{se.warn("recordOutcome failed",{error:f instanceof Error?f.message:String(f),taskId:e.id})});let g="error"in d?Ka(d.error):void 0;return{taskId:e.id,success:!1,error:p,duration:Date.now()-t,domain:n,...g?{errorDetails:g}:{}}}await this.publishTaskCompleted(e.id,d.value,n),this.recordOutcome(e,i,!0,Date.now()-t).catch(p=>{se.warn("recordOutcome failed",{error:p instanceof Error?p.message:String(p),taskId:e.id})});let m;if(this._config.saveResults&&r?.saveResults!==!1)try{let p={language:r?.language||this._config.defaultLanguage,framework:r?.framework||this._config.defaultFramework,includeSecondary:!0};m=(await this.resultSaver.save(e.id,e.type,d.value,p)).files.map(f=>f.path)}catch(p){console.error(`[TaskExecutor] Failed to save results: ${p}`)}return{taskId:e.id,success:!0,data:{...d.value,_routing:{tier:i,model:c,usedAgentBooster:!1}},duration:Date.now()-t,domain:n,savedFiles:m}}catch(u){let d=E(u);await this.publishTaskFailed(e.id,d,n,_e(u)),this.recordOutcome(e,i,!1,Date.now()-t).catch(p=>{se.warn("recordOutcome failed",{error:p instanceof Error?p.message:String(p),taskId:e.id})});let m=Ka(u);return{taskId:e.id,success:!1,error:d,duration:Date.now()-t,domain:n,...m?{errorDetails:m}:{}}}}async resetServiceCaches(){if(this.coverageAnalyzer=null,this.securityScanner=null,this.testGenerator=null,this.knowledgeGraph=null,this.qualityAnalyzer=null,this.coherenceActionGate=null,this.agentBooster){try{await this.agentBooster.dispose()}catch(e){console.debug("[TaskExecutor] Agent Booster disposal error:",e instanceof Error?e.message:e)}this.agentBooster=null}this.taskRouter=null}resetServiceCachesSync(){this.coverageAnalyzer=null,this.securityScanner=null,this.testGenerator=null,this.knowledgeGraph=null,this.qualityAnalyzer=null,this.agentBooster=null,this.taskRouter=null,this.coherenceActionGate=null}evaluateCoherenceGate(e,t){try{this.coherenceActionGate||(this.coherenceActionGate=wa({advisory:!0}));let n=e.payload,r=typeof n?.confidence=="number"?n.confidence:.7,i=n?.riskLevel??"medium";return Ra(e.type,t,r,i,n??{},this.coherenceActionGate)}catch(n){return se.warn("Coherence gate evaluation error (continuing)",{error:n instanceof Error?n.message:String(n),taskId:e.id}),null}}_reasoningQEC=null;_reasoningQECLoaded=!1;validateWithReasoningQEC(e,t){try{if(!this._reasoningQECLoaded){this._reasoningQECLoaded=!0;try{let{isReasoningQECEnabled:s}=($t(),Qi(hc));if(s()){let{createReasoningQEC:a}=(Qa(),Qi(Va));this._reasoningQEC=a()}}catch(s){se.debug("ReasoningQEC module unavailable",{error:s instanceof Error?s.message:String(s)})}}if(!this._reasoningQEC)return;let n=e.payload,r=n?.reasoningSteps;if(!r||r.length<2)return;let i=this._reasoningQEC.validate({type:t,context:n,steps:r});i.valid||se.warn("ReasoningQEC validation found issues (advisory)",{taskId:e.id,domain:t,confidence:i.confidence,issues:i.issues.length})}catch(n){se.debug("ReasoningQEC evaluation error",{error:n instanceof Error?n.message:String(n),taskId:e.id})}}getTaskDomain(e){return{"generate-tests":"test-generation","execute-tests":"test-execution","analyze-coverage":"coverage-analysis","assess-quality":"quality-assessment","predict-defects":"defect-intelligence","validate-requirements":"requirements-validation","index-code":"code-intelligence","scan-security":"security-compliance","validate-contracts":"contract-testing","test-accessibility":"visual-accessibility","run-chaos":"chaos-resilience","optimize-learning":"learning-optimization","cross-domain-workflow":"learning-optimization","protocol-execution":"learning-optimization","ideation-assessment":"requirements-validation"}[e]||"learning-optimization"}async timeout(e){return new Promise((t,n)=>{setTimeout(()=>n(new Error(`Task execution timed out after ${e}ms`)),e)})}async publishTaskCompleted(e,t,n){await this.eventBus.publish({id:G(),type:"TaskCompleted",timestamp:new Date,source:n,payload:{taskId:e,result:t}})}async publishTaskFailed(e,t,n,r=!1){await this.eventBus.publish({id:G(),type:"TaskFailed",timestamp:new Date,source:n,payload:{taskId:e,error:t,...r?{callerError:!0}:{}}})}};function Ya(o,e){return new ei(o,o.eventBus,e)}async function Ja(){}import{randomUUID as He}from"crypto";k();var ti=".agentic-qe/results/";function Za(o){if(o===null||typeof o!="object")return!0;let e=o.saveResults;if(e==null)return!0;if(typeof e!="boolean")throw new Error(`saveResults must be a boolean (true or false), got ${typeof e}.`);return e}function In(o,e){if(!o)return{resultsSaved:!1,savedFiles:[],resultsNote:`saveResults was false: no files were written under ${ti}.`};let t=e??[];return t.length===0?{resultsSaved:!1,savedFiles:[],resultsNote:`No result files were written under ${ti} (saving is disabled or failed).`}:{resultsSaved:!0,savedFiles:t,resultsNote:`Saved ${t.length} result file(s) under ${ti}; see savedFiles. Pass saveResults: false to skip.`}}var ni={effectiveness:.25,coverage:.2,mutationKill:.15,stability:.15,maintainability:.15,performance:.1},ri={"short-term":{minSuccessCount:0,minSuccessRate:0,minQualityScore:0,minAgeDays:0},working:{minSuccessCount:3,minSuccessRate:.6,minQualityScore:.5,minAgeDays:1},"long-term":{minSuccessCount:10,minSuccessRate:.75,minQualityScore:.7,minAgeDays:7},permanent:{minSuccessCount:50,minSuccessRate:.9,minQualityScore:.85,minAgeDays:30}},Re={qualityWeights:ni,promotionCriteria:ri,autoPromote:!0,autoDemote:!0,minCoverageImprovementToLearn:5,maxOutcomesInMemory:1e4,persistOutcomes:!0,batchSize:100};ue();k();X();var ii=class{outcomes=[];maxOutcomes;constructor(e){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getAll(){return[...this.outcomes]}getByPattern(e){return this.outcomes.filter(t=>t.patternId===e)}getByAgent(e){return this.outcomes.filter(t=>t.generatedBy===e)}getByDomain(e){return this.outcomes.filter(t=>t.domain===e)}getRecent(e){return this.outcomes.slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},si=class o{store;reasoningBank=null;config;db=null;persistCount=0;static RETENTION_CLEANUP_INTERVAL=100;patternMetrics=new Map;constructor(e={}){this.config={...Re,...e},this.store=new ii(this.config.maxOutcomesInMemory)}connectReasoningBank(e){this.reasoningBank=e}async initialize(){try{this.db=Q(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb()}catch(e){console.warn("[TestOutcomeTracker] DB initialization failed, using memory-only:",E(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
418
+ `),p=m.length,g=0,f=[];p>500?(g+=.25,f.push(`Large file (${p} lines)`)):p>300&&(g+=.15,f.push(`Medium-large file (${p} lines)`));let h=d.match(/\b(if|else|switch|case|for|while|catch|&&|\|\|)\b/g)||[],v=h.length/Math.max(p,1);v>.15?(g+=.25,f.push(`High branch density (${h.length} branches in ${p} lines)`)):v>.08&&(g+=.1,f.push("Moderate branch complexity")),Math.max(...m.map(w=>{let T=w.match(/^(\s*)/);return T?T[1].length:0}))>20&&(g+=.15,f.push("Deep nesting detected"));let C=(d.match(/\b(TODO|FIXME|HACK|XXX|WORKAROUND)\b/gi)||[]).length;C>3&&(g+=.15,f.push(`${C} technical debt markers`));let b=(d.match(/\b(function|def|func|async)\b/g)||[]).length;if(b>0&&p/b>80&&(g+=.1,f.push("Potentially long functions")),g=Math.min(g,.95),g>=r){let w=u.startsWith(n)?u.slice(n.length).replace(/^\//,""):u;s.push({file:w,probability:Math.round(g*100)/100,reason:f.join("; ")})}}catch{}s.sort((u,d)=>d.probability-u.probability);let a=s.length>0?s.reduce((u,d)=>u+d.probability,0)/s.length:0,c=Math.round(a*100),l=[];if(s.length>0){l.push(`${s.length} files flagged for potential defects out of ${i.length} analyzed`);let u=s[0];l.push(`Highest risk: ${u.file} (${Math.round(u.probability*100)}%) \u2014 ${u.reason}`)}return s.some(u=>u.reason.includes("Large file"))&&l.push("Consider splitting large files to reduce complexity"),s.some(u=>u.reason.includes("technical debt"))&&l.push("Address TODO/FIXME comments to reduce technical debt"),s.length===0&&l.push("No files exceeded the defect probability threshold \u2014 code looks healthy"),_({predictedDefects:s.slice(0,20),riskScore:c,recommendations:l,filesAnalyzed:i.length})}catch(n){return L(z(n))}})}function Jr(o){o.registerHandler("test-accessibility",async e=>{let t=e.payload;return _({url:t.url||"",standard:t.standard||"wcag21-aa",passed:!1,violations:[],warnings:[],score:0,note:"Accessibility testing requires a browser environment (Puppeteer/Playwright). Use tools like axe-core, pa11y, or Lighthouse CLI for WCAG compliance testing. Example: npx pa11y "+(t.url||"<url>")})}),o.registerHandler("run-chaos",async e=>{let t=e.payload;return _({faultType:t.faultType||"unknown",target:t.target||"unknown",dryRun:t.dryRun??!0,duration:t.duration||0,systemBehavior:"not-executed",resilience:null,note:"Chaos engineering requires infrastructure-level fault injection. Use tools like Chaos Monkey, Litmus, or toxiproxy for real resilience testing. For Node.js apps, consider: nock (HTTP faults), testcontainers (dependency failures)."})}),o.registerHandler("optimize-learning",async e=>{try{let t=await import("./unified-memory-hnsw-ZOP5FEYX.js");return _({patternsLearned:0,modelsUpdated:0,memoryConsolidated:!1,note:'Learning optimization runs during the dream cycle (SessionEnd hook). Use "npx agentic-qe hooks session-end --save-state" to trigger pattern consolidation.'})}catch{return _({patternsLearned:0,modelsUpdated:0,memoryConsolidated:!1,note:'Learning system not initialized. Run "aqe init --auto" first.'})}})}var se=ye("TaskExecutor");function vu(o){return $e.resolve(qe.CoverageAnalyzerService)(o)}function bu(o){return $e.resolve(qe.SecurityScannerService)(o)}function Wa(o,e){return $e.resolve(qe.createTestGeneratorService)(o,e)}function Cu(o){return $e.resolve(qe.KnowledgeGraphService)(o)}function Su(o){return $e.resolve(qe.QualityAnalyzerService)(o)}function Ka(o){return o instanceof os?{...o.toDetails()}:_e(o)?{callerError:!0}:void 0}function Xa(o){return o===0?"agent-booster":Xi(o)}function Tu(o){if(["generate-tests","analyze-coverage","scan-security","execute-tests","assess-quality","validate-contracts","test-accessibility","chaos-test","predict-defects","validate-requirements","index-code"].includes(o.type))return null;let t=o.payload?.codeContext||"",n=o.payload?.sourceCode||"",r=t||n;return r?r.includes("var ")&&!r.includes("const ")&&!r.includes("let ")?"var-to-const":r.includes("console.log")||r.includes("console.warn")||r.includes("console.error")?"remove-console":r.includes(".then(")&&r.includes(".catch(")?"promise-to-async":r.includes("require(")&&!r.includes("import ")?"cjs-to-esm":r.includes("function ")&&!r.includes("=>")?"func-to-arrow":null:null}var ei=class{constructor(e,t,n){this.kernel=e;this.eventBus=t;this._config={timeout:n?.timeout??3e5,maxRetries:n?.maxRetries??3,enableCaching:n?.enableCaching??!0,saveResults:n?.saveResults??!0,resultsDir:n?.resultsDir??zt(),defaultLanguage:n?.defaultLanguage??"typescript",defaultFramework:n?.defaultFramework??"vitest"},this.resultSaver=va(this._config.resultsDir),this.registerHandlers()}kernel;eventBus;_config;resultSaver;coverageAnalyzer=null;securityScanner=null;testGenerator=null;deterministicTestGenerator=null;knowledgeGraph=null;qualityAnalyzer=null;agentBooster=null;taskRouter=null;qualityFeedbackLoop=null;coherenceActionGate=null;taskHandlers=new Map;get memory(){return this.kernel.memory}get config(){return this._config}registerHandler(e,t){this.taskHandlers.set(e,t)}setQualityFeedbackLoop(e){this.qualityFeedbackLoop=e}getCoverageAnalyzer(){return this.coverageAnalyzer||(this.coverageAnalyzer=vu(this.kernel.memory)),this.coverageAnalyzer}getSecurityScanner(){return this.securityScanner||(this.securityScanner=bu(this.kernel.memory)),this.securityScanner}async getTestGenerator(e=!0){return e?(this.testGenerator||(this.testGenerator=Wa(this.kernel.memory,await this.resolveLLMRouter())),this.testGenerator):(this.deterministicTestGenerator||(this.deterministicTestGenerator=Wa(this.kernel.memory)),this.deterministicTestGenerator)}async resolveLLMRouter(){if(this.kernel.llmRouter)return this.kernel.llmRouter;try{let{getSharedLLMRouter:e}=await import("./base-2XML4WH7.js");return await e()??void 0}catch(e){se.debug("LLM router unavailable; using deterministic generation",{error:E(e)});return}}getKnowledgeGraph(){return this.knowledgeGraph||(this.knowledgeGraph=Cu(this.kernel.memory)),this.knowledgeGraph}async getCodeIntelligenceCoordinator(){try{let e=this.kernel.getDomainAPIAsync?await this.kernel.getDomainAPIAsync("code-intelligence"):this.kernel.getDomainAPI("code-intelligence");return typeof e?.getCoordinator=="function"?e.getCoordinator():void 0}catch(e){se.debug("code-intelligence coordinator unavailable for project metrics",{error:e instanceof Error?e.message:String(e)});return}}getQualityAnalyzer(){return this.qualityAnalyzer||(this.qualityAnalyzer=Su(this.kernel.memory)),this.qualityAnalyzer}registerHandlers(){$r(this),Ur(this),Vr(this),Wr(this),Kr(this),Yr(this),Jr(this)}async getAgentBooster(){return this.agentBooster||(this.agentBooster=await Jt({enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7})),this.agentBooster}async getTaskRouterInstance(){if(!this.taskRouter)try{this.taskRouter=await Tn()}catch{return null}return this.taskRouter}async executeWithAgentBooster(e,t,n){let r=Tu(e);if(!r)return console.debug(`[TaskExecutor] No applicable Agent Booster transform for task ${e.id}`),null;try{let i=await this.getAgentBooster(),s=e.payload?.codeContext||e.payload?.sourceCode||"",a=await i.transform(s,r);return a.success&&a.confidence>=.7?(console.debug(`[TaskExecutor] Agent Booster transform succeeded: ${r}, confidence=${a.confidence}`),{taskId:e.id,success:!0,data:{transformed:!0,transformType:r,originalCode:a.originalCode,transformedCode:a.transformedCode,confidence:a.confidence,implementationUsed:a.implementationUsed,durationMs:a.durationMs,changeCount:a.changeCount,tier:0,model:"agent-booster"},duration:Date.now()-t,domain:n}):(console.debug(`[TaskExecutor] Agent Booster low confidence (${a.confidence}), falling back to Tier 1`),null)}catch(i){return console.warn(`[TaskExecutor] Agent Booster error, falling back: ${i}`),null}}async recordOutcome(e,t,n,r){try{if(!await this.getTaskRouterInstance())return;if(console.debug(`[TaskExecutor] Outcome recorded: task=${e.id}, tier=${t}, model=${Xa(t)}, success=${n}, duration=${r}ms`),this.qualityFeedbackLoop){let s=e.targetDomains||[],a=n?1:0,c=r<100?1:r<500?.8:r<2e3?.6:r<5e3?.4:r<1e4?.2:.1,l=.25*a+.325+.1*c;await this.qualityFeedbackLoop.recordRoutingOutcome({taskId:e.id,taskDescription:e.type,recommendedAgent:String(t),usedAgent:String(t),followedRecommendation:!0,success:n,qualityScore:l,durationMs:r,timestamp:new Date,error:n?void 0:"Task execution failed"})}}catch(i){console.warn("[TaskExecutor] Failed to record outcome:",i)}}async execute(e){let t=Date.now(),n=this.getTaskDomain(e.type),r=e.payload,i=r?.routingTier??2,s=r?.useAgentBooster??!1,a=r?.compiledContext??void 0,c=Xa(i);a&&e.payload&&(e.payload.__compiledContext=a),console.debug(`[TaskExecutor] Executing task ${e.id}: type=${e.type}, tier=${i}, model=${c}, useAgentBooster=${s}${a?", hasContext=true":""}`);let l=this.evaluateCoherenceGate(e,n);l&&console.debug(`[TaskExecutor] Coherence gate: task=${e.id}, decision=${l.decision}, combined=${l.combinedScore.toFixed(3)}, advisory=${l.advisory}`),this.validateWithReasoningQEC(e,n);try{if(i===0||s){let p=await this.executeWithAgentBooster(e,t,n);if(p)return this.recordOutcome(e,0,!0,Date.now()-t).catch(g=>{se.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),await this.publishTaskCompleted(e.id,p.data,n),p;console.debug(`[TaskExecutor] Agent Booster fallback to Tier 1 for task ${e.id}`)}let u=this.taskHandlers.get(e.type);if(!u){let p={taskId:e.id,success:!1,error:`No handler registered for task type: ${e.type}`,duration:Date.now()-t,domain:n};return this.recordOutcome(e,i,!1,Date.now()-t).catch(g=>{se.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),p}let d=await Promise.race([u(e),this.timeout(e.timeout||this._config.timeout)]);if(!d.success){let p="error"in d?d.error.message:"Unknown error";await this.publishTaskFailed(e.id,p,n,"error"in d&&_e(d.error)),this.recordOutcome(e,i,!1,Date.now()-t).catch(f=>{se.warn("recordOutcome failed",{error:f instanceof Error?f.message:String(f),taskId:e.id})});let g="error"in d?Ka(d.error):void 0;return{taskId:e.id,success:!1,error:p,duration:Date.now()-t,domain:n,...g?{errorDetails:g}:{}}}await this.publishTaskCompleted(e.id,d.value,n),this.recordOutcome(e,i,!0,Date.now()-t).catch(p=>{se.warn("recordOutcome failed",{error:p instanceof Error?p.message:String(p),taskId:e.id})});let m;if(this._config.saveResults&&r?.saveResults!==!1)try{let p={language:r?.language||this._config.defaultLanguage,framework:r?.framework||this._config.defaultFramework,includeSecondary:!0};m=(await this.resultSaver.save(e.id,e.type,d.value,p)).files.map(f=>f.path)}catch(p){console.error(`[TaskExecutor] Failed to save results: ${p}`)}return{taskId:e.id,success:!0,data:{...d.value,_routing:{tier:i,model:c,usedAgentBooster:!1}},duration:Date.now()-t,domain:n,savedFiles:m}}catch(u){let d=E(u);await this.publishTaskFailed(e.id,d,n,_e(u)),this.recordOutcome(e,i,!1,Date.now()-t).catch(p=>{se.warn("recordOutcome failed",{error:p instanceof Error?p.message:String(p),taskId:e.id})});let m=Ka(u);return{taskId:e.id,success:!1,error:d,duration:Date.now()-t,domain:n,...m?{errorDetails:m}:{}}}}async resetServiceCaches(){if(this.coverageAnalyzer=null,this.securityScanner=null,this.testGenerator=null,this.knowledgeGraph=null,this.qualityAnalyzer=null,this.coherenceActionGate=null,this.agentBooster){try{await this.agentBooster.dispose()}catch(e){console.debug("[TaskExecutor] Agent Booster disposal error:",e instanceof Error?e.message:e)}this.agentBooster=null}this.taskRouter=null}resetServiceCachesSync(){this.coverageAnalyzer=null,this.securityScanner=null,this.testGenerator=null,this.knowledgeGraph=null,this.qualityAnalyzer=null,this.agentBooster=null,this.taskRouter=null,this.coherenceActionGate=null}evaluateCoherenceGate(e,t){try{this.coherenceActionGate||(this.coherenceActionGate=wa({advisory:!0}));let n=e.payload,r=typeof n?.confidence=="number"?n.confidence:.7,i=n?.riskLevel??"medium";return Ra(e.type,t,r,i,n??{},this.coherenceActionGate)}catch(n){return se.warn("Coherence gate evaluation error (continuing)",{error:n instanceof Error?n.message:String(n),taskId:e.id}),null}}_reasoningQEC=null;_reasoningQECLoaded=!1;validateWithReasoningQEC(e,t){try{if(!this._reasoningQECLoaded){this._reasoningQECLoaded=!0;try{let{isReasoningQECEnabled:s}=($t(),Qi(hc));if(s()){let{createReasoningQEC:a}=(Qa(),Qi(Va));this._reasoningQEC=a()}}catch(s){se.debug("ReasoningQEC module unavailable",{error:s instanceof Error?s.message:String(s)})}}if(!this._reasoningQEC)return;let n=e.payload,r=n?.reasoningSteps;if(!r||r.length<2)return;let i=this._reasoningQEC.validate({type:t,context:n,steps:r});i.valid||se.warn("ReasoningQEC validation found issues (advisory)",{taskId:e.id,domain:t,confidence:i.confidence,issues:i.issues.length})}catch(n){se.debug("ReasoningQEC evaluation error",{error:n instanceof Error?n.message:String(n),taskId:e.id})}}getTaskDomain(e){return{"generate-tests":"test-generation","execute-tests":"test-execution","analyze-coverage":"coverage-analysis","assess-quality":"quality-assessment","predict-defects":"defect-intelligence","validate-requirements":"requirements-validation","index-code":"code-intelligence","scan-security":"security-compliance","validate-contracts":"contract-testing","test-accessibility":"visual-accessibility","run-chaos":"chaos-resilience","optimize-learning":"learning-optimization","cross-domain-workflow":"learning-optimization","protocol-execution":"learning-optimization","ideation-assessment":"requirements-validation"}[e]||"learning-optimization"}async timeout(e){return new Promise((t,n)=>{setTimeout(()=>n(new Error(`Task execution timed out after ${e}ms`)),e)})}async publishTaskCompleted(e,t,n){await this.eventBus.publish({id:G(),type:"TaskCompleted",timestamp:new Date,source:n,payload:{taskId:e,result:t}})}async publishTaskFailed(e,t,n,r=!1){await this.eventBus.publish({id:G(),type:"TaskFailed",timestamp:new Date,source:n,payload:{taskId:e,error:t,...r?{callerError:!0}:{}}})}};function Ya(o,e){return new ei(o,o.eventBus,e)}async function Ja(){}import{randomUUID as He}from"crypto";k();var ti=".agentic-qe/results/";function Za(o){if(o===null||typeof o!="object")return!0;let e=o.saveResults;if(e==null)return!0;if(typeof e!="boolean")throw new Error(`saveResults must be a boolean (true or false), got ${typeof e}.`);return e}function In(o,e){if(!o)return{resultsSaved:!1,savedFiles:[],resultsNote:`saveResults was false: no files were written under ${ti}.`};let t=e??[];return t.length===0?{resultsSaved:!1,savedFiles:[],resultsNote:`No result files were written under ${ti} (saving is disabled or failed).`}:{resultsSaved:!0,savedFiles:t,resultsNote:`Saved ${t.length} result file(s) under ${ti}; see savedFiles. Pass saveResults: false to skip.`}}var ni={effectiveness:.25,coverage:.2,mutationKill:.15,stability:.15,maintainability:.15,performance:.1},ri={"short-term":{minSuccessCount:0,minSuccessRate:0,minQualityScore:0,minAgeDays:0},working:{minSuccessCount:3,minSuccessRate:.6,minQualityScore:.5,minAgeDays:1},"long-term":{minSuccessCount:10,minSuccessRate:.75,minQualityScore:.7,minAgeDays:7},permanent:{minSuccessCount:50,minSuccessRate:.9,minQualityScore:.85,minAgeDays:30}},Re={qualityWeights:ni,promotionCriteria:ri,autoPromote:!0,autoDemote:!0,minCoverageImprovementToLearn:5,maxOutcomesInMemory:1e4,persistOutcomes:!0,batchSize:100};ue();k();X();var ii=class{outcomes=[];maxOutcomes;constructor(e){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getAll(){return[...this.outcomes]}getByPattern(e){return this.outcomes.filter(t=>t.patternId===e)}getByAgent(e){return this.outcomes.filter(t=>t.generatedBy===e)}getByDomain(e){return this.outcomes.filter(t=>t.domain===e)}getRecent(e){return this.outcomes.slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},si=class o{store;reasoningBank=null;config;db=null;persistCount=0;static RETENTION_CLEANUP_INTERVAL=100;patternMetrics=new Map;constructor(e={}){this.config={...Re,...e},this.store=new ii(this.config.maxOutcomesInMemory)}connectReasoningBank(e){this.reasoningBank=e}async initialize(){try{this.db=Q(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb()}catch(e){console.warn("[TestOutcomeTracker] DB initialization failed, using memory-only:",E(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
419
419
  SELECT * FROM test_outcomes ORDER BY created_at DESC LIMIT ?
420
420
  `).all(this.config.maxOutcomesInMemory);for(let n of t.reverse()){let r={id:n.id,testId:n.test_id,testName:n.test_name,generatedBy:n.generated_by,patternId:n.pattern_id||void 0,framework:n.framework,language:n.language,domain:n.domain,passed:!!n.passed,errorMessage:n.error_message||void 0,coverage:{lines:n.coverage_lines,branches:n.coverage_branches,functions:n.coverage_functions},mutationScore:n.mutation_score??void 0,executionTimeMs:n.execution_time_ms,flaky:!!n.flaky,flakinessScore:n.flakiness_score??void 0,maintainabilityScore:n.maintainability_score,complexity:n.complexity??void 0,linesOfCode:n.lines_of_code??void 0,assertionCount:n.assertion_count??void 0,filePath:n.file_path||void 0,sourceFilePath:n.source_file_path||void 0,timestamp:new Date(n.created_at),metadata:n.metadata_json?M(n.metadata_json):void 0};this.store.add(r),r.patternId&&this.updatePatternMetrics(r)}t.length>0&&console.log(`[TestOutcomeTracker] Loaded ${t.length} outcomes from DB`)}persistOutcome(e){if(this.db)try{let t=this.db.getDatabase();t.prepare(`
421
421
  INSERT OR REPLACE INTO test_outcomes (
@@ -446,7 +446,7 @@ ${e.trim()}`}function Gl(o,e,t=e,n=10){let r=$.resolve(o);for(let i=0;i<=n;i++){
446
446
  )
447
447
  `).run(t)}catch(t){console.warn("[CoverageLearner] Retention cleanup failed:",E(t))}}async learnFromSession(e){this.sessionStore.add(e),this.persistSession(e);let t=this.calculateOverallImprovement(e);if(t<this.config.minCoverageImprovementToLearn)return null;let n=await this.extractStrategy(e,t);return this.reasoningBank&&n&&await this.storeStrategyAsPattern(n),n}calculateOverallImprovement(e){let t=e.beforeCoverage,n=e.afterCoverage,r=n.lines-t.lines,i=n.branches-t.branches,s=n.functions-t.functions;return r*.4+i*.35+s*.25}async extractStrategy(e,t){let n=this.extractFilePattern(e.targetPath),r=`${e.technique}:${n}`,i=this.strategies.get(r);return i?i={...i,avgImprovement:(i.avgImprovement*i.successCount+t)/(i.successCount+1),successCount:i.successCount+1,confidence:Math.min(1,i.confidence+.05),lastUsedAt:new Date}:i={id:`strategy-${Date.now()}-${Eu().slice(0,8)}`,description:this.generateStrategyDescription(e,t),technique:e.technique,filePatterns:[n],avgImprovement:t,successCount:1,confidence:.5,createdAt:new Date,lastUsedAt:new Date},this.strategies.set(r,i),i}extractFilePattern(e){let t=e.split("/"),r=t[t.length-1].split(".").pop()||"";return t.length>=2?`${t[t.length-2]}/*.${r}`:`*.${r}`}generateStrategyDescription(e,t){let r={"gap-analysis":"Identify and target uncovered code paths","branch-coverage":"Focus on branch conditions and decision points","edge-case-generation":"Generate tests for edge cases and boundary conditions","mutation-guided":"Use mutation testing to identify weak test areas","risk-based":"Prioritize high-risk code paths","semantic-analysis":"Use code semantics to generate meaningful tests","boundary-testing":"Test boundary conditions and limits","state-machine":"Model state transitions and test state changes","data-flow":"Follow data flow paths through the code"}[e.technique]||e.technique,i=e.gapsTargeted.filter(a=>a.addressed).length,s=e.gapsTargeted.length;return`${r} for ${this.extractFilePattern(e.targetPath)} files. Achieved ${t.toFixed(1)}% improvement. Addressed ${i}/${s} gaps with ${e.testsGenerated} tests.`}async storeStrategyAsPattern(e){this.reasoningBank&&await this.reasoningBank.storeQEPattern({patternType:"coverage-strategy",name:`Coverage Strategy: ${e.technique}`,description:e.description,template:{type:"workflow",content:JSON.stringify({technique:e.technique,filePatterns:e.filePatterns,avgImprovement:e.avgImprovement}),variables:[{name:"targetFile",type:"string",required:!0,description:"Target file to analyze"},{name:"currentCoverage",type:"number",required:!0,description:"Current coverage percentage"}]},context:{tags:["coverage",e.technique,...e.filePatterns]}})}getRecommendedStrategy(e){let t=this.extractFilePattern(e),n=null,r=0;for(let i of this.strategies.values())if(i.filePatterns.some(a=>t.includes(a.split("/").pop()||"")||a.includes(t.split("/").pop()||""))||i.filePatterns.length===0){let a=(Date.now()-i.lastUsedAt.getTime())/864e5,c=Math.max(.5,1-a/30),l=i.avgImprovement*i.confidence*c;l>r&&(r=l,n=i)}return n}getAllStrategies(){return Array.from(this.strategies.values())}getStrategiesByTechnique(e){return this.getAllStrategies().filter(t=>t.technique===e)}getSessionStats(){let e=this.sessionStore.getAll();if(e.length===0)return{totalSessions:0,successfulSessions:0,avgImprovement:0,byTechnique:new Map,strategiesLearned:0};let t=e.map(a=>this.calculateOverallImprovement(a)),n=t.filter(a=>a>=this.config.minCoverageImprovementToLearn).length,r=t.reduce((a,c)=>a+c,0)/t.length,i=new Map,s=new Map;for(let a of e){let c=s.get(a.technique)||[];c.push(a),s.set(a.technique,c)}for(let[a,c]of s){let l=c.map(u=>this.calculateOverallImprovement(u));i.set(a,{count:c.length,avgImprovement:l.reduce((u,d)=>u+d,0)/l.length})}return{totalSessions:e.length,successfulSessions:n,avgImprovement:r,byTechnique:i,strategiesLearned:this.strategies.size}}analyzeGapResolution(){let t=this.sessionStore.getAll().flatMap(i=>i.gapsTargeted);if(t.length===0)return{totalGapsTargeted:0,gapsAddressed:0,resolutionRate:0,byGapType:new Map};let n=t.filter(i=>i.addressed).length,r=new Map;for(let i of t){let s=r.get(i.type)||{targeted:0,addressed:0};s.targeted++,i.addressed&&s.addressed++,r.set(i.type,s)}return{totalGapsTargeted:t.length,gapsAddressed:n,resolutionRate:n/t.length,byGapType:r}}exportSessions(){return this.sessionStore.getAll()}importSessions(e){for(let t of e)this.sessionStore.add(t)}exportStrategies(){return this.getAllStrategies()}importStrategies(e){for(let t of e){let n=`${t.technique}:${t.filePatterns[0]||"*"}`;this.strategies.set(n,t)}}clear(){this.sessionStore.clear(),this.strategies.clear()}getLearnerStats(){return{totalSessions:this.sessionStore.size,totalStrategies:this.strategies.size,hasReasoningBank:this.reasoningBank!==null,minImprovementThreshold:this.config.minCoverageImprovementToLearn}}};function to(o){return new oi(o)}var ci=class{weights;historicalScores=[];maxHistory;constructor(e={},t=100){this.weights={...ni,...e},this.maxHistory=t}calculateFromOutcome(e){let t=this.calculateDimensions(e),n=this.calculateOverall(t);return this.trackScore(n),{overall:n,dimensions:t,weights:this.weights,trend:this.calculateTrend(),calculatedAt:new Date}}calculateDimensions(e){return{effectiveness:this.calculateEffectiveness(e),coverage:this.calculateCoverageScore(e.coverage),mutationKill:e.mutationScore??.5,stability:this.calculateStability(e),maintainability:e.maintainabilityScore,performance:this.calculatePerformanceScore(e.executionTimeMs)}}calculateEffectiveness(e){return e.passed?e.flaky?.3:1:0}calculateCoverageScore(e){return(e.lines*.4+e.branches*.35+e.functions*.25)/100}calculateStability(e){return e.flaky?.2:e.flakinessScore!==void 0?1-e.flakinessScore:1}calculatePerformanceScore(e){return e<100?1:e<500?.8:e<2e3?.6:e<5e3?.4:e<1e4?.2:.1}calculateOverall(e){return this.weights.effectiveness*e.effectiveness+this.weights.coverage*e.coverage+this.weights.mutationKill*e.mutationKill+this.weights.stability*e.stability+this.weights.maintainability*e.maintainability+this.weights.performance*e.performance}trackScore(e){this.historicalScores.push(e),this.historicalScores.length>this.maxHistory&&(this.historicalScores=this.historicalScores.slice(-this.maxHistory))}calculateTrend(){if(this.historicalScores.length<10)return"stable";let e=this.historicalScores.slice(-10),t=this.historicalScores.slice(-20,-10);if(t.length===0)return"stable";let n=e.reduce((s,a)=>s+a,0)/e.length,r=t.reduce((s,a)=>s+a,0)/t.length,i=n-r;return i>.05?"improving":i<-.05?"declining":"stable"}calculateAggregate(e){if(e.length===0)return{overall:0,dimensions:{effectiveness:0,coverage:0,mutationKill:0,stability:0,maintainability:0,performance:0},weights:this.weights,trend:"stable",calculatedAt:new Date};let t={effectiveness:0,coverage:0,mutationKill:0,stability:0,maintainability:0,performance:0};for(let s of e){let a=this.calculateDimensions(s);t.effectiveness+=a.effectiveness,t.coverage+=a.coverage,t.mutationKill+=a.mutationKill,t.stability+=a.stability,t.maintainability+=a.maintainability,t.performance+=a.performance}let n=e.length,r={effectiveness:t.effectiveness/n,coverage:t.coverage/n,mutationKill:t.mutationKill/n,stability:t.stability/n,maintainability:t.maintainability/n,performance:t.performance/n};return{overall:this.calculateOverall(r),dimensions:r,weights:this.weights,trend:this.calculateTrend(),calculatedAt:new Date}}calculateDelta(e,t){let n={effectiveness:t.dimensions.effectiveness-e.dimensions.effectiveness,coverage:t.dimensions.coverage-e.dimensions.coverage,mutationKill:t.dimensions.mutationKill-e.dimensions.mutationKill,stability:t.dimensions.stability-e.dimensions.stability,maintainability:t.dimensions.maintainability-e.dimensions.maintainability,performance:t.dimensions.performance-e.dimensions.performance},r=t.overall-e.overall;return{overallDelta:r,dimensionDeltas:n,improved:r>0}}getRecommendations(e){let t=[],n=e.dimensions;return n.effectiveness<.8&&t.push("Improve test pass rate - investigate failing tests"),n.coverage<.7&&t.push("Increase code coverage - target uncovered paths"),n.mutationKill<.6&&t.push("Strengthen assertions - tests may be too weak"),n.stability<.9&&t.push("Address test flakiness - stabilize intermittent tests"),n.maintainability<.7&&t.push("Improve test maintainability - reduce complexity"),n.performance<.6&&t.push("Optimize test performance - reduce execution time"),t.length===0&&t.push("Quality is excellent - maintain current practices"),t}updateWeights(e){this.weights={...this.weights,...e}}getWeights(){return{...this.weights}}getStats(){let e=this.historicalScores.slice(-10),t=e.length>0?e.reduce((n,r)=>n+r,0)/e.length:0;return{scoresTracked:this.historicalScores.length,currentTrend:this.calculateTrend(),avgRecentScore:t}}clearHistory(){this.historicalScores=[]}};function no(o,e){return new ci(o,e)}var li=class{criteria;promotionHistory=[];demotionHistory=[];reasoningBank=null;config;constructor(e={}){this.config={...Re,...e},this.criteria={...ri}}connectReasoningBank(e){this.reasoningBank=e}evaluatePromotion(e,t){let n=e.tier,r=this.getNextTier(n);if(!r)return null;let i=this.criteria[r];if(this.meetsPromotionCriteria(t,i)){let s={patternId:e.id,fromTier:n,toTier:r,reason:this.generatePromotionReason(t,i),metrics:{successCount:t.successCount,successRate:t.successRate,qualityScore:t.qualityScore,ageDays:t.ageDays},timestamp:new Date};return this.promotionHistory.push(s),s}return null}evaluateDemotion(e,t){if(!this.config.autoDemote)return null;let n=e.tier;if(n==="short-term")return null;if(t.recentSuccessRate<.4||t.recentFailureCount>=5||t.qualityScore<.3){let i=this.getPreviousTier(n);if(!i)return null;let s={patternId:e.id,fromTier:n,toTier:i,reason:this.generateDemotionReason(t),metrics:{recentSuccessRate:t.recentSuccessRate,recentQualityScore:t.qualityScore,failureCount:t.recentFailureCount},timestamp:new Date};return this.demotionHistory.push(s),s}return null}async processPatternChange(e,t){let n=this.evaluateDemotion(e,t);if(n)return this.reasoningBank&&await this.reasoningBank.demotePattern(e.id),{action:"demoted",event:n};let r=this.evaluatePromotion(e,t);return r?(this.reasoningBank&&await this.reasoningBank.promotePattern(e.id),{action:"promoted",event:r}):{action:"unchanged"}}meetsPromotionCriteria(e,t){return e.successCount>=t.minSuccessCount&&e.successRate>=t.minSuccessRate&&e.qualityScore>=t.minQualityScore&&e.ageDays>=t.minAgeDays}getNextTier(e){let t=["short-term","working","long-term","permanent"],n=t.indexOf(e);return n<t.length-1?t[n+1]:null}getPreviousTier(e){let t=["short-term","working","long-term","permanent"],n=t.indexOf(e);return n>0?t[n-1]:null}generatePromotionReason(e,t){let n=[];return e.successCount>=t.minSuccessCount&&n.push(`${e.successCount} successful uses (>=${t.minSuccessCount})`),e.successRate>=t.minSuccessRate&&n.push(`${(e.successRate*100).toFixed(0)}% success rate (>=${t.minSuccessRate*100}%)`),e.qualityScore>=t.minQualityScore&&n.push(`${(e.qualityScore*100).toFixed(0)}% quality score (>=${t.minQualityScore*100}%)`),`Pattern promoted: ${n.join(", ")}`}generateDemotionReason(e){let t=[];return e.recentSuccessRate<.4&&t.push(`low recent success rate (${(e.recentSuccessRate*100).toFixed(0)}%)`),e.recentFailureCount>=5&&t.push(`${e.recentFailureCount} recent failures`),e.qualityScore<.3&&t.push(`low quality score (${(e.qualityScore*100).toFixed(0)}%)`),`Pattern demoted: ${t.join(", ")}`}updateCriteria(e,t){this.criteria[e]={...this.criteria[e],...t}}getCriteria(e){return{...this.criteria[e]}}getAllCriteria(){return{...this.criteria}}getPromotionHistory(e=100){return this.promotionHistory.slice(-e)}getDemotionHistory(e=100){return this.demotionHistory.slice(-e)}getStats(){let e={"short-term":0,working:0,"long-term":0,permanent:0};for(let s of this.promotionHistory)e[s.toTier]++;let t={"short-term":0,working:0,"long-term":0,permanent:0};for(let s of this.demotionHistory)t[s.toTier]++;let n=Date.now()-10080*60*1e3,r=this.promotionHistory.filter(s=>s.timestamp.getTime()>n).length,i=this.demotionHistory.filter(s=>s.timestamp.getTime()>n).length;return{totalPromotions:this.promotionHistory.length,totalDemotions:this.demotionHistory.length,promotionsByTier:e,demotionsByTier:t,recentPromotions:r,recentDemotions:i}}exportHistory(){return{promotions:[...this.promotionHistory],demotions:[...this.demotionHistory]}}importHistory(e){e.promotions&&this.promotionHistory.push(...e.promotions),e.demotions&&this.demotionHistory.push(...e.demotions)}clearHistory(){this.promotionHistory=[],this.demotionHistory=[]}};function ro(o){return new li(o)}var ui=class{outcomeTracker;coverageLearner;qualityCalculator;promotionManager;routingFeedback;reasoningBank=null;config;constructor(e={}){this.config={...Re,...e},this.outcomeTracker=eo(this.config),this.coverageLearner=to(this.config),this.qualityCalculator=no(this.config.qualityWeights),this.promotionManager=ro(this.config),this.routingFeedback=as(this.config.maxOutcomesInMemory)}async initialize(){await Promise.all([this.outcomeTracker.initialize(),this.coverageLearner.initialize(),this.routingFeedback.initialize()])}connectReasoningBank(e){this.reasoningBank=e,this.outcomeTracker.connectReasoningBank(e),this.coverageLearner.connectReasoningBank(e),this.promotionManager.connectReasoningBank(e)}async recordTestOutcome(e){await this.outcomeTracker.track(e);let t=this.qualityCalculator.calculateFromOutcome(e),n;if(e.patternId&&this.reasoningBank){let r=await this.reasoningBank.searchQEPatterns(e.patternId,{limit:1});if(r.success&&r.value.length>0){let i=r.value[0].pattern,s=this.outcomeTracker.getPatternMetrics(e.patternId);if(s){let a=await this.promotionManager.processPatternChange(i,{patternId:e.patternId,successCount:s.successCount,failureCount:s.failureCount,successRate:s.successRate,qualityScore:s.avgQuality,ageDays:this.calculateAgeDays(i.createdAt),recentSuccessRate:this.calculateRecentSuccessRate(e.patternId),recentFailureCount:this.calculateRecentFailures(e.patternId)});n={action:a.action,tier:a.event&&"toTier"in a.event?a.event.toTier:void 0}}}}return{qualityScore:t,patternUpdate:n}}async recordCoverageSession(e){let t=await this.coverageLearner.learnFromSession(e);return{improvement:(e.afterCoverage.lines-e.beforeCoverage.lines+e.afterCoverage.branches-e.beforeCoverage.branches+e.afterCoverage.functions-e.beforeCoverage.functions)/3,strategyLearned:t!==null,strategyId:t?.id}}getRecommendedCoverageStrategy(e){return this.coverageLearner.getRecommendedStrategy(e)}getQualityRecommendations(){let e=this.outcomeTracker.getRecentOutcomes(50);if(e.length===0)return["No test outcomes recorded yet. Start tracking test results to get recommendations."];let t=this.qualityCalculator.calculateAggregate(e);return this.qualityCalculator.getRecommendations(t)}async recordRoutingOutcome(e){let t={id:e.taskId,description:e.taskDescription,complexity:"medium",domains:["test-generation"],context:{}},n={recommended:e.recommendedAgent,confidence:.8,reasoning:"Recorded from feedback",alternatives:[],scores:{similarity:.8,performance:.8,capabilities:.8,combined:.8},latencyMs:0,timestamp:e.timestamp};this.routingFeedback.recordOutcome(t,n,e.usedAgent,{success:e.success,qualityScore:e.qualityScore,durationMs:e.durationMs,error:e.error})}getRoutingAnalysis(){let e=this.routingFeedback.analyzeRoutingAccuracy(),t=this.routingFeedback.getImprovementRecommendations();return{totalOutcomes:e.totalOutcomes,recommendationFollowRate:1-e.overrideRate,successRateWhenFollowed:e.recommendationSuccessRate,successRateWhenOverridden:e.overrideSuccessRate,confidenceCorrelation:e.confidenceCorrelation,recommendations:t}}calculateAgeDays(e){return(Date.now()-e.getTime())/(1e3*60*60*24)}calculateRecentSuccessRate(e){let t=this.outcomeTracker.exportOutcomes().filter(r=>r.patternId===e).slice(-10);return t.length===0?0:t.filter(r=>r.passed&&!r.flaky).length/t.length}calculateRecentFailures(e){return this.outcomeTracker.exportOutcomes().filter(n=>n.patternId===e).slice(-10).filter(n=>!n.passed||n.flaky).length}getStats(){let e=this.outcomeTracker.getStats(),t=this.coverageLearner.getSessionStats(),n=this.promotionManager.getStats(),r=this.qualityCalculator.getStats(),i=this.outcomeTracker.getTrackerStats(),s=this.routingFeedback.analyzeRoutingAccuracy();return{testOutcomes:{total:e.totalTests,passRate:e.passRate,avgQuality:e.avgMaintainability,flakyCount:e.flakyTests},coverage:{totalSessions:t.totalSessions,successfulSessions:t.successfulSessions,avgImprovement:t.avgImprovement,strategiesLearned:t.strategiesLearned},patterns:{promoted:n.totalPromotions,demoted:n.totalDemotions,tracked:i.patternsTracked},quality:{currentTrend:r.currentTrend,avgRecentScore:r.avgRecentScore},routing:{totalOutcomes:s.totalOutcomes,recommendationFollowRate:1-s.overrideRate,successRateWhenFollowed:s.recommendationSuccessRate,successRateWhenOverridden:s.overrideSuccessRate},integrationStatus:{reasoningBankConnected:this.reasoningBank!==null}}}exportData(){return{outcomes:this.outcomeTracker.exportOutcomes(),sessions:this.coverageLearner.exportSessions(),strategies:this.coverageLearner.exportStrategies(),promotionHistory:this.promotionManager.exportHistory(),routingOutcomes:this.routingFeedback.exportOutcomes()}}importData(e){e.outcomes&&this.outcomeTracker.importOutcomes(e.outcomes),e.sessions&&this.coverageLearner.importSessions(e.sessions),e.strategies&&this.coverageLearner.importStrategies(e.strategies),e.promotionHistory&&this.promotionManager.importHistory(e.promotionHistory),e.routingOutcomes&&this.routingFeedback.importOutcomes(e.routingOutcomes)}clear(){this.outcomeTracker.clear(),this.coverageLearner.clear(),this.qualityCalculator.clearHistory(),this.promotionManager.clearHistory(),this.routingFeedback.clear()}};async function io(o){let e=new ui(o);return await e.initialize(),so=e,e}var so=null;function ao(){return so}function Ve(){return`test-${He()}`}function co(o){return`${o}-${He()}`}function Dn(o){return{enabled:!0,agentId:co(o),message:"Experience captured asynchronously via learning pipeline"}}async function wu(o,e,t,n,r){let i=co(o);try{let{kernel:s}=Ct();if(!s)return{enabled:!1,agentId:i,message:"Learning engine not available - kernel not initialized"};let a=await Pu();if(!a)return{enabled:!1,agentId:i,message:"Learning engine not available"};let c=a.getExperienceCaptureService();if(!c)return{enabled:!1,agentId:i,message:"Experience capture service not available"};let l=Ru(e),u=c.startCapture(`${e}: ${JSON.stringify(t).slice(0,200)}`,{agent:o,domain:l||void 0,metadata:{tool:e,durationMs:r}});c.recordStep(u,{action:`execute-${e}`,result:typeof n=="object"?JSON.stringify(n).slice(0,500):String(n).slice(0,500),quality:.7});let d=await c.completeCapture(u,{success:!0,quality:.7});if(d.success){let m=d.value;return{enabled:!0,agentId:i,message:`Experience captured: ${m.id} (domain: ${l||"general"}, quality: ${m.quality})`,experienceId:m.id,domain:l||"general"}}return{enabled:!0,agentId:i,message:"Experience capture completed (no pattern extracted)"}}catch(s){return{enabled:!1,agentId:i,message:`Learning capture failed: ${E(s)}`}}}function Ru(o){return{test_generate_enhanced:"test-generation",test_execute_parallel:"test-execution",coverage_analyze_sublinear:"coverage-analysis",quality_assess:"quality-assessment",security_scan_comprehensive:"security-compliance",contract_validate:"contract-testing",accessibility_test:"visual-accessibility",chaos_test:"chaos-resilience",defect_predict:"defect-intelligence",requirements_validate:"requirements-validation",code_index:"code-intelligence"}[o]||null}async function Pu(){return fo()}async function xu(o,e,t,n){let r=ao();if(!r&&di&&(r=await di),!!r){if(o==="test-generation"&&e){let i=e.tests||e.generatedTests||[];for(let s of i.slice(0,20)){let a={id:String(s.id||He()),testId:String(s.id||s.name||He()),testName:String(s.name||s.testName||"generated-test"),generatedBy:"qe-test-generation",patternId:s.patternId,framework:s.framework||n.framework||"vitest",language:s.language||n.language||"typescript",domain:"test-generation",passed:s.passed!==!1,coverage:{lines:Number(s.coverageLines||0),branches:Number(s.coverageBranches||0),functions:Number(s.coverageFunctions||0)},executionTimeMs:Number(s.executionTimeMs||t/Math.max(i.length,1)),flaky:!!s.flaky,maintainabilityScore:Number(s.qualityScore||s.maintainability||.7),timestamp:new Date};await r.recordTestOutcome(a)}}if(o==="coverage-analysis"&&e&&nn(o,e)){let i={id:He(),targetPath:String(n.target||n.targetPath||"src/"),agentId:"qe-coverage-analysis",technique:n.technique||"gap-analysis",beforeCoverage:{lines:Number(e.beforeCoverage?.lines||0),branches:Number(e.beforeCoverage?.branches||0),functions:Number(e.beforeCoverage?.functions||0)},afterCoverage:{lines:Number(e.lineCoverage||e.lines||0),branches:Number(e.branchCoverage||e.branches||0),functions:Number(e.functionCoverage||e.functions||0)},testsGenerated:Number(e.testsGenerated||0),testsPassed:Number(e.testsPassed||0),gapsTargeted:(e.gaps||[]).map((s,a)=>({id:String(s.id||`gap-${He().slice(0,8)}-${a}`),type:["uncovered-line","uncovered-branch","uncovered-function","partial-branch"].includes(String(s.type))?String(s.type):"uncovered-line",filePath:String(s.file||s.filePath||""),startLine:Number(s.line||s.startLine||0),endLine:s.endLine?Number(s.endLine):void 0,riskScore:Number(s.riskScore||.5),addressed:!!s.addressed})),durationMs:t,startedAt:new Date(Date.now()-t),completedAt:new Date,context:{measured:!0,coverageMethod:e.coverageMethod??"instrumented-report",branchDataCollected:e.branchCoverage!==null&&e.branchCoverage!==void 0,functionDataCollected:e.functionCoverage!==null&&e.functionCoverage!==void 0}};await r.recordCoverageSession(i)}}}function lo(o){let e=o.split(`
448
448
  `).length,t=(o.match(/if|switch|for|while|catch/g)||[]).length;return{score:e+t*2,level:t>5?"high":t>2?"medium":"low"}}function uo(o,e){let t=[];return o.level==="high"&&(t.push("Consider refactoring complex functions"),t.push("Add unit tests for each branch")),t.push("Consider adding edge case tests"),t.push("Add error handling tests"),e==="integration"&&(t.push("Add mock external dependencies"),t.push("Test API contract boundaries")),{recommendations:t,estimatedTime:`${Math.round(o.score*.5)} minutes`,confidence:.85}}function mo(o,e,t,n){let r=[],i=/(?:function\s+(\w+)|const\s+(\w+)\s*=|def\s+(\w+)|func\s+(\w+))/g,s=[],a;for(;(a=i.exec(o))!==null;){let l=a[1]||a[2]||a[3]||a[4];l&&s.push(l)}for(let l=0;l<Math.min(s.length,n);l++){let u=s[l]||"exampleFunction";r.push({id:Ve(),name:`test_${u}_${l}`,type:e,parameters:[],assertions:[`${u}() === null`],expectedResult:null,estimatedDuration:e==="integration"?2e3:1e3,aiGenerated:!0})}(e==="integration"||n>s.length)&&r.push({id:Ve(),name:`integration_ComponentA_${r.length}`,type:"integration",parameters:[],assertions:["ComponentA integration test passes"],expectedResult:null,estimatedDuration:2e3,aiGenerated:!0});let c=["high-complexity","deep-nesting","null-handling","empty-input"];for(let l=r.length;l<n&&l-r.length<c.length;l++)r.push({id:Ve(),name:`edge_case_${c[l-r.length]}_${l}`,type:"unit",parameters:[],assertions:[`${c[l-r.length]} edge case handled`],expectedResult:null,estimatedDuration:1500,aiGenerated:!0});return r}function po(o,e){let t=[],n=o.split(`
449
- `);return o.includes("eval(")&&t.push({type:"dangerous-eval",line:n.findIndex(r=>r.includes("eval("))+1,severity:"critical",suggestion:"Replace eval() with safer alternatives"}),o.includes("var ")&&(e==="javascript"||e==="typescript")&&t.push({type:"var-usage",line:n.findIndex(r=>r.includes("var "))+1,severity:"low",suggestion:"Use const or let instead of var"}),o.includes("any")&&e==="typescript"&&t.push({type:"any-type",line:n.findIndex(r=>r.includes("any"))+1,severity:"medium",suggestion:"Replace any with specific types"}),t}var bt=null,di=null,de=null,Au=Number(process.env.AQE_ROUTE_TIMEOUT_MS)||5e3;function ku(o,e,t){return new Promise(n=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(t))},e);typeof i.unref=="function"&&i.unref(),o.then(s=>{r||(r=!0,clearTimeout(i),n(s))},()=>{r||(r=!0,clearTimeout(i),n(t))})})}function Mu(){if(!bt){let{kernel:o}=Ct();if(!o)throw new Error("Kernel not initialized");bt=Ya(o);let e=bt;di=io().then(t=>(e.setQualityFeedbackLoop(t),t)).catch(t=>(console.warn("[HandlerFactory] Failed to initialize QualityFeedbackLoop:",t),null))}return bt}function go(){if(bt=null,de){let o=de;de=null,o.dispose().catch(()=>{})}}async function fo(){if(de)return de;try{let{kernel:o}=Ct();if(!o)return null;let{createAQELearningEngine:e}=await import("./aqe-learning-engine-DHKZI5RX.js"),t=o.memory,n=e(t,{projectRoot:process.cwd(),enableClaudeFlow:!1});return await n.initialize(),de=n,de}catch(o){return console.debug("[HandlerFactory] Learning engine init failed:",E(o)),null}}async function Iu(o,e){try{let t=await fo();if(!t)return[];let n=e,r=await t.searchPatterns(o,{limit:5,minConfidence:.4,domain:n,useVectorSearch:!0});return!r.success||r.value.length===0?[]:r.value.filter(i=>i.similarity>=.4).map(i=>({name:i.pattern.name,description:i.pattern.description,similarity:i.similarity,confidence:i.pattern.confidence,canReuse:i.canReuse,patternId:i.pattern.id}))}catch(t){return console.debug("[HandlerFactory] Pattern search failed:",E(t)),[]}}async function Du(o,e,t){try{let n=await Iu(o,e);return n.length>0&&console.debug(`[HandlerFactory] Found ${n.length} relevant patterns for ${e}`),await(await Tn()).routeTask({task:o,domain:e,codeContext:t,agentType:`qe-${e}`,enablePatternSearch:!0,patternHints:n.length>0?n:void 0})}catch(n){return console.error(`[HandlerFactory] Routing failed for ${e}: ${n}`),null}}async function oo(o,e,t,n){if(!(!o||o.length===0)&&de)try{for(let r of o)r.patternId&&await de.recordOutcome({patternId:r.patternId,success:e,metrics:{executionTimeMs:n},feedback:`Domain handler ${t} execution ${e?"succeeded":"failed"}`})}catch{}}function Z(o){let{domain:e,taskType:t,priority:n="p1",defaultTimeout:r=18e4,buildTaskDescription:i,mapToPayload:s,mapToResult:a,calculateTimeout:c,includeCodeContext:l}=o;return async u=>{if(!Qe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:d}=Ct(),m=null;try{let p=Za(u),g=i(u),f=l?.(u);m=await ku(Du(g,e,f),Au,null);let h=s(u,m);p||(h.saveResults=!1);let v=c?.(u)??r,y=await d.submitTask({type:t,priority:n,targetDomains:[e],payload:h,timeout:v});if(!y.success)return{success:!1,error:y.error.message};let C=Mu(),b=d.getTaskStatus(y.value);if(!b)return{success:!1,error:"Task not found after submission"};let w=await C.execute(b.task);if(!w.success)return{success:!1,error:w.error||"Task execution failed",...w.errorDetails?{data:w.errorDetails}:{}};let T=w.data,S=a(y.value,T,w.duration,w.savedFiles,u);if(Object.assign(S,In(p,w.savedFiles)),nn(e,T)&&nn("",S)){oo(m?.patternHints,!0,e,w.duration),wu(`qe-${e}`,t,u,T,w.duration).catch(()=>{});try{await xu(e,T,w.duration,u)}catch{}}return{success:!0,data:S}}catch(p){let g=E(p),f=_e(p);return f||oo(m?.patternHints,!1,e,0),{success:!1,error:`Failed to ${t.replace(/-/g," ")}: ${g}`,...f?{data:{callerError:!0}}:{}}}}}var _n=class{taskMetrics=[];agentMetrics=new Map;resourceSnapshots=[];workerLoads=new Map;activeTasks=new Map;lastCpuUsage=null;snapshotInterval=null;initialized=!1;initialize(){this.initialized||(this.initialized=!0,this.lastCpuUsage=process.cpuUsage(),this.snapshotInterval=setInterval(()=>{this.takeResourceSnapshot()},1e3),this.snapshotInterval.unref&&this.snapshotInterval.unref())}shutdown(){this.snapshotInterval&&(clearInterval(this.snapshotInterval),this.snapshotInterval=null),this.initialized=!1}startTask(e,t){this.ensureInitialized();let n={taskId:e,agentId:t,startTime:process.hrtime(),success:!1,retries:0};this.activeTasks.set(e,n),this.updateWorkerLoad(t,1,0)}recordRetry(e){let t=this.activeTasks.get(e);t&&t.retries++}completeTask(e,t){let n=this.activeTasks.get(e);if(!n)return 0;n.endTime=process.hrtime(),n.success=t;let r=process.hrtime(n.startTime);return n.durationMs=r[0]*1e3+r[1]/1e6,this.updateAgentMetrics(n),this.updateWorkerLoad(n.agentId,-1,1),this.taskMetrics.push(n),this.taskMetrics.length>100&&this.taskMetrics.shift(),this.activeTasks.delete(e),n.durationMs}getCpuUsagePercent(){if(this.ensureInitialized(),!this.lastCpuUsage)return this.lastCpuUsage=process.cpuUsage(),0;let e=process.cpuUsage(this.lastCpuUsage);this.lastCpuUsage=process.cpuUsage();let t=e.user+e.system,r=1e3*1e3,i=t/r*100;return Math.min(100,Math.max(0,i))}getMemoryUsagePercent(){let e=process.memoryUsage(),t=e.heapUsed/e.heapTotal*100;return Math.min(100,Math.max(0,t))}getResourceStats(e){return{cpu:this.getCpuUsagePercent(),memory:this.getMemoryUsagePercent()}}getAgentTaskStats(e){let t=this.agentMetrics.get(e);if(!t||t.taskCount===0)return{tasksCompleted:0,averageTime:0,successRate:1};let n=t.tasksCompleted+t.tasksFailed,r=n>0?t.tasksCompleted/n:1,i=t.taskCount>0?t.totalDurationMs/t.taskCount:0;return{tasksCompleted:t.tasksCompleted,averageTime:Math.round(i),successRate:Math.min(1,Math.max(0,r))}}getWorkerEfficiency(){if(this.taskMetrics.length===0)return .85;let t=this.taskMetrics.filter(a=>a.success).length/this.taskMetrics.length,r=this.taskMetrics.reduce((a,c)=>a+c.retries,0)/this.taskMetrics.length,i=Math.min(.2,r*.1),s=t*(1-i);return Math.min(1,Math.max(0,s))}getLoadBalanceScore(){if(this.workerLoads.size===0)return .9;let e=Array.from(this.workerLoads.values()).map(a=>a.completedTaskCount);if(e.length<=1)return 1;let t=e.reduce((a,c)=>a+c,0)/e.length;if(t===0)return 1;let n=e.reduce((a,c)=>a+Math.pow(c-t,2),0)/e.length,s=1/(1+Math.sqrt(n)/t);return Math.min(1,Math.max(0,s))}getRetryStats(){let e=0,t=0,n=0;for(let r of this.agentMetrics.values())e+=r.totalRetries,t+=r.successfulRetries,n+=r.maxRetriesReached;return{totalRetries:e,successfulRetries:t,maxRetriesReached:n}}getAverageExecutionTime(){if(this.taskMetrics.length===0)return 0;let e=this.taskMetrics.reduce((t,n)=>t+(n.durationMs||0),0);return Math.round(e/this.taskMetrics.length)}getWorkersUsed(){return this.workerLoads.size}getTestDurations(e){let t=[];if(this.taskMetrics.length===0){for(let r=0;r<e;r++)t.push(100+r*10);return t}let n=this.taskMetrics.map(r=>r.durationMs||200).sort((r,i)=>r-i);for(let r=0;r<e;r++){let i=r%n.length;t.push(Math.round(n[i]))}return t}recordSuccessfulRetry(e){let t=this.agentMetrics.get(e);t&&t.successfulRetries++}recordMaxRetriesReached(e){let t=this.agentMetrics.get(e);t&&t.maxRetriesReached++}reset(){this.taskMetrics=[],this.agentMetrics.clear(),this.resourceSnapshots=[],this.workerLoads.clear(),this.activeTasks.clear(),this.lastCpuUsage=null}ensureInitialized(){this.initialized||this.initialize()}updateAgentMetrics(e){let t=this.agentMetrics.get(e.agentId);t||(t={agentId:e.agentId,tasksCompleted:0,tasksFailed:0,totalRetries:0,successfulRetries:0,maxRetriesReached:0,totalDurationMs:0,taskCount:0},this.agentMetrics.set(e.agentId,t)),e.success?(t.tasksCompleted++,e.retries>0&&t.successfulRetries++):t.tasksFailed++,t.totalRetries+=e.retries,t.totalDurationMs+=e.durationMs||0,t.taskCount++}updateWorkerLoad(e,t,n){let r=this.workerLoads.get(e);r||(r={workerId:e,activeTaskCount:0,completedTaskCount:0,lastActivityTime:Date.now()},this.workerLoads.set(e,r)),r.activeTaskCount=Math.max(0,r.activeTaskCount+t),r.completedTaskCount+=n,r.lastActivityTime=Date.now()}takeResourceSnapshot(){let e=process.memoryUsage(),t=process.cpuUsage(),n={timestamp:Date.now(),cpuUser:t.user,cpuSystem:t.system,memoryHeapUsed:e.heapUsed,memoryHeapTotal:e.heapTotal,memoryExternal:e.external,memoryRss:e.rss};this.resourceSnapshots.push(n),this.resourceSnapshots.length>60&&this.resourceSnapshots.shift()}},Ae=new _n;k();bc();var mi="^(?:UNKNOWN|[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,255})$",pi="(?:^|[._:/@+\\-])(?:(?:[sS][kK]|[rR][kK]|[gG][hH][pPoOuUsSrR]|[gG][iI][tT][hH][uU][bB]_[pP][aA][tT]|[xX][oO][xX][bBaApPrRsS]|[nN][pP][mM]|[gG][lL][pP][aA][tT]|[pP][aA][tT])(?:[-_][A-Za-z0-9_-]*|(?=$|[.:/@+\\-]))|(?:[aA][kK][iI][aA]|[aA][sS][iI][aA]|[aA][iI][zZ][aA])[A-Za-z0-9]*)",gi="(?:^|[^A-Za-z0-9_-])(?:eyJ[A-Za-z0-9_-]*|e30|ew[A-Za-z0-9_-]*)\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+(?:$|[^A-Za-z0-9_-])",fi="(?:^|[._:/@+\\-])[A-Za-z0-9]{32,}(?:$|[._:/@+\\-])",hi="(?:(?:^|[.:@\\-])[A-Za-z0-9+/]{32,}={0,2}(?:$|[.:@\\-])|(?:^|[.:/@+\\-])[A-Za-z0-9_-]{48,}(?:$|[.:/@+\\-]))",yi="^\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d{1,9})?Z$",zy=new RegExp(mi),Uy=new RegExp(pi),By=new RegExp(gi),Hy=new RegExp(fi),Vy=new RegExp(hi),Qy=new RegExp(yi);function _u(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function Ou(o){return Array.isArray(o)&&o.every(e=>typeof e=="string")}function Nu(o){return typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1}function yo(o){let e=[];return _u(o)?(o.contract!=="risk-decision@1"&&e.push('contract must be "risk-decision@1"'),["approve","block","escalate"].includes(o.decision)||e.push("decision must be approve|block|escalate"),Ou(o.riskFactors)||e.push("riskFactors must be string[]"),Nu(o.confidence)||e.push("confidence must be a number in [0,1]"),(typeof o.rationale!="string"||o.rationale.length===0)&&e.push("rationale must be a non-empty string"),{valid:e.length===0,errors:e}):{valid:!1,errors:["not an object"]}}var Fu=.7;function vo(o){let{passed:e,qualityScore:t,recommendations:n=[],unmeasured:r=[],failedMetrics:i=[],gateEvaluated:s}=o,a=s===!1?" (no quality gate was evaluated)":"",c=typeof t=="number"?` with score ${t}`:"";if(i.length>0){let m=r.length>0?`; also unmeasured: ${r.join(", ")}`:"";return{contract:"risk-decision@1",decision:"block",riskFactors:[`failed: ${i.join(", ")}`,...r.length>0?[`unmeasured: ${r.join(", ")}`]:[],...n].slice(0,10),confidence:.9,rationale:`Measured ${i.join(", ")} failed its threshold${m}${a}`}}if(r.length>0){let m=typeof o.evidenceConfidence=="number"&&Number.isFinite(o.evidenceConfidence)?Math.min(1,Math.max(0,o.evidenceConfidence)):0;return{contract:"risk-decision@1",decision:"escalate",riskFactors:[`unmeasured: ${r.join(", ")}`,...n].slice(0,10),confidence:Math.round(.5*m*100)/100,rationale:`Insufficient evidence: ${r.join(", ")} not measured${a} \u2014 measure the missing metrics or run the measured quality gate before deciding`}}let l=e===!0?"approve":e===!1?"block":"escalate",u=s===!1?"Static analysis":"Quality gate",d=l==="escalate"?.5:l==="approve"&&s===!1?Fu:.9;return{contract:"risk-decision@1",decision:l,riskFactors:n.slice(0,10),confidence:d,rationale:l==="escalate"?"Quality gate outcome indeterminate \u2014 manual review required":`${u} ${e?"passed":"failed"}${c}${a}`}}var Lu={type:"number",minimum:0,maximum:1},ho={type:"array",items:{type:"string"}};function We(o){return{type:"string",pattern:mi,allOf:[{not:{pattern:pi}},{not:{pattern:gi}},{not:{pattern:o==="provider"||o==="requestedModel"||o==="resolvedModel"?fi:hi}}]}}var Ke={type:"string",pattern:"^(?:UNKNOWN|sha256:[a-f0-9]{64})$"},ee={type:"string",pattern:"^sha256:[a-f0-9]{64}$"};var Jy={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://agentic-qe.dev/schemas/finding-verdict.schema.json",title:"FindingVerdict",type:"object",required:["contract","id","title","severity","confidence","evidence","verdict","refutations"],additionalProperties:!0,properties:{contract:{const:"finding-verdict@1"},id:{type:"string",minLength:1},title:{type:"string",minLength:1},file:{type:"string"},severity:{enum:["critical","high","medium","low","info"]},confidence:Lu,evidence:ho,verdict:{enum:["upheld","refuted","uncertain"]},refutations:ho,measurementReceipts:{type:"array",items:{type:"object",required:["contract","provider","requestedModel","resolvedModel","endpointClass","snapshotIdentity","semantics","fingerprint","requestHash","promptHash","configHash","parserSchemaHash","outputHash","parsedVoteHash","temperature","topP","seed","deterministic","cacheStatus","retryCount","timestamp","windowId","latencyMs","requestId"],additionalProperties:!1,properties:{contract:{const:"judge-measurement@1"},provider:We("provider"),requestedModel:We("requestedModel"),resolvedModel:We("resolvedModel"),endpointClass:{enum:["shared","dedicated","local","UNKNOWN"]},snapshotIdentity:{enum:["L0_UNKNOWN","L1_NAMED","L2_CONTENT_BOUND"]},semantics:{enum:["verified","provider-asserted","UNKNOWN"]},fingerprint:We("fingerprint"),requestHash:Ke,promptHash:Ke,configHash:Ke,parserSchemaHash:Ke,outputHash:Ke,parsedVoteHash:Ke,temperature:{type:["number","null"],minimum:0},topP:{type:["number","null"],minimum:0,maximum:1},seed:{type:["integer","null"],minimum:Number.MIN_SAFE_INTEGER,maximum:Number.MAX_SAFE_INTEGER},deterministic:{type:["boolean","null"]},cacheStatus:{enum:["hit","miss","bypass","UNKNOWN"]},retryCount:{type:"integer",minimum:0,maximum:Number.MAX_SAFE_INTEGER},timestamp:{anyOf:[{const:"UNKNOWN"},{type:"string",pattern:yi,format:"date-time"}]},windowId:We("windowId"),latencyMs:{type:["number","null"],minimum:0},requestId:We("requestId")},allOf:[{if:{properties:{snapshotIdentity:{const:"L2_CONTENT_BOUND"}}},then:{properties:{fingerprint:{not:{const:"UNKNOWN"}},requestHash:ee,promptHash:ee,configHash:ee,parserSchemaHash:ee,outputHash:ee,parsedVoteHash:ee}}},{if:{properties:{snapshotIdentity:{const:"L1_NAMED"}}},then:{properties:{resolvedModel:{not:{const:"UNKNOWN"}}}}},{if:{properties:{semantics:{const:"verified"}}},then:{properties:{snapshotIdentity:{const:"L2_CONTENT_BOUND"},fingerprint:{not:{const:"UNKNOWN"}},requestHash:ee,promptHash:ee,configHash:ee,parserSchemaHash:ee,outputHash:ee,parsedVoteHash:ee}}},{if:{properties:{semantics:{enum:["verified","provider-asserted"]}}},then:{properties:{snapshotIdentity:{not:{const:"L0_UNKNOWN"}},fingerprint:{not:{const:"UNKNOWN"}}}}}]}}}};var bo=Object.keys(Qt);function qu(o){if(!o)return"typescript";let e=o.toLowerCase().trim(),t={ts:"typescript",js:"javascript",py:"python","c#":"csharp","c-sharp":"csharp",cs:"csharp",golang:"go",rs:"rust",kt:"kotlin"};return t[e]?t[e]:bo.includes(e)?e:null}var Co={domain:"test-generation",taskType:"generate-tests",priority:"p1",defaultTimeout:12e4,buildTaskDescription:o=>`Generate ${o.testType||"unit"} tests for ${o.language||"typescript"} code`,includeCodeContext:o=>o.sourceCode,mapToPayload:(o,e)=>{let t=qu(o.language);if(t===null)throw new Error(`Unsupported language '${o.language}'. Supported languages: ${bo.join(", ")}. Open a feature request for additional language support.`);let n;if(o.framework){n=o.framework;let i=is[n];if(i&&i!==t){let s=a=>a==="javascript"||a==="typescript";if(!(s(i)&&s(t)))throw new Error(`Framework '${n}' targets ${i}, but language was '${t}'. Either pick a matching framework or omit \`framework\` to use the default (${Qt[t]}).`)}}else n=Qt[t];let r=Vt(o.behaviorExamples);return{sourceCode:o.sourceCode,behaviorExamples:r,filePath:o.filePath,language:t,framework:n,testType:o.testType||"unit",coverageGoal:o.coverageGoal||80,aiEnhancement:o.aiEnhancement!==!1,detectAntiPatterns:o.detectAntiPatterns||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,n,r)=>{let i=r?.sourceCode||"",s=r?.language||"typescript",a=r?.testType||"unit",c=e.testsGenerated||6,l=lo(i),u=r?.aiEnhancement!==!1?uo(l,a):{recommendations:[],estimatedTime:"0 minutes",confidence:0},d=r?.detectAntiPatterns?po(i,s):[],m=Dn("test-generator"),p=e.tests,g=Array.isArray(p)&&p.length>0&&p[0].testCode,f=e.llmEnhanced===!0,h=g?p.map((v,y)=>({id:Ve(),name:v.name||`test_${y}`,type:v.type||a,parameters:[],assertions:v.testCode?$u(v.testCode):[`test assertion ${y}`],expectedResult:null,estimatedDuration:v.type==="integration"?2e3:1e3,aiGenerated:f,testCode:v.testCode,generationMode:v.generationMode,generationLimits:v.generationLimits,sourceFile:v.sourceFile,testFile:v.testFile||v.file})):mo(i,a,s,c);return{tests:h,antiPatterns:d,suggestions:d.map(v=>`Fix: ${v.type} - ${v.suggestion}`),aiInsights:u,coverage:{predicted:e.coverageEstimate??null,confidence:e.coverageEstimate==null?0:f?.9:0,achievable:e.coverageEstimate==null?null:!0},properties:h.filter(v=>v.type==="property").map(v=>({name:v.name,invariant:"output_matches_expectation"})),language:s,complexity:l,learning:m,taskId:o,status:"completed",testsGenerated:h.length,coverageEstimate:e.coverageEstimate??null,patternsUsed:e.patternsUsed||["assertion-patterns","mock-generation","edge-case-detection"],duration:t,...In(r?.saveResults!==!1,n),llmEnhanced:f,...e.generationMode?{generationMode:e.generationMode}:{},...e.note?{note:e.note}:{}}}},So={domain:"test-execution",taskType:"execute-tests",priority:"p1",defaultTimeout:3e5,buildTaskDescription:o=>`Execute ${o.testFiles?.length||0} test files with ${o.parallel!==!1?"parallel":"sequential"} execution`,mapToPayload:(o,e)=>({testFiles:o.testFiles||[],testSuites:o.testSuites||[],parallel:o.parallel!==!1,parallelism:o.parallelism||4,retryCount:o.retryCount||3,timeout:o.timeout||6e4,collectCoverage:o.collectCoverage||!1,reportFormat:o.reportFormat||"json",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:o=>o.timeout||3e5,mapToResult:(o,e,t,n,r)=>{let i=e.total||0,s=e.passed||0,a=e.failed||0,c=typeof e.coverage=="number"&&Number.isFinite(e.coverage)?e.coverage:null,l=r?.parallelism||4,u=Ae.getRetryStats(),d=Ae.getWorkersUsed(),m={workersUsed:d>0?d:Math.min(l,i||1),efficiency:Ae.getWorkerEfficiency(),loadBalance:Ae.getLoadBalanceScore(),avgExecutionTime:t/Math.max(i,1)},p={totalRetries:u.totalRetries,successfulRetries:u.successfulRetries,maxRetriesReached:u.maxRetriesReached},g=Dn("test-executor");return{workerStats:m,retryStats:p,results:(()=>{let f=Ae.getTestDurations(i);return Array.from({length:i},(h,v)=>({id:Ve(),name:`test_case_${v}`,status:v<s?"passed":"failed",duration:f[v]||200,retries:0}))})(),summary:{totalTests:i,passRate:i>0?s/i*100:0,avgDuration:t/Math.max(i,1),parallelEfficiency:m.efficiency},learning:g,taskId:o,status:"completed",total:i,passed:s,failed:a,duration:t,coverage:c,savedFiles:n}}},To={domain:"coverage-analysis",taskType:"analyze-coverage",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Analyze coverage for ${o.target||"project"} with gap detection`,mapToPayload:(o,e)=>({target:o.target||".",includeRisk:o.includeRisk||!1,detectGaps:o.detectGaps!==!1,mlPowered:o.mlPowered||!1,prioritization:o.prioritization||"complexity",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>{let r=e.summary,i=r?.files??e.totalFiles??0,s=e.gaps||[],a=e.branchDataCollected===!0,c=e.functionDataCollected===!0,l=a?r?.branch??e.branchCoverage??null:null,u=c?r?.function??e.functionCoverage??null:null,d=e.estimated===!0,m=e.measured===!0,g=r?.line??e.lineCoverage??null,f=r?.statement??e.statementCoverage,h=f===void 0?g:f,v=Dn("coverage-analyzer"),y=s.map((w,T)=>{let S=w;return S?.file?{id:`gap-${Date.now()}-${T}`,file:S.file,line:S.lines?.[0]||0,uncoveredLines:S.lines||[],type:S.type||"uncovered-line",severity:S.severity||"medium",reason:S.reason||"Missing test case",priority:S.priority||"medium",suggestion:S.suggestedTest||"Add test coverage",suggestedTest:S.suggestedTest||"Add test coverage",riskScore:S.riskScore||.5,confidence:S.confidence??(m?.7:.2),estimated:S.estimated===!0||d}:null}).filter(w=>w!==null),C=e.coverageByFile;return{coverageByFile:C?C.map(w=>({file:w.file,lineCoverage:w.lineCoverage||0,branchCoverage:w.branchCoverage??null,functionCoverage:w.functionCoverage??null})):[],gapAnalysis:{totalGaps:y.length,highPriority:y.filter(w=>w.priority==="high").length,gaps:y},trends:{lineCoverageTrend:i>0?"stable":"no-data",branchCoverageTrend:i>0?"stable":"no-data",weeklyChange:0},aiInsights:i>0?{recommendations:d?["ESTIMATED RESULT \u2014 no instrumentation ran. The figures below are a static guess from source shape, not measured coverage. Do not act on individual gaps without running real instrumentation first.",...e.recommendations||[]]:e.recommendations||["Run tests with coverage enabled to get accurate metrics"],riskAssessment:d||!m||g===null?"unknown":g<70?"high":g<85?"medium":"low",confidence:d?.2:m?.88:0}:{recommendations:["No coverage data found. Run tests with coverage first (e.g., npm test -- --coverage, or pytest --cov)"],riskAssessment:"unknown",confidence:0},learning:v,taskId:o,status:"completed",lineCoverage:g,branchCoverage:l,functionCoverage:u,statementCoverage:h,totalFiles:i,gaps:y,duration:t,savedFiles:n,estimated:d,measured:m,coverageMethod:e.coverageMethod??"unknown",branchDataCollected:a,functionDataCollected:c,...e.runStatus==="passed"||e.runStatus==="failed"?{runStatus:e.runStatus}:{},...e.unmeasured===!0?{unmeasured:!0}:{},...e.warning?{warning:e.warning}:{}}}},Eo={domain:"quality-assessment",taskType:"assess-quality",priority:"p0",defaultTimeout:18e4,buildTaskDescription:o=>`Assess quality with ${o.runGate?"quality gate":"metrics analysis"}`,mapToPayload:(o,e)=>{if(o.runGate!==void 0&&typeof o.runGate!="boolean")throw new Error("runGate must be a boolean.");let t=o.metrics===void 0?["coverage","complexity","maintainability"]:Xt(o.metrics);if(o.target!==void 0&&(typeof o.target!="string"||o.target.trim()===""))throw new ae("target must be a non-empty string path.");if(o.sourceFiles!==void 0&&(!Array.isArray(o.sourceFiles)||o.sourceFiles.length===0||o.sourceFiles.some(n=>typeof n!="string"||n.trim()==="")))throw new ae("sourceFiles must be a non-empty array of file paths.");return{runGate:o.runGate??!1,...o.target!==void 0?{target:o.target}:{},...o.sourceFiles!==void 0?{sourceFiles:o.sourceFiles}:{},threshold:o.threshold||80,thresholdSource:o.threshold===void 0?"default":"request",metrics:t,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,n)=>{let r=Array.isArray(e.unmeasured)?e.unmeasured.filter(g=>typeof g=="string"):void 0,i=(r?.length??0)>0||e.evidenceStatus===Le,s=typeof e.gateEvaluated=="boolean"?e.gateEvaluated:void 0,a=typeof e.confidence=="number"?e.confidence:void 0,c=Array.isArray(e.measuredFailures)?e.measuredFailures:void 0,l=(c??[]).map(g=>g.metric),u=e.unmeasuredReasons&&typeof e.unmeasuredReasons=="object"&&Object.values(e.unmeasuredReasons).every(g=>typeof g=="string")?e.unmeasuredReasons:void 0,d=typeof e.qualityScore=="number"&&e.qualityScore>=0?e.qualityScore:void 0,m=!i&&l.length===0&&e.passed===!0,p=vo({passed:i||l.length>0?!1:typeof e.passed=="boolean"?e.passed:void 0,qualityScore:d,recommendations:e.recommendations||[],unmeasured:i?r?.length?r:["unknown"]:[],failedMetrics:l,evidenceConfidence:a,gateEvaluated:s});return{taskId:o,status:i?Le:"completed",...typeof e.qualityScore=="number"?{qualityScore:e.qualityScore}:{},...Array.isArray(e.checks)?{checks:e.checks}:{},passed:m,metrics:e.metrics||{},recommendations:e.recommendations||[],...e.evidenceStatus==="measured"||i?{evidenceStatus:i?Le:"measured"}:{},...r?{unmeasured:r}:{},...u?{unmeasuredReasons:u}:{},...Array.isArray(e.partialMetrics)?{partialMetrics:e.partialMetrics}:{},...Array.isArray(e.excludedFiles)?{excludedFiles:e.excludedFiles}:{},...typeof e.excludedCount=="number"?{excludedCount:e.excludedCount}:{},...typeof e.scope=="string"?{scope:e.scope}:{},...Array.isArray(e.scoreBasis)&&e.scoreBasis.every(g=>typeof g=="string")?{scoreBasis:e.scoreBasis}:{},...c?{measuredFailures:c}:{},...s!==void 0?{gateEvaluated:s}:{},...a!==void 0?{confidence:a}:{},...typeof e.note=="string"?{note:e.note}:{},duration:t,savedFiles:n,...yo(p).valid?{riskDecision:p}:{}}}},wo={domain:"security-compliance",taskType:"scan-security",priority:"p0",defaultTimeout:6e5,buildTaskDescription:o=>{let e=[];return o.sast!==!1&&e.push("SAST"),o.dast&&e.push("DAST"),o.dependencies&&e.push("dependency advisories"),`Security scan (${e.join(", ")}) for ${o.target||"project"}`},mapToPayload:(o,e)=>{for(let t of["sast","dast","dependencies"])if(o[t]!==void 0&&typeof o[t]!="boolean")throw new Error(`${t} must be a boolean`);return{sast:o.sast!==!1,dast:o.dast||!1,dependencies:o.dependencies===!0,compliance:o.compliance||[],target:o.target||".",targetUrl:o.targetUrl,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,n)=>({taskId:o,status:e.evidence?.completeness==="complete"?"completed":e.evidence?.completeness==="partial"?"partial":e.evidence?"unavailable":"unverified",vulnerabilities:e.vulnerabilities||0,critical:e.critical||0,high:e.high||0,medium:e.medium||0,low:e.low||0,informational:e.informational||0,topVulnerabilities:e.topVulnerabilities||[],findings:e.findings,recommendations:e.recommendations||[],evidence:e.evidence,limitations:e.limitations||["Execution receipts unavailable; scan completeness is unverified."],...e.evidence?{filesScanned:e.filesScanned,jstsFilesScanned:e.jstsFilesScanned,otherFilesScanned:e.otherFilesScanned,coverage:e.coverage}:{},deepAnalysisPerformed:!!(e.evidence&&e.deepAnalysisPerformed===!0),analysisDepth:e.analysisDepth,scanTypes:e.scanTypes,...e.dependencyScan?{dependencyScan:e.dependencyScan}:{},note:e.note,duration:t,savedFiles:n})},Ro={domain:"contract-testing",taskType:"validate-contracts",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Validate API contract at ${o.contractPath}`,mapToPayload:(o,e)=>({contractPath:o.contractPath,providerUrl:o.providerUrl,consumerName:o.consumerName,checkBreakingChanges:o.checkBreakingChanges!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",valid:e.valid||!1,breakingChanges:e.breakingChanges||[],warnings:e.warnings||[],duration:t,savedFiles:n})},Po={domain:"visual-accessibility",taskType:"test-accessibility",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Test accessibility for ${o.url} against ${o.standard||"WCAG 2.1 AA"} standard`,mapToPayload:(o,e)=>({url:o.url,standard:o.standard||"wcag21-aa",includeScreenReader:o.includeScreenReader||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",passed:e.passed||!1,score:e.score||0,violations:e.violations||[],warnings:e.warnings||[],duration:t,savedFiles:n})},xo={domain:"chaos-resilience",taskType:"run-chaos",priority:"p2",defaultTimeout:9e4,buildTaskDescription:o=>`Run chaos test with ${o.faultType||"latency"} fault injection on ${o.target}`,mapToPayload:(o,e)=>({faultType:o.faultType||"latency",target:o.target,duration:o.duration||3e4,intensity:o.intensity||50,dryRun:o.dryRun!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:o=>(o.duration||3e4)+6e4,mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",faultType:e.faultType||"latency",resilience:e.resilience||{recovered:!1,recoveryTime:0,dataLoss:!1},duration:t,savedFiles:n})},Ao={domain:"defect-intelligence",taskType:"predict-defects",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Predict defects in ${o.target||"codebase"} with ${o.lookback||30} day lookback`,mapToPayload:(o,e)=>({target:o.target||".",lookback:o.lookback||30,minConfidence:o.minConfidence||.7,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",predictedDefects:e.predictedDefects||[],riskScore:e.riskScore||0,recommendations:e.recommendations||[],duration:t,savedFiles:n})},ko={domain:"requirements-validation",taskType:"validate-requirements",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Validate requirements${o.generateBDD?" and generate BDD scenarios":""}`,mapToPayload:(o,e)=>({requirementsPath:o.requirementsPath,testPath:o.testPath,generateBDD:o.generateBDD||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",requirementsAnalyzed:e.requirementsAnalyzed||0,testable:e.testable||0,coverage:e.coverage||0,bddScenarios:e.bddScenarios||[],duration:t,savedFiles:n})},Mo={domain:"code-intelligence",taskType:"index-code",priority:"p2",defaultTimeout:3e5,buildTaskDescription:o=>`Index code in ${o.target||"codebase"}${o.incremental?" incrementally":""}`,mapToPayload:(o,e)=>({target:o.target||".",incremental:o.incremental||!1,gitSince:o.gitSince,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",filesIndexed:e.filesIndexed||0,symbolsExtracted:e.symbolsExtracted||0,relationsFound:e.relationsFound||0,...e.projectMetrics?{projectMetrics:e.projectMetrics}:{},duration:t,savedFiles:n})};function $u(o){let e=[],t=o.split(`
449
+ `);return o.includes("eval(")&&t.push({type:"dangerous-eval",line:n.findIndex(r=>r.includes("eval("))+1,severity:"critical",suggestion:"Replace eval() with safer alternatives"}),o.includes("var ")&&(e==="javascript"||e==="typescript")&&t.push({type:"var-usage",line:n.findIndex(r=>r.includes("var "))+1,severity:"low",suggestion:"Use const or let instead of var"}),o.includes("any")&&e==="typescript"&&t.push({type:"any-type",line:n.findIndex(r=>r.includes("any"))+1,severity:"medium",suggestion:"Replace any with specific types"}),t}var bt=null,di=null,de=null,Au=Number(process.env.AQE_ROUTE_TIMEOUT_MS)||5e3;function ku(o,e,t){return new Promise(n=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(t))},e);typeof i.unref=="function"&&i.unref(),o.then(s=>{r||(r=!0,clearTimeout(i),n(s))},()=>{r||(r=!0,clearTimeout(i),n(t))})})}function Mu(){if(!bt){let{kernel:o}=Ct();if(!o)throw new Error("Kernel not initialized");bt=Ya(o);let e=bt;di=io().then(t=>(e.setQualityFeedbackLoop(t),t)).catch(t=>(console.warn("[HandlerFactory] Failed to initialize QualityFeedbackLoop:",t),null))}return bt}function go(){if(bt=null,de){let o=de;de=null,o.dispose().catch(()=>{})}}async function fo(){if(de)return de;try{let{kernel:o}=Ct();if(!o)return null;let{createAQELearningEngine:e}=await import("./aqe-learning-engine-AUAL6UBL.js"),t=o.memory,n=e(t,{projectRoot:process.cwd(),enableClaudeFlow:!1});return await n.initialize(),de=n,de}catch(o){return console.debug("[HandlerFactory] Learning engine init failed:",E(o)),null}}async function Iu(o,e){try{let t=await fo();if(!t)return[];let n=e,r=await t.searchPatterns(o,{limit:5,minConfidence:.4,domain:n,useVectorSearch:!0});return!r.success||r.value.length===0?[]:r.value.filter(i=>i.similarity>=.4).map(i=>({name:i.pattern.name,description:i.pattern.description,similarity:i.similarity,confidence:i.pattern.confidence,canReuse:i.canReuse,patternId:i.pattern.id}))}catch(t){return console.debug("[HandlerFactory] Pattern search failed:",E(t)),[]}}async function Du(o,e,t){try{let n=await Iu(o,e);return n.length>0&&console.debug(`[HandlerFactory] Found ${n.length} relevant patterns for ${e}`),await(await Tn()).routeTask({task:o,domain:e,codeContext:t,agentType:`qe-${e}`,enablePatternSearch:!0,patternHints:n.length>0?n:void 0})}catch(n){return console.error(`[HandlerFactory] Routing failed for ${e}: ${n}`),null}}async function oo(o,e,t,n){if(!(!o||o.length===0)&&de)try{for(let r of o)r.patternId&&await de.recordOutcome({patternId:r.patternId,success:e,metrics:{executionTimeMs:n},feedback:`Domain handler ${t} execution ${e?"succeeded":"failed"}`})}catch{}}function Z(o){let{domain:e,taskType:t,priority:n="p1",defaultTimeout:r=18e4,buildTaskDescription:i,mapToPayload:s,mapToResult:a,calculateTimeout:c,includeCodeContext:l}=o;return async u=>{if(!Qe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:d}=Ct(),m=null;try{let p=Za(u),g=i(u),f=l?.(u);m=await ku(Du(g,e,f),Au,null);let h=s(u,m);p||(h.saveResults=!1);let v=c?.(u)??r,y=await d.submitTask({type:t,priority:n,targetDomains:[e],payload:h,timeout:v});if(!y.success)return{success:!1,error:y.error.message};let C=Mu(),b=d.getTaskStatus(y.value);if(!b)return{success:!1,error:"Task not found after submission"};let w=await C.execute(b.task);if(!w.success)return{success:!1,error:w.error||"Task execution failed",...w.errorDetails?{data:w.errorDetails}:{}};let T=w.data,S=a(y.value,T,w.duration,w.savedFiles,u);if(Object.assign(S,In(p,w.savedFiles)),nn(e,T)&&nn("",S)){oo(m?.patternHints,!0,e,w.duration),wu(`qe-${e}`,t,u,T,w.duration).catch(()=>{});try{await xu(e,T,w.duration,u)}catch{}}return{success:!0,data:S}}catch(p){let g=E(p),f=_e(p);return f||oo(m?.patternHints,!1,e,0),{success:!1,error:`Failed to ${t.replace(/-/g," ")}: ${g}`,...f?{data:{callerError:!0}}:{}}}}}var _n=class{taskMetrics=[];agentMetrics=new Map;resourceSnapshots=[];workerLoads=new Map;activeTasks=new Map;lastCpuUsage=null;snapshotInterval=null;initialized=!1;initialize(){this.initialized||(this.initialized=!0,this.lastCpuUsage=process.cpuUsage(),this.snapshotInterval=setInterval(()=>{this.takeResourceSnapshot()},1e3),this.snapshotInterval.unref&&this.snapshotInterval.unref())}shutdown(){this.snapshotInterval&&(clearInterval(this.snapshotInterval),this.snapshotInterval=null),this.initialized=!1}startTask(e,t){this.ensureInitialized();let n={taskId:e,agentId:t,startTime:process.hrtime(),success:!1,retries:0};this.activeTasks.set(e,n),this.updateWorkerLoad(t,1,0)}recordRetry(e){let t=this.activeTasks.get(e);t&&t.retries++}completeTask(e,t){let n=this.activeTasks.get(e);if(!n)return 0;n.endTime=process.hrtime(),n.success=t;let r=process.hrtime(n.startTime);return n.durationMs=r[0]*1e3+r[1]/1e6,this.updateAgentMetrics(n),this.updateWorkerLoad(n.agentId,-1,1),this.taskMetrics.push(n),this.taskMetrics.length>100&&this.taskMetrics.shift(),this.activeTasks.delete(e),n.durationMs}getCpuUsagePercent(){if(this.ensureInitialized(),!this.lastCpuUsage)return this.lastCpuUsage=process.cpuUsage(),0;let e=process.cpuUsage(this.lastCpuUsage);this.lastCpuUsage=process.cpuUsage();let t=e.user+e.system,r=1e3*1e3,i=t/r*100;return Math.min(100,Math.max(0,i))}getMemoryUsagePercent(){let e=process.memoryUsage(),t=e.heapUsed/e.heapTotal*100;return Math.min(100,Math.max(0,t))}getResourceStats(e){return{cpu:this.getCpuUsagePercent(),memory:this.getMemoryUsagePercent()}}getAgentTaskStats(e){let t=this.agentMetrics.get(e);if(!t||t.taskCount===0)return{tasksCompleted:0,averageTime:0,successRate:1};let n=t.tasksCompleted+t.tasksFailed,r=n>0?t.tasksCompleted/n:1,i=t.taskCount>0?t.totalDurationMs/t.taskCount:0;return{tasksCompleted:t.tasksCompleted,averageTime:Math.round(i),successRate:Math.min(1,Math.max(0,r))}}getWorkerEfficiency(){if(this.taskMetrics.length===0)return .85;let t=this.taskMetrics.filter(a=>a.success).length/this.taskMetrics.length,r=this.taskMetrics.reduce((a,c)=>a+c.retries,0)/this.taskMetrics.length,i=Math.min(.2,r*.1),s=t*(1-i);return Math.min(1,Math.max(0,s))}getLoadBalanceScore(){if(this.workerLoads.size===0)return .9;let e=Array.from(this.workerLoads.values()).map(a=>a.completedTaskCount);if(e.length<=1)return 1;let t=e.reduce((a,c)=>a+c,0)/e.length;if(t===0)return 1;let n=e.reduce((a,c)=>a+Math.pow(c-t,2),0)/e.length,s=1/(1+Math.sqrt(n)/t);return Math.min(1,Math.max(0,s))}getRetryStats(){let e=0,t=0,n=0;for(let r of this.agentMetrics.values())e+=r.totalRetries,t+=r.successfulRetries,n+=r.maxRetriesReached;return{totalRetries:e,successfulRetries:t,maxRetriesReached:n}}getAverageExecutionTime(){if(this.taskMetrics.length===0)return 0;let e=this.taskMetrics.reduce((t,n)=>t+(n.durationMs||0),0);return Math.round(e/this.taskMetrics.length)}getWorkersUsed(){return this.workerLoads.size}getTestDurations(e){let t=[];if(this.taskMetrics.length===0){for(let r=0;r<e;r++)t.push(100+r*10);return t}let n=this.taskMetrics.map(r=>r.durationMs||200).sort((r,i)=>r-i);for(let r=0;r<e;r++){let i=r%n.length;t.push(Math.round(n[i]))}return t}recordSuccessfulRetry(e){let t=this.agentMetrics.get(e);t&&t.successfulRetries++}recordMaxRetriesReached(e){let t=this.agentMetrics.get(e);t&&t.maxRetriesReached++}reset(){this.taskMetrics=[],this.agentMetrics.clear(),this.resourceSnapshots=[],this.workerLoads.clear(),this.activeTasks.clear(),this.lastCpuUsage=null}ensureInitialized(){this.initialized||this.initialize()}updateAgentMetrics(e){let t=this.agentMetrics.get(e.agentId);t||(t={agentId:e.agentId,tasksCompleted:0,tasksFailed:0,totalRetries:0,successfulRetries:0,maxRetriesReached:0,totalDurationMs:0,taskCount:0},this.agentMetrics.set(e.agentId,t)),e.success?(t.tasksCompleted++,e.retries>0&&t.successfulRetries++):t.tasksFailed++,t.totalRetries+=e.retries,t.totalDurationMs+=e.durationMs||0,t.taskCount++}updateWorkerLoad(e,t,n){let r=this.workerLoads.get(e);r||(r={workerId:e,activeTaskCount:0,completedTaskCount:0,lastActivityTime:Date.now()},this.workerLoads.set(e,r)),r.activeTaskCount=Math.max(0,r.activeTaskCount+t),r.completedTaskCount+=n,r.lastActivityTime=Date.now()}takeResourceSnapshot(){let e=process.memoryUsage(),t=process.cpuUsage(),n={timestamp:Date.now(),cpuUser:t.user,cpuSystem:t.system,memoryHeapUsed:e.heapUsed,memoryHeapTotal:e.heapTotal,memoryExternal:e.external,memoryRss:e.rss};this.resourceSnapshots.push(n),this.resourceSnapshots.length>60&&this.resourceSnapshots.shift()}},Ae=new _n;k();bc();var mi="^(?:UNKNOWN|[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,255})$",pi="(?:^|[._:/@+\\-])(?:(?:[sS][kK]|[rR][kK]|[gG][hH][pPoOuUsSrR]|[gG][iI][tT][hH][uU][bB]_[pP][aA][tT]|[xX][oO][xX][bBaApPrRsS]|[nN][pP][mM]|[gG][lL][pP][aA][tT]|[pP][aA][tT])(?:[-_][A-Za-z0-9_-]*|(?=$|[.:/@+\\-]))|(?:[aA][kK][iI][aA]|[aA][sS][iI][aA]|[aA][iI][zZ][aA])[A-Za-z0-9]*)",gi="(?:^|[^A-Za-z0-9_-])(?:eyJ[A-Za-z0-9_-]*|e30|ew[A-Za-z0-9_-]*)\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+(?:$|[^A-Za-z0-9_-])",fi="(?:^|[._:/@+\\-])[A-Za-z0-9]{32,}(?:$|[._:/@+\\-])",hi="(?:(?:^|[.:@\\-])[A-Za-z0-9+/]{32,}={0,2}(?:$|[.:@\\-])|(?:^|[.:/@+\\-])[A-Za-z0-9_-]{48,}(?:$|[.:/@+\\-]))",yi="^\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d{1,9})?Z$",zy=new RegExp(mi),Uy=new RegExp(pi),By=new RegExp(gi),Hy=new RegExp(fi),Vy=new RegExp(hi),Qy=new RegExp(yi);function _u(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function Ou(o){return Array.isArray(o)&&o.every(e=>typeof e=="string")}function Nu(o){return typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1}function yo(o){let e=[];return _u(o)?(o.contract!=="risk-decision@1"&&e.push('contract must be "risk-decision@1"'),["approve","block","escalate"].includes(o.decision)||e.push("decision must be approve|block|escalate"),Ou(o.riskFactors)||e.push("riskFactors must be string[]"),Nu(o.confidence)||e.push("confidence must be a number in [0,1]"),(typeof o.rationale!="string"||o.rationale.length===0)&&e.push("rationale must be a non-empty string"),{valid:e.length===0,errors:e}):{valid:!1,errors:["not an object"]}}var Fu=.7;function vo(o){let{passed:e,qualityScore:t,recommendations:n=[],unmeasured:r=[],failedMetrics:i=[],gateEvaluated:s}=o,a=s===!1?" (no quality gate was evaluated)":"",c=typeof t=="number"?` with score ${t}`:"";if(i.length>0){let m=r.length>0?`; also unmeasured: ${r.join(", ")}`:"";return{contract:"risk-decision@1",decision:"block",riskFactors:[`failed: ${i.join(", ")}`,...r.length>0?[`unmeasured: ${r.join(", ")}`]:[],...n].slice(0,10),confidence:.9,rationale:`Measured ${i.join(", ")} failed its threshold${m}${a}`}}if(r.length>0){let m=typeof o.evidenceConfidence=="number"&&Number.isFinite(o.evidenceConfidence)?Math.min(1,Math.max(0,o.evidenceConfidence)):0;return{contract:"risk-decision@1",decision:"escalate",riskFactors:[`unmeasured: ${r.join(", ")}`,...n].slice(0,10),confidence:Math.round(.5*m*100)/100,rationale:`Insufficient evidence: ${r.join(", ")} not measured${a} \u2014 measure the missing metrics or run the measured quality gate before deciding`}}let l=e===!0?"approve":e===!1?"block":"escalate",u=s===!1?"Static analysis":"Quality gate",d=l==="escalate"?.5:l==="approve"&&s===!1?Fu:.9;return{contract:"risk-decision@1",decision:l,riskFactors:n.slice(0,10),confidence:d,rationale:l==="escalate"?"Quality gate outcome indeterminate \u2014 manual review required":`${u} ${e?"passed":"failed"}${c}${a}`}}var Lu={type:"number",minimum:0,maximum:1},ho={type:"array",items:{type:"string"}};function We(o){return{type:"string",pattern:mi,allOf:[{not:{pattern:pi}},{not:{pattern:gi}},{not:{pattern:o==="provider"||o==="requestedModel"||o==="resolvedModel"?fi:hi}}]}}var Ke={type:"string",pattern:"^(?:UNKNOWN|sha256:[a-f0-9]{64})$"},ee={type:"string",pattern:"^sha256:[a-f0-9]{64}$"};var Jy={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://agentic-qe.dev/schemas/finding-verdict.schema.json",title:"FindingVerdict",type:"object",required:["contract","id","title","severity","confidence","evidence","verdict","refutations"],additionalProperties:!0,properties:{contract:{const:"finding-verdict@1"},id:{type:"string",minLength:1},title:{type:"string",minLength:1},file:{type:"string"},severity:{enum:["critical","high","medium","low","info"]},confidence:Lu,evidence:ho,verdict:{enum:["upheld","refuted","uncertain"]},refutations:ho,measurementReceipts:{type:"array",items:{type:"object",required:["contract","provider","requestedModel","resolvedModel","endpointClass","snapshotIdentity","semantics","fingerprint","requestHash","promptHash","configHash","parserSchemaHash","outputHash","parsedVoteHash","temperature","topP","seed","deterministic","cacheStatus","retryCount","timestamp","windowId","latencyMs","requestId"],additionalProperties:!1,properties:{contract:{const:"judge-measurement@1"},provider:We("provider"),requestedModel:We("requestedModel"),resolvedModel:We("resolvedModel"),endpointClass:{enum:["shared","dedicated","local","UNKNOWN"]},snapshotIdentity:{enum:["L0_UNKNOWN","L1_NAMED","L2_CONTENT_BOUND"]},semantics:{enum:["verified","provider-asserted","UNKNOWN"]},fingerprint:We("fingerprint"),requestHash:Ke,promptHash:Ke,configHash:Ke,parserSchemaHash:Ke,outputHash:Ke,parsedVoteHash:Ke,temperature:{type:["number","null"],minimum:0},topP:{type:["number","null"],minimum:0,maximum:1},seed:{type:["integer","null"],minimum:Number.MIN_SAFE_INTEGER,maximum:Number.MAX_SAFE_INTEGER},deterministic:{type:["boolean","null"]},cacheStatus:{enum:["hit","miss","bypass","UNKNOWN"]},retryCount:{type:"integer",minimum:0,maximum:Number.MAX_SAFE_INTEGER},timestamp:{anyOf:[{const:"UNKNOWN"},{type:"string",pattern:yi,format:"date-time"}]},windowId:We("windowId"),latencyMs:{type:["number","null"],minimum:0},requestId:We("requestId")},allOf:[{if:{properties:{snapshotIdentity:{const:"L2_CONTENT_BOUND"}}},then:{properties:{fingerprint:{not:{const:"UNKNOWN"}},requestHash:ee,promptHash:ee,configHash:ee,parserSchemaHash:ee,outputHash:ee,parsedVoteHash:ee}}},{if:{properties:{snapshotIdentity:{const:"L1_NAMED"}}},then:{properties:{resolvedModel:{not:{const:"UNKNOWN"}}}}},{if:{properties:{semantics:{const:"verified"}}},then:{properties:{snapshotIdentity:{const:"L2_CONTENT_BOUND"},fingerprint:{not:{const:"UNKNOWN"}},requestHash:ee,promptHash:ee,configHash:ee,parserSchemaHash:ee,outputHash:ee,parsedVoteHash:ee}}},{if:{properties:{semantics:{enum:["verified","provider-asserted"]}}},then:{properties:{snapshotIdentity:{not:{const:"L0_UNKNOWN"}},fingerprint:{not:{const:"UNKNOWN"}}}}}]}}}};var bo=Object.keys(Qt);function qu(o){if(!o)return"typescript";let e=o.toLowerCase().trim(),t={ts:"typescript",js:"javascript",py:"python","c#":"csharp","c-sharp":"csharp",cs:"csharp",golang:"go",rs:"rust",kt:"kotlin"};return t[e]?t[e]:bo.includes(e)?e:null}var Co={domain:"test-generation",taskType:"generate-tests",priority:"p1",defaultTimeout:12e4,buildTaskDescription:o=>`Generate ${o.testType||"unit"} tests for ${o.language||"typescript"} code`,includeCodeContext:o=>o.sourceCode,mapToPayload:(o,e)=>{let t=qu(o.language);if(t===null)throw new Error(`Unsupported language '${o.language}'. Supported languages: ${bo.join(", ")}. Open a feature request for additional language support.`);let n;if(o.framework){n=o.framework;let i=is[n];if(i&&i!==t){let s=a=>a==="javascript"||a==="typescript";if(!(s(i)&&s(t)))throw new Error(`Framework '${n}' targets ${i}, but language was '${t}'. Either pick a matching framework or omit \`framework\` to use the default (${Qt[t]}).`)}}else n=Qt[t];let r=Vt(o.behaviorExamples);return{sourceCode:o.sourceCode,behaviorExamples:r,filePath:o.filePath,language:t,framework:n,testType:o.testType||"unit",coverageGoal:o.coverageGoal||80,aiEnhancement:o.aiEnhancement!==!1,detectAntiPatterns:o.detectAntiPatterns||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,n,r)=>{let i=r?.sourceCode||"",s=r?.language||"typescript",a=r?.testType||"unit",c=e.testsGenerated||6,l=lo(i),u=r?.aiEnhancement!==!1?uo(l,a):{recommendations:[],estimatedTime:"0 minutes",confidence:0},d=r?.detectAntiPatterns?po(i,s):[],m=Dn("test-generator"),p=e.tests,g=Array.isArray(p)&&p.length>0&&p[0].testCode,f=e.llmEnhanced===!0,h=g?p.map((v,y)=>({id:Ve(),name:v.name||`test_${y}`,type:v.type||a,parameters:[],assertions:v.testCode?$u(v.testCode):[`test assertion ${y}`],expectedResult:null,estimatedDuration:v.type==="integration"?2e3:1e3,aiGenerated:f,testCode:v.testCode,generationMode:v.generationMode,generationLimits:v.generationLimits,sourceFile:v.sourceFile,testFile:v.testFile||v.file})):mo(i,a,s,c);return{tests:h,antiPatterns:d,suggestions:d.map(v=>`Fix: ${v.type} - ${v.suggestion}`),aiInsights:u,coverage:{predicted:e.coverageEstimate??null,confidence:e.coverageEstimate==null?0:f?.9:0,achievable:e.coverageEstimate==null?null:!0},properties:h.filter(v=>v.type==="property").map(v=>({name:v.name,invariant:"output_matches_expectation"})),language:s,complexity:l,learning:m,taskId:o,status:"completed",testsGenerated:h.length,coverageEstimate:e.coverageEstimate??null,patternsUsed:e.patternsUsed||["assertion-patterns","mock-generation","edge-case-detection"],duration:t,...In(r?.saveResults!==!1,n),llmEnhanced:f,...e.generationMode?{generationMode:e.generationMode}:{},...e.note?{note:e.note}:{}}}},So={domain:"test-execution",taskType:"execute-tests",priority:"p1",defaultTimeout:3e5,buildTaskDescription:o=>`Execute ${o.testFiles?.length||0} test files with ${o.parallel!==!1?"parallel":"sequential"} execution`,mapToPayload:(o,e)=>({testFiles:o.testFiles||[],testSuites:o.testSuites||[],parallel:o.parallel!==!1,parallelism:o.parallelism||4,retryCount:o.retryCount||3,timeout:o.timeout||6e4,collectCoverage:o.collectCoverage||!1,reportFormat:o.reportFormat||"json",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:o=>o.timeout||3e5,mapToResult:(o,e,t,n,r)=>{let i=e.total||0,s=e.passed||0,a=e.failed||0,c=typeof e.coverage=="number"&&Number.isFinite(e.coverage)?e.coverage:null,l=r?.parallelism||4,u=Ae.getRetryStats(),d=Ae.getWorkersUsed(),m={workersUsed:d>0?d:Math.min(l,i||1),efficiency:Ae.getWorkerEfficiency(),loadBalance:Ae.getLoadBalanceScore(),avgExecutionTime:t/Math.max(i,1)},p={totalRetries:u.totalRetries,successfulRetries:u.successfulRetries,maxRetriesReached:u.maxRetriesReached},g=Dn("test-executor");return{workerStats:m,retryStats:p,results:(()=>{let f=Ae.getTestDurations(i);return Array.from({length:i},(h,v)=>({id:Ve(),name:`test_case_${v}`,status:v<s?"passed":"failed",duration:f[v]||200,retries:0}))})(),summary:{totalTests:i,passRate:i>0?s/i*100:0,avgDuration:t/Math.max(i,1),parallelEfficiency:m.efficiency},learning:g,taskId:o,status:"completed",total:i,passed:s,failed:a,duration:t,coverage:c,savedFiles:n}}},To={domain:"coverage-analysis",taskType:"analyze-coverage",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Analyze coverage for ${o.target||"project"} with gap detection`,mapToPayload:(o,e)=>({target:o.target||".",includeRisk:o.includeRisk||!1,detectGaps:o.detectGaps!==!1,mlPowered:o.mlPowered||!1,prioritization:o.prioritization||"complexity",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>{let r=e.summary,i=r?.files??e.totalFiles??0,s=e.gaps||[],a=e.branchDataCollected===!0,c=e.functionDataCollected===!0,l=a?r?.branch??e.branchCoverage??null:null,u=c?r?.function??e.functionCoverage??null:null,d=e.estimated===!0,m=e.measured===!0,g=r?.line??e.lineCoverage??null,f=r?.statement??e.statementCoverage,h=f===void 0?g:f,v=Dn("coverage-analyzer"),y=s.map((w,T)=>{let S=w;return S?.file?{id:`gap-${Date.now()}-${T}`,file:S.file,line:S.lines?.[0]||0,uncoveredLines:S.lines||[],type:S.type||"uncovered-line",severity:S.severity||"medium",reason:S.reason||"Missing test case",priority:S.priority||"medium",suggestion:S.suggestedTest||"Add test coverage",suggestedTest:S.suggestedTest||"Add test coverage",riskScore:S.riskScore||.5,confidence:S.confidence??(m?.7:.2),estimated:S.estimated===!0||d}:null}).filter(w=>w!==null),C=e.coverageByFile;return{coverageByFile:C?C.map(w=>({file:w.file,lineCoverage:w.lineCoverage||0,branchCoverage:w.branchCoverage??null,functionCoverage:w.functionCoverage??null})):[],gapAnalysis:{totalGaps:y.length,highPriority:y.filter(w=>w.priority==="high").length,gaps:y},trends:{lineCoverageTrend:i>0?"stable":"no-data",branchCoverageTrend:i>0?"stable":"no-data",weeklyChange:0},aiInsights:i>0?{recommendations:d?["ESTIMATED RESULT \u2014 no instrumentation ran. The figures below are a static guess from source shape, not measured coverage. Do not act on individual gaps without running real instrumentation first.",...e.recommendations||[]]:e.recommendations||["Run tests with coverage enabled to get accurate metrics"],riskAssessment:d||!m||g===null?"unknown":g<70?"high":g<85?"medium":"low",confidence:d?.2:m?.88:0}:{recommendations:["No coverage data found. Run tests with coverage first (e.g., npm test -- --coverage, or pytest --cov)"],riskAssessment:"unknown",confidence:0},learning:v,taskId:o,status:"completed",lineCoverage:g,branchCoverage:l,functionCoverage:u,statementCoverage:h,totalFiles:i,gaps:y,duration:t,savedFiles:n,estimated:d,measured:m,coverageMethod:e.coverageMethod??"unknown",branchDataCollected:a,functionDataCollected:c,...e.runStatus==="passed"||e.runStatus==="failed"?{runStatus:e.runStatus}:{},...e.unmeasured===!0?{unmeasured:!0}:{},...e.warning?{warning:e.warning}:{}}}},Eo={domain:"quality-assessment",taskType:"assess-quality",priority:"p0",defaultTimeout:18e4,buildTaskDescription:o=>`Assess quality with ${o.runGate?"quality gate":"metrics analysis"}`,mapToPayload:(o,e)=>{if(o.runGate!==void 0&&typeof o.runGate!="boolean")throw new Error("runGate must be a boolean.");let t=o.metrics===void 0?["coverage","complexity","maintainability"]:Xt(o.metrics);if(o.target!==void 0&&(typeof o.target!="string"||o.target.trim()===""))throw new ae("target must be a non-empty string path.");if(o.sourceFiles!==void 0&&(!Array.isArray(o.sourceFiles)||o.sourceFiles.length===0||o.sourceFiles.some(n=>typeof n!="string"||n.trim()==="")))throw new ae("sourceFiles must be a non-empty array of file paths.");return{runGate:o.runGate??!1,...o.target!==void 0?{target:o.target}:{},...o.sourceFiles!==void 0?{sourceFiles:o.sourceFiles}:{},threshold:o.threshold||80,thresholdSource:o.threshold===void 0?"default":"request",metrics:t,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,n)=>{let r=Array.isArray(e.unmeasured)?e.unmeasured.filter(g=>typeof g=="string"):void 0,i=(r?.length??0)>0||e.evidenceStatus===Le,s=typeof e.gateEvaluated=="boolean"?e.gateEvaluated:void 0,a=typeof e.confidence=="number"?e.confidence:void 0,c=Array.isArray(e.measuredFailures)?e.measuredFailures:void 0,l=(c??[]).map(g=>g.metric),u=e.unmeasuredReasons&&typeof e.unmeasuredReasons=="object"&&Object.values(e.unmeasuredReasons).every(g=>typeof g=="string")?e.unmeasuredReasons:void 0,d=typeof e.qualityScore=="number"&&e.qualityScore>=0?e.qualityScore:void 0,m=!i&&l.length===0&&e.passed===!0,p=vo({passed:i||l.length>0?!1:typeof e.passed=="boolean"?e.passed:void 0,qualityScore:d,recommendations:e.recommendations||[],unmeasured:i?r?.length?r:["unknown"]:[],failedMetrics:l,evidenceConfidence:a,gateEvaluated:s});return{taskId:o,status:i?Le:"completed",...typeof e.qualityScore=="number"?{qualityScore:e.qualityScore}:{},...Array.isArray(e.checks)?{checks:e.checks}:{},passed:m,metrics:e.metrics||{},recommendations:e.recommendations||[],...e.evidenceStatus==="measured"||i?{evidenceStatus:i?Le:"measured"}:{},...r?{unmeasured:r}:{},...u?{unmeasuredReasons:u}:{},...Array.isArray(e.partialMetrics)?{partialMetrics:e.partialMetrics}:{},...Array.isArray(e.excludedFiles)?{excludedFiles:e.excludedFiles}:{},...typeof e.excludedCount=="number"?{excludedCount:e.excludedCount}:{},...typeof e.scope=="string"?{scope:e.scope}:{},...Array.isArray(e.scoreBasis)&&e.scoreBasis.every(g=>typeof g=="string")?{scoreBasis:e.scoreBasis}:{},...c?{measuredFailures:c}:{},...s!==void 0?{gateEvaluated:s}:{},...a!==void 0?{confidence:a}:{},...typeof e.note=="string"?{note:e.note}:{},duration:t,savedFiles:n,...yo(p).valid?{riskDecision:p}:{}}}},wo={domain:"security-compliance",taskType:"scan-security",priority:"p0",defaultTimeout:6e5,buildTaskDescription:o=>{let e=[];return o.sast!==!1&&e.push("SAST"),o.dast&&e.push("DAST"),o.dependencies&&e.push("dependency advisories"),`Security scan (${e.join(", ")}) for ${o.target||"project"}`},mapToPayload:(o,e)=>{for(let t of["sast","dast","dependencies"])if(o[t]!==void 0&&typeof o[t]!="boolean")throw new Error(`${t} must be a boolean`);return{sast:o.sast!==!1,dast:o.dast||!1,dependencies:o.dependencies===!0,compliance:o.compliance||[],target:o.target||".",targetUrl:o.targetUrl,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,n)=>({taskId:o,status:e.evidence?.completeness==="complete"?"completed":e.evidence?.completeness==="partial"?"partial":e.evidence?"unavailable":"unverified",vulnerabilities:e.vulnerabilities||0,critical:e.critical||0,high:e.high||0,medium:e.medium||0,low:e.low||0,informational:e.informational||0,topVulnerabilities:e.topVulnerabilities||[],findings:e.findings,recommendations:e.recommendations||[],evidence:e.evidence,limitations:e.limitations||["Execution receipts unavailable; scan completeness is unverified."],...e.evidence?{filesScanned:e.filesScanned,jstsFilesScanned:e.jstsFilesScanned,otherFilesScanned:e.otherFilesScanned,coverage:e.coverage}:{},deepAnalysisPerformed:!!(e.evidence&&e.deepAnalysisPerformed===!0),analysisDepth:e.analysisDepth,scanTypes:e.scanTypes,...e.dependencyScan?{dependencyScan:e.dependencyScan}:{},note:e.note,duration:t,savedFiles:n})},Ro={domain:"contract-testing",taskType:"validate-contracts",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Validate API contract at ${o.contractPath}`,mapToPayload:(o,e)=>({contractPath:o.contractPath,providerUrl:o.providerUrl,consumerName:o.consumerName,checkBreakingChanges:o.checkBreakingChanges!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",valid:e.valid||!1,breakingChanges:e.breakingChanges||[],warnings:e.warnings||[],duration:t,savedFiles:n})},Po={domain:"visual-accessibility",taskType:"test-accessibility",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Test accessibility for ${o.url} against ${o.standard||"WCAG 2.1 AA"} standard`,mapToPayload:(o,e)=>({url:o.url,standard:o.standard||"wcag21-aa",includeScreenReader:o.includeScreenReader||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",passed:e.passed||!1,score:e.score||0,violations:e.violations||[],warnings:e.warnings||[],duration:t,savedFiles:n})},xo={domain:"chaos-resilience",taskType:"run-chaos",priority:"p2",defaultTimeout:9e4,buildTaskDescription:o=>`Run chaos test with ${o.faultType||"latency"} fault injection on ${o.target}`,mapToPayload:(o,e)=>({faultType:o.faultType||"latency",target:o.target,duration:o.duration||3e4,intensity:o.intensity||50,dryRun:o.dryRun!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:o=>(o.duration||3e4)+6e4,mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",faultType:e.faultType||"latency",resilience:e.resilience||{recovered:!1,recoveryTime:0,dataLoss:!1},duration:t,savedFiles:n})},Ao={domain:"defect-intelligence",taskType:"predict-defects",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Predict defects in ${o.target||"codebase"} with ${o.lookback||30} day lookback`,mapToPayload:(o,e)=>({target:o.target||".",lookback:o.lookback||30,minConfidence:o.minConfidence||.7,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",predictedDefects:e.predictedDefects||[],riskScore:e.riskScore||0,recommendations:e.recommendations||[],duration:t,savedFiles:n})},ko={domain:"requirements-validation",taskType:"validate-requirements",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Validate requirements${o.generateBDD?" and generate BDD scenarios":""}`,mapToPayload:(o,e)=>({requirementsPath:o.requirementsPath,testPath:o.testPath,generateBDD:o.generateBDD||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",requirementsAnalyzed:e.requirementsAnalyzed||0,testable:e.testable||0,coverage:e.coverage||0,bddScenarios:e.bddScenarios||[],duration:t,savedFiles:n})},Mo={domain:"code-intelligence",taskType:"index-code",priority:"p2",defaultTimeout:3e5,buildTaskDescription:o=>`Index code in ${o.target||"codebase"}${o.incremental?" incrementally":""}`,mapToPayload:(o,e)=>({target:o.target||".",incremental:o.incremental||!1,gitSince:o.gitSince,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",filesIndexed:e.filesIndexed||0,symbolsExtracted:e.symbolsExtracted||0,relationsFound:e.relationsFound||0,...e.projectMetrics?{projectMetrics:e.projectMetrics}:{},duration:t,savedFiles:n})};function $u(o){let e=[],t=o.split(`
450
450
  `);for(let n of t){let r=n.trim(),i=r.match(/expect\((.+?)\)\.(to\w+)\((.+?)\)/);if(i){e.push(`expect(${i[1]}).${i[2]}(${i[3]})`);continue}let s=r.match(/assert\w*\((.+)\)/);if(s){e.push(s[0]);continue}let a=r.match(/(?:it|test)\s*\(\s*['"`](.+?)['"`]/);a&&e.push(a[1])}return e.length>0?e:["test generated from source analysis"]}function Io(){go()}var xv=Z(Co),Av=Z(So),kv=Z(To),Mv=Z(Eo),Iv=Z(wo),Dv=Z(Ro),_v=Z(Po),Ov=Z(xo),Nv=Z(Ao),Fv=Z(ko),Lv=Z(Mo);k();var On=class extends A{config={name:"qe/tests/generate",description:"Generate tests for source code files. Supports unit, integration, and e2e tests with AI-powered pattern recognition.",domain:"test-generation",schema:Gu,streaming:!0,timeout:12e4};testGeneratorService=null;async getService(e){if(!this.testGeneratorService){let t=await O(),n=await U(e);this.testGeneratorService=ss({memory:t,llmRouter:n},{defaultFramework:"vitest",maxTestsPerFile:50,coverageTargetDefault:80,enableAIGeneration:!0})}return this.testGeneratorService}async execute(e,t){let{sourceFiles:n,testType:r="unit",framework:i="vitest",language:s="typescript",coverageTarget:a=80,patterns:c=[],aiEnhancement:l=!0,detectAntiPatterns:u=!1}=e;try{let d=Vt(e.behaviorExamples);if(this.emitStream(t,{status:"analyzing",message:`Analyzing ${n.length} source files`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(Er.isEnabled()){let y=`Generate ${r} tests for ${n.length} files using ${i}`,C=await Er.checkTaskEarlyExit(y,"test-generation");C.canExit&&C.reusedPattern&&(this.emitStream(t,{status:"pattern-reuse",message:`Reusing pattern: ${C.reusedPattern.name}`,tokensSaved:C.estimatedTokensSaved}),console.log(`[TestGenerateTool] Early exit: reusing pattern ${C.reusedPattern.name}, saving ~${C.estimatedTokensSaved} tokens`))}let m=await this.getService(t),p={behaviorExamples:d,sourceFiles:n,testType:r,framework:i,coverageTarget:a,patterns:c},g=await m.generateTests(p);if(!g.success)return{success:!1,error:g.error?.message||"Test generation failed"};let f=g.value,h=f.tests.map(y=>({id:y.id,name:y.name,sourceFile:y.sourceFile,testFile:y.testFile,testCode:y.testCode,type:y.type,assertions:y.assertions,generationMode:y.generationMode,generationLimits:y.generationLimits}));this.emitStream(t,{status:"generating",message:`Generated ${h.length} test files`,progress:50});let v=u?ju(n):[];return this.emitStream(t,{status:"complete",message:"Test generation complete",progress:100}),{success:!0,data:{tests:h,coverageEstimate:f.coverageEstimate,patternsUsed:f.patternsUsed,suggestions:Bu(h,l),antiPatterns:v.length>0?v:void 0}}}catch(d){return{success:!1,error:`Test generation failed: ${E(d)}`}}}resetInstanceCache(){this.testGeneratorService=null}},Gu={type:"object",properties:{behaviorExamples:{type:"array",description:"Trusted JSON specification fixtures: functionName, args, expected",items:rs},sourceFiles:{type:"array",description:"Array of source file paths to generate tests for",items:{type:"string",description:"File path"}},testType:{type:"string",description:"Type of tests to generate",enum:["unit","integration","e2e"],default:"unit"},framework:{type:"string",description:"Test framework to use",enum:["jest","vitest","mocha","pytest"],default:"vitest"},language:{type:"string",description:"Programming language of source files",enum:["typescript","javascript","python","java","go"],default:"typescript"},coverageTarget:{type:"number",description:"Target code coverage percentage (0-100)",minimum:0,maximum:100,default:80},patterns:{type:"array",description:"Test patterns to apply",items:{type:"string",description:"Pattern name"}},aiEnhancement:{type:"boolean",description:"Enable AI-powered test enhancement",default:!0},detectAntiPatterns:{type:"boolean",description:"Detect and report anti-patterns in source code",default:!1}},required:["sourceFiles"]};function ju(o){let e=[],t=pc("fs");for(let n of o)try{let r;try{r=t.readFileSync(n,"utf-8")}catch{continue}let i=r.split(`
451
451
  `),s=/(?<![\w.])(\d{2,}|[2-9]\d*)(?![\w.])/g,a=new Set(["10","100","1000","60","24","365","404","500","200","201"]);i.forEach((g,f)=>{if(g.trim().startsWith("//")||g.trim().startsWith("*")||g.includes("import")||g.includes("require"))return;let h=g.match(s);if(h)for(let v of h){if(a.has(v))continue;let y=g.substring(0,g.indexOf(v)),C=(y.match(/'/g)||[]).length,b=(y.match(/"/g)||[]).length,w=(y.match(/`/g)||[]).length;if(!(C%2===1||b%2===1||w%2===1)){e.push({name:"magic-number",location:`${n}:${f+1}`,severity:"medium",suggestion:`Consider extracting ${v} into a named constant to improve readability and maintainability`});break}}});let c=/(?:it|test)\s*\(\s*['"`]([^'"`]+)['"`]\s*,/g,l;for(;(l=c.exec(r))!==null;){let g=l.index,f=l[1],h=r.substring(g),v=zu(h);if(v){let y=/expect\s*\(/.test(v),C=/assert[\.\(]/.test(v),b=/\.should[\.\(]/.test(v),w=/\.toBe|\.toEqual|\.toMatch|\.toThrow|\.toContain/.test(v);if(!y&&!C&&!b&&!w){let T=r.substring(0,g).split(`
452
452
  `).length;e.push({name:"no-assertions",location:`${n}:${T}`,severity:"high",suggestion:`Test "${f}" has no assertions. Add expect() or assert() calls to verify behavior`})}}}let u=[{pattern:/let\s+\w+\s*=\s*(?!undefined|null)/g,name:"mutable-let-declaration"},{pattern:/(?:^|\s)var\s+\w+\s*=/g,name:"mutable-var-declaration"}],d=r.match(/describe\s*\([^)]+,\s*(?:function\s*\(\)|(?:\(\s*\))?\s*=>)\s*\{/g);if(d)for(let g of d){let f=r.indexOf(g),h=Uu(r.substring(f));if(h){let v=h.match(/^\s*let\s+(\w+)\s*(?::\s*\w+)?\s*(?:=|;)/m);if(v){let y=v[1];if((h.match(new RegExp(`(?:it|test)\\s*\\([^)]+,[^]*?${y}\\s*=`,"g"))||[]).length>=2){let b=r.substring(0,f+h.indexOf(v[0])).split(`
@@ -638,7 +638,7 @@ ${l}
638
638
  Analyze the requirements above and return the complete QualityCriteriaAnalysis.`}resetInstanceCache(){this.service=null}},Sd={type:"object",properties:{assessmentName:{type:"string",description:"Assessment name (e.g., Epic title or feature name)"},epicPath:{type:"string",description:"Path to epic/requirements document"},epicContent:{type:"string",description:"Epic content as string (alternative to epicPath)"},sourcePaths:{type:"array",description:"Source code paths to analyze for evidence",items:{type:"string",description:"Source path glob pattern"}},outputFormat:{type:"string",description:"Output format for the report",enum:["html","json","markdown"],default:"html"},outputPath:{type:"string",description:"Path to save the output report"},evidencePoints:{type:"array",description:"Evidence points to validate (for validate-evidence action)",items:{type:"object",description:"Evidence point object",properties:{sourceReference:{type:"string",description:"Source reference in file:line format"},type:{type:"string",enum:["Direct","Inferred","Claimed"],description:"Evidence type"},qualityImplication:{type:"string",description:"Quality implication of this evidence"},reasoning:{type:"string",description:"Reasoning explaining WHY it matters"}},required:["sourceReference","type","qualityImplication","reasoning"]}},completedAnalysis:{type:"object",description:"Completed QualityCriteriaAnalysis object (for format action)"},action:{type:"string",description:'Action to perform. "analyze" (default) returns agentInvocation for real analysis. "validate-evidence" validates evidence format. "format" formats completed analysis.',enum:["analyze","validate-evidence","format"],default:"analyze"}},required:["assessmentName"]},FC=new Et;import*as wi from"fs";import*as Pe from"path";k();var Hn=class extends A{config={name:"qe/code/analyze",description:"Analyze code using knowledge graph and semantic search. Supports indexing, searching, impact analysis, and dependency mapping.",domain:"code-intelligence",schema:Td,streaming:!0,timeout:3e5};knowledgeGraph=null;semanticAnalyzer=null;impactAnalyzer=null;async getKnowledgeGraph(e){if(!this.knowledgeGraph){let t=e.memory??await O(),n=await U(e);this.knowledgeGraph=new Yt({memory:t,llmRouter:n})}return this.knowledgeGraph}async getSemanticAnalyzer(e){if(!this.semanticAnalyzer){let t=e.memory;this.semanticAnalyzer=new As(t||await O())}return this.semanticAnalyzer}async getImpactAnalyzer(e){if(!this.impactAnalyzer){let t=e.memory,n=await this.getKnowledgeGraph(e);this.impactAnalyzer=new ks(t||await O(),n)}return this.impactAnalyzer}async execute(e,t){let{action:n,paths:r=["."],query:i,changedFiles:s=[],depth:a=3,incremental:c=!1}=e;try{if(this.emitStream(t,{status:"processing",message:`Executing ${n} action`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let l={action:n};switch(n){case"index":l.indexResult=await this.executeIndex(r,c,t);break;case"search":if(!i)return{success:!1,error:"Query is required for search action"};l.searchResult=await this.executeSearch(i,r,t);break;case"impact":if(s.length===0)return{success:!1,error:"changedFiles is required for impact action"};l.impactResult=await this.executeImpact(s,a,t);break;case"dependencies":l.dependencyResult=await this.executeDependencies(r,a,t);break;default:return{success:!1,error:`Unknown action: ${n}`}}return this.emitStream(t,{status:"complete",message:`${n} complete`,progress:100}),{success:!0,data:l}}catch(l){return{success:!1,error:`Code analysis failed: ${E(l)}`}}}async executeIndex(e,t,n){this.emitStream(n,{status:"indexing",message:`Indexing ${e.length} paths (${t?"incremental":"full"})`});let r=await this.getKnowledgeGraph(n),i=await this.expandPaths(e),s=await r.index({paths:i,incremental:t,includeTests:!0,languages:["typescript","javascript"]});if(!s.success)throw new Error(s.error?.message||"Indexing failed");return{filesIndexed:s.value.filesIndexed,nodesCreated:s.value.nodesCreated,edgesCreated:s.value.edgesCreated,duration:s.value.duration,errors:s.value.errors}}async executeSearch(e,t,n){let r=Date.now();if(this.isDemoMode(n)){let l=Date.now()-r;return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoSearchResult(e,l)}this.emitStream(n,{status:"searching",message:`Searching for: ${e}`});let s=await(await this.getSemanticAnalyzer(n)).search({query:e,type:"semantic",limit:20,scope:t.length>0&&t[0]!=="."?t:void 0}),a=Date.now()-r;return s.success?s.value.results.length===0?(this.markAsRealData(),{results:[],total:0,searchTime:a}):(this.markAsRealData(),{results:s.value.results.map(l=>({file:l.file,line:l.line,snippet:l.snippet.substring(0,200)+(l.snippet.length>200?"...":""),score:l.score,highlights:Ed(l.snippet,e)})),total:s.value.total,searchTime:a}):{results:[],total:0,searchTime:a}}getDemoSearchResult(e,t){return{results:[{file:"src/services/UserService.ts",line:15,snippet:`export class ${e} { constructor() { /* initialization */ } }...`,score:.95,highlights:[e,`class ${e}`,`${e}Service`]},{file:"src/handlers/user-handler.ts",line:42,snippet:`const service = new ${e}(); await service.initialize()...`,score:.85,highlights:[`new ${e}()`,`service.${e.toLowerCase()}`]},{file:"tests/services/UserService.test.ts",line:8,snippet:`describe('${e}', () => { it('should initialize correctly'...`,score:.78,highlights:[`describe('${e}'`,`test ${e}`]}],total:3,searchTime:t}}getDemoImpactResult(e){let t=e[0]||"src/service.ts",n=t.split("/").pop()?.replace(".ts","")||"service";return{directImpact:[{file:`src/handlers/${n}-handler.ts`,reason:`Direct import from ${t}`,distance:0,riskScore:.75},{file:`src/controllers/${n}-controller.ts`,reason:`Uses exported functions from ${t}`,distance:0,riskScore:.65}],transitiveImpact:[{file:"src/routes/api.ts",reason:`Imports from ${n}-handler.ts`,distance:1,riskScore:.45},{file:"src/app.ts",reason:"Imports API routes",distance:2,riskScore:.25}],impactedTests:[`tests/${n}.test.ts`,`tests/${n}-handler.test.ts`,"tests/integration/api.test.ts"],riskLevel:"medium",recommendations:[`Review changes in ${t} for breaking changes`,"Run affected test suites before merging","Consider updating dependent documentation"]}}async executeImpact(e,t,n){if(this.isDemoMode(n))return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoImpactResult(e);this.emitStream(n,{status:"analyzing",message:`Analyzing impact of ${e.length} changed files`});try{let i=await(await this.getImpactAnalyzer(n)).analyzeImpact({changedFiles:e,depth:t,includeTests:!0});if(!i.success)return{directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"low",recommendations:[`Impact analysis failed: ${i.error?.message||"Unknown error"}. Ensure the code index is built first using action: 'index'.`]};this.markAsRealData();let s=i.value;return{directImpact:s.directImpact,transitiveImpact:s.transitiveImpact,impactedTests:s.impactedTests,riskLevel:s.riskLevel,recommendations:s.recommendations}}catch(r){return{directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"low",recommendations:[`Impact analysis error: ${r instanceof Error?r.message:"Unknown error"}. Check that files exist and index is built.`]}}}async executeDependencies(e,t,n){this.emitStream(n,{status:"mapping",message:`Mapping dependencies to depth ${t}`});let r=await this.getKnowledgeGraph(n),i=await this.expandPaths(e),s=await r.mapDependencies({files:i,direction:"both",depth:t});if(!s.success)throw new Error(s.error?.message||"Dependency mapping failed");let a=s.value,c=a.nodes.map(u=>({id:u.id,path:u.path,type:u.type,inDegree:u.inDegree,outDegree:u.outDegree})),l=a.edges.map(u=>({source:u.source,target:u.target,type:u.type}));return{nodes:c,edges:l,cycles:a.cycles,metrics:{totalNodes:a.metrics.totalNodes,totalEdges:a.metrics.totalEdges,avgDegree:a.metrics.avgDegree,maxDepth:a.metrics.maxDepth}}}async expandPaths(e){let t=[];for(let n of e){let r=Pe.isAbsolute(n)?n:Pe.resolve(process.cwd(),n);try{let i=await wi.promises.stat(r);if(i.isDirectory()){let s=await this.findSourceFiles(r);t.push(...s)}else i.isFile()&&t.push(r)}catch{}}return t}async findSourceFiles(e,t=!0){let n=[],r=[".ts",".tsx",".js",".jsx"],i=["node_modules",".git","dist","build","coverage"];try{let s=await wi.promises.readdir(e,{withFileTypes:!0});for(let a of s){let c=Pe.join(e,a.name);if(a.isDirectory()){if(!i.includes(a.name)&&!ls(e,a.name,t)){let l=await this.findSourceFiles(c,!1);n.push(...l)}}else if(a.isFile()){let l=Pe.extname(a.name);r.includes(l)&&n.push(c)}}}catch{}return n}},Td={type:"object",properties:{action:{type:"string",description:"Analysis action to perform",enum:["index","search","impact","dependencies"]},paths:{type:"array",description:"Paths to analyze",items:{type:"string",description:"File or directory path"},default:["."]},query:{type:"string",description:"Search query (for search action)"},changedFiles:{type:"array",description:"Changed files to analyze (for impact action)",items:{type:"string",description:"File path"}},depth:{type:"number",description:"Analysis depth",minimum:1,maximum:10,default:3},incremental:{type:"boolean",description:"Incremental indexing (for index action)",default:!1}},required:["action"]};function Ed(o,e){let t=[],n=e.toLowerCase().split(/\s+/),r=o.toLowerCase();for(let i of n){if(i.length<2)continue;let s=0;for(;(s=r.indexOf(i,s))!==-1;){let a=Math.max(0,s-20),c=Math.min(o.length,s+i.length+20),l=o.substring(a,c);if(t.includes(l)||t.push(l),s+=i.length,t.length>=3)break}if(t.length>=3)break}return t}k();var Ri=(o,e)=>o==="all"||o===e,Vn=class extends A{config={name:"qe/code/c4",description:"Generate C4 architecture diagrams (Context/Container/Component, Mermaid) from a codebase with a deterministic confidence gate, or semantically search previously generated diagrams.",domain:"code-intelligence",schema:wd,streaming:!1,timeout:3e5};bridge=null;searchService=null;async getBridge(e){if(!this.bridge){let t=e.memory??await O();this.bridge=new Ps(new Ji,t,{publishEvents:!1,enableC4Embeddings:!0,relationshipResolver:xs(n=>new Yt(t,{basePath:n}))})}return this.bridge}async getSearchService(e){if(!this.searchService){let t=e.memory??await O();this.searchService=new Rs(t,{enableEmbeddings:!0})}return this.searchService}async execute(e,t){let{action:n,projectPath:r=".",level:i="all",query:s,limit:a=10}=e;try{if(this.isAborted(t))return{success:!1,error:"Operation aborted"};let c={action:n};switch(n){case"generate":{let u=await(await this.getBridge(t)).requestC4Diagrams({projectPath:r,includeContext:Ri(i,"context"),includeContainer:Ri(i,"container"),includeComponent:Ri(i,"component"),includeDependency:i==="all",analyzeComponents:!0,detectExternalSystems:!0,analyzeCoupling:!0});if(!u.success)return{success:!1,error:E(u.error)};let d=u.value;c.generateResult={diagrams:d.diagrams,confidence:d.metadata.analysisMetadata?.confidence,componentsDetected:d.components.length,externalSystemsDetected:d.externalSystems.length,relationshipsDetected:d.relationships.length,circularDependencies:(d.couplingAnalysis??[]).filter(m=>m.isCircular).length};break}case"search":{if(!s)return{success:!1,error:"Query is required for search action"};let u=await(await this.getSearchService(t)).searchDiagrams(s,a);if(!u.success)return{success:!1,error:E(u.error)};c.searchResult={results:u.value.map(d=>({key:d.key,type:d.type,title:d.title,score:d.score,preview:d.preview})),total:u.value.length};break}default:return{success:!1,error:`Unknown action: ${n}`}}return{success:!0,data:c}}catch(c){return{success:!1,error:E(c)}}}},wd={type:"object",properties:{action:{type:"string",description:"C4 action to perform",enum:["generate","search"]},projectPath:{type:"string",description:"Project root to analyze (generate action). Defaults to the current directory."},level:{type:"string",description:"C4 level to generate (generate action)",enum:["context","container","component","all"]},query:{type:"string",description:"Semantic search query over stored diagrams (search action)"},limit:{type:"number",description:"Max search results (search action)"}},required:["action"]};k();X();var Vo=[{id:"secret-key-assignment",pattern:/(?:SECRET_KEY|secret_key|SECRET|PRIVATE_KEY)\s*=\s*['"][^'"]{4,}['"]/g,severity:"critical",title:"Hardcoded Secret Key",description:"Secret key assigned as string literal in source code",cweId:"CWE-798",remediation:'Use environment variables: SECRET_KEY = os.environ["SECRET_KEY"]'},{id:"cors-wildcard-credentials",pattern:/allow_origins\s*=\s*\[\s*["']\*["']\s*\]/g,severity:"high",title:"CORS Wildcard Origin",description:"CORS configured to allow all origins \u2014 combined with credentials this is a security risk",cweId:"CWE-942",remediation:"Restrict CORS origins to specific trusted domains"},{id:"cors-allow-credentials-wildcard",pattern:/allow_credentials\s*=\s*True/g,severity:"medium",title:"CORS Credentials Enabled",description:"CORS credentials enabled \u2014 verify origins are restricted",cweId:"CWE-942",remediation:'Ensure allow_origins does not include "*" when credentials are enabled'},{id:"token-hardcoded",pattern:/(?:token|TOKEN)\s*[:=]\s*['"][a-zA-Z0-9_\-.]{20,}['"]/g,severity:"high",title:"Hardcoded Token",description:"Hardcoded token found in source code",cweId:"CWE-798",remediation:"Use environment variables or secrets manager for tokens"}],Qn=class extends A{config={name:"qe/security/scan",description:"Comprehensive security scanning including SAST, DAST, dependency analysis, and compliance validation.",domain:"security-compliance",schema:Rd,streaming:!0,timeout:6e5};async execute(e,t){let{target:n=".",scanType:r=["sast","dependency"],compliance:i=[],dastUrl:s,depth:a="standard",failOnSeverity:c="critical"}=e,l=Date.now();try{if(this.emitStream(t,{status:"scanning",message:`Starting security scan (${r.join(", ")})`,depth:a}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let u=await Ad(n,a);this.emitStream(t,{status:"discovered",message:`Found ${u.length} files to scan`});let d=[];if(r.includes("sast")||r.includes("secret")){this.emitStream(t,{status:"sast",message:"Running static analysis"});let y=await kd(u,r);d.push(...y)}if(r.includes("dependency")){this.emitStream(t,{status:"dependency",message:"Scanning dependencies"});let y=await Md(n);d.push(...y)}r.includes("dast")&&s&&(this.emitStream(t,{status:"dast",message:`Scanning ${s}`}),d.push(...Ld(s)));let m=i.map(y=>qd(y,d)),p={critical:d.filter(y=>y.severity==="critical").length,high:d.filter(y=>y.severity==="high").length,medium:d.filter(y=>y.severity==="medium").length,low:d.filter(y=>y.severity==="low").length,informational:d.filter(y=>y.severity==="informational").length,totalFiles:u.length,scanDurationMs:Date.now()-l},g=["critical","high","medium","low","informational"],f=g.indexOf(c),v=(d.length>0?Math.min(...d.map(y=>g.indexOf(y.severity))):g.length)>f;return await Wt(await rn(t),{securityVulnerabilities:d.length},{measuredAt:new Date().toISOString(),source:"qe/security/scan"}),this.emitStream(t,{status:"complete",message:`Scan complete: ${d.length} vulnerabilities found in ${u.length} files`,progress:100}),{success:!0,data:{scanId:t.requestId,summary:p,vulnerabilities:d,complianceResults:m.length>0?m:void 0,recommendations:$d(d,p),passed:v}}}catch(u){return{success:!1,error:`Security scan failed: ${E(u)}`}}}},Rd={type:"object",properties:{target:{type:"string",description:"Target directory or file to scan",default:"."},scanType:{type:"array",description:"Types of security scans to run",items:{type:"string",description:"Scan type",enum:["sast","dast","dependency","secret"]},default:["sast","dependency"]},compliance:{type:"array",description:"Compliance standards to validate against",items:{type:"string",description:"Standard",enum:["owasp","gdpr","hipaa","pci-dss","soc2"]}},dastUrl:{type:"string",description:"URL for DAST scanning"},depth:{type:"string",description:"Scan depth",enum:["quick","standard","deep"],default:"standard"},failOnSeverity:{type:"string",description:"Fail threshold severity",enum:["critical","high","medium","low"],default:"critical"}}},Pd=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".java",".kt",".scala",".go",".rb",".php",".rs",".cs",".yaml",".yml",".json",".toml",".cfg",".ini",".env",".env.local",".env.production",".sh",".bash"]),xd=new Set(["node_modules",".git","__pycache__",".venv","venv","dist","build",".next",".nuxt","coverage",".tox"]);async function Ad(o,e){let t=await import("fs"),n=await import("path"),r=n.resolve(o),i=[],s=e==="quick"?50:e==="standard"?500:2e3,a=e==="quick"?3:e==="standard"?8:20;function c(l,u){if(i.length>=s||u>a)return;let d;try{d=t.readdirSync(l,{withFileTypes:!0})}catch{return}for(let m of d){if(i.length>=s)break;let p=n.join(l,m.name);if(m.isDirectory()){let g=new Set([".github",".docker",".aws",".circleci",".gitlab"]);xd.has(m.name)||m.name.startsWith(".")&&!g.has(m.name)||c(p,u+1)}else if(m.isFile()){let g=n.extname(m.name).toLowerCase();(Pd.has(g)||m.name==="Dockerfile"||m.name==="Makefile"||m.name.startsWith(".env"))&&i.push(p)}}}try{t.statSync(r).isFile()?i.push(r):c(r,0)}catch{}return i}async function kd(o,e){let t=await import("fs"),n=await import("path"),r=[],i=0,s=[];if(e.includes("sast")){for(let a of Os)s.push({id:a.id,pattern:new RegExp(a.pattern.source,a.pattern.flags),severity:a.severity,title:a.title,description:a.description,cweId:a.cweId,remediation:a.remediation,category:a.category});for(let a of Vo)s.push({id:a.id,pattern:new RegExp(a.pattern.source,a.pattern.flags),severity:a.severity,title:a.title,description:a.description,cweId:a.cweId,remediation:a.remediation,category:"sensitive-data"})}if(e.includes("secret")){for(let a of _s)s.some(c=>c.id===a.id)||s.push({id:a.id,pattern:new RegExp(a.pattern.source,a.pattern.flags),severity:a.severity,title:a.title,description:a.description,cweId:a.cweId,remediation:a.remediation,category:a.category});for(let a of Vo)s.some(c=>c.id===a.id)||s.push({...a,category:"sensitive-data"})}for(let a of o){let c;try{c=t.readFileSync(a,"utf-8")}catch{continue}if(c.includes("\0")||c.length>1e6)continue;let l=c.split(`
639
639
  `),u=n.relative(process.cwd(),a);for(let d of s){let m=new RegExp(d.pattern.source,d.pattern.flags),p;for(;(p=m.exec(c))!==null;){i++;let g=c.substring(0,p.index).split(`
640
640
  `).length,f=l[g-1]||"",h=f.trim().length>100?f.trim().substring(0,100)+"...":f.trim();if(r.push({id:`${d.id}-${i}`,title:d.title,severity:d.severity,category:d.category||"security-misconfiguration",location:{file:u,line:g,snippet:h},description:d.description,remediation:d.remediation,cweId:d.cweId,references:[]}),i>200)break}}}return r}async function Md(o){let e=await import("fs"),t=await import("path"),n=[],r=t.resolve(o),i=t.join(r,"package.json");if(e.existsSync(i))try{let c=M(e.readFileSync(i,"utf-8")),l={...c.dependencies,...c.devDependencies};n.push(...Dd(l,"package.json"))}catch{}let s=t.join(r,"pyproject.toml");if(e.existsSync(s))try{let c=e.readFileSync(s,"utf-8"),l=Od(c);n.push(...Qo(l,"pyproject.toml"))}catch{}let a=t.join(r,"requirements.txt");if(e.existsSync(a))try{let c=e.readFileSync(a,"utf-8"),l=Nd(c);n.push(...Qo(l,"requirements.txt"))}catch{}if(n.length===0){let c=[i,s,a].filter(l=>e.existsSync(l));c.length>0&&n.push({id:"DEP-INFO-001",title:"Dependency audit recommended",severity:"informational",category:"vulnerable-components",location:{file:t.relative(process.cwd(),c[0])},description:`Found ${t.basename(c[0])} \u2014 run language-specific dependency audit for comprehensive results`,remediation:"Run npm audit, pip-audit, or equivalent for full vulnerability check",references:[]})}return n}var Id={lodash:{maxSafe:"4.17.21",cve:"CVE-2021-23337",severity:"high",desc:"Prototype pollution in lodash"},minimist:{maxSafe:"1.2.6",cve:"CVE-2021-44906",severity:"critical",desc:"Prototype pollution in minimist"},"node-fetch":{maxSafe:"2.6.7",cve:"CVE-2022-0235",severity:"high",desc:"Information exposure in node-fetch"},express:{maxSafe:"4.19.2",cve:"CVE-2024-29041",severity:"medium",desc:"Open redirect in express"}};function Dd(o,e){let t=[];for(let[n,r]of Object.entries(o)){let i=Id[n];if(i){let s=r.replace(/^[\^~>=<]+/,"");Fd(s,i.maxSafe)<0&&t.push({id:`DEP-${n}-${i.cve}`,title:`Vulnerable ${n} version`,severity:i.severity,category:"vulnerable-components",location:{file:e,dependency:{name:n,version:s}},description:i.desc,remediation:`Upgrade ${n} to >= ${i.maxSafe}`,cveId:i.cve,references:[`https://nvd.nist.gov/vuln/detail/${i.cve}`]})}}return t}var _d={"python-jose":{cve:"CVE-2024-33663",severity:"critical",desc:"python-jose is abandoned and has known JWT vulnerabilities"},pyjwt:{cve:"CVE-2022-29217",severity:"high",desc:"PyJWT algorithm confusion vulnerability (upgrade to >= 2.4.0)"},"python-multipart":{cve:"CVE-2026-24486",severity:"high",desc:"python-multipart DoS vulnerability"},jinja2:{cve:"CVE-2024-34064",severity:"medium",desc:"Jinja2 XSS via template injection"},urllib3:{cve:"CVE-2023-45803",severity:"medium",desc:"urllib3 request body exposure on redirect"},requests:{cve:"CVE-2023-32681",severity:"medium",desc:"Requests proxy credential exposure"}};function Od(o){let e=[],t=o.match(/dependencies\s*=\s*\[([\s\S]*?)\]/);if(t){let n=t[1].matchAll(/["']([a-zA-Z0-9_-]+)/g);for(let r of n)e.push(r[1].toLowerCase())}return e}function Nd(o){return o.split(`
641
- `).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")).map(e=>e.split(/[>=<!~\[]/)[0].trim().toLowerCase()).filter(Boolean)}function Qo(o,e){let t=[];for(let n of o){let r=_d[n];r&&t.push({id:`DEP-py-${n}-${r.cve}`,title:`Vulnerable Python dependency: ${n}`,severity:r.severity,category:"vulnerable-components",location:{file:e,dependency:{name:n,version:"any"}},description:r.desc,remediation:n==="python-jose"?"Migrate to PyJWT or joserfc":`Check for updates to ${n}`,cveId:r.cve,references:[`https://nvd.nist.gov/vuln/detail/${r.cve}`]})}return t}function Fd(o,e){let t=o.split(".").map(Number),n=e.split(".").map(Number);for(let r=0;r<3;r++){let i=t[r]||0,s=n[r]||0;if(i<s)return-1;if(i>s)return 1}return 0}function Ld(o){return[{id:"DAST-INFO-001",title:"DAST scan target noted",severity:"informational",category:"security-misconfiguration",location:{file:o},description:`DAST target ${o} recorded. Full DAST requires integration with a dynamic scanner (e.g., ZAP, Burp).`,remediation:"Configure a DAST tool to scan the live application",references:["https://owasp.org/www-project-zap/"]}]}function qd(o,e){let t=e.filter(n=>o==="owasp"?!0:o==="pci-dss"?n.category==="injection"||n.category==="sensitive-data":o==="gdpr"?n.category==="sensitive-data":!1);return{standard:o,passed:t.filter(n=>n.severity==="critical"||n.severity==="high").length===0,score:Math.max(0,100-t.length*15),violations:t.map(n=>({ruleId:n.id,ruleName:n.title,location:n.location,details:n.description,remediation:n.remediation}))}}function $d(o,e){let t=[];return e.critical>0&&t.push("URGENT: Address critical vulnerabilities immediately"),e.high>0&&t.push("Prioritize high-severity issues in next sprint"),o.some(n=>n.category==="injection")&&t.push("Review input validation across the application"),o.some(n=>n.category==="sensitive-data")&&t.push("Implement proper secrets management"),o.some(n=>n.category==="vulnerable-components")&&t.push("Run full dependency audit and update vulnerable packages"),t.length===0&&t.push("No critical issues found. Continue regular security reviews."),t}X();k();function Wo(o){try{let e=new URL(o);if(!["http:","https:"].includes(e.protocol))return{valid:!1,error:`Invalid protocol: ${e.protocol}. Only http/https allowed.`};let t=e.hostname.toLowerCase(),n=[/^localhost$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2[0-9]|3[01])\./,/^192\.168\./,/^0\.0\.0\.0$/,/^\[::1\]$/,/^169\.254\./];for(let r of n)if(r.test(t))return{valid:!1,error:`Blocked hostname: ${t}. Cannot access internal/private addresses.`};return{valid:!0}}catch{return{valid:!1,error:`Invalid URL format: ${o}`}}}var Wn=class extends A{config={name:"qe/contracts/validate",description:"Validate API contracts, detect breaking changes, and verify provider-consumer compatibility.",domain:"contract-testing",schema:Gd,streaming:!0,timeout:18e4};contractValidator=null;apiCompatibility=null;async getServices(e){if(!this.contractValidator||!this.apiCompatibility){let t=e.memory||await O(),n=await U(e);this.contractValidator=new Ns({memory:t,llmRouter:n}),this.apiCompatibility=new Fs(t)}return{contractValidator:this.contractValidator,apiCompatibility:this.apiCompatibility}}async execute(e,t){let{contractPath:n,contractContent:r,providerUrl:i,consumerName:s,baselineVersion:a,baselineContent:c,checkBreakingChanges:l=!0,format:u="openapi"}=e,{contractValidator:d,apiCompatibility:m}=await this.getServices(t);try{if(!n&&!r)return{success:!1,error:"Either contractPath or contractContent is required"};if(this.emitStream(t,{status:"validating",message:`Validating ${u} contract`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let p=r||n||"",g=[],f,h,v;if(u==="openapi"){let b=await d.validateOpenAPI(p);if(b.success){let w=b.value;for(let T of w.errors)g.push({path:T.path,message:T.message,code:T.code,severity:"error"});for(let T of w.warnings)g.push({path:"",message:T,code:"WARNING",severity:"warning"});this.emitStream(t,{status:"analyzed",message:`Found ${w.endpointCount} endpoints, ${w.schemaCount} schemas`})}}else{let b=this.buildContractFromContent(p,u,s),w=await d.validateContract(b);if(w.success){let T=w.value;for(let S of T.errors)g.push(this.convertValidationError(S));for(let S of T.warnings)g.push({path:"",message:S,code:"WARNING",severity:"warning"})}}if(l&&(a||c)){this.emitStream(t,{status:"comparing",message:"Detecting breaking changes"});let b=this.buildContractFromContent(p,u,s),w=this.buildContractFromContent(c||p,u,s,a),T=await m.compareVersions(w,b);T.success?(f=T.value.breakingChanges.map(S=>this.convertBreakingChange(S)),v={isBackwardCompatible:T.value.isCompatible,breakingChangeCount:T.value.breakingChanges.length,nonBreakingChangeCount:T.value.nonBreakingChanges.length,deprecations:T.value.deprecations.map(S=>this.convertDeprecation(S))}):v=this.generateDefaultCompatibility(g,f)}else v=this.generateDefaultCompatibility(g,f);i&&(this.emitStream(t,{status:"verifying",message:"Verifying against provider"}),h=await this.verifyAgainstProvider(i,s||"default",p,u,d));let y=g.filter(b=>b.severity==="error").length===0,C=this.generateRecommendations(g,f,h);return this.emitStream(t,{status:"complete",message:y?"Contract is valid":`Found ${g.length} issues`,progress:100}),{success:!0,data:{isValid:y,validationErrors:g,breakingChanges:f,verificationResult:h,compatibility:v,recommendations:C}}}catch(p){return{success:!1,error:`Contract validation failed: ${E(p)}`}}}buildContractFromContent(e,t,n,r){let i=`contract-${Date.now()}`,s=Ds.parse(r||"1.0.0"),a=[],c=[];if(t==="openapi")try{let l=M(e),d=l.components?.schemas||{};for(let[p,g]of Object.entries(d))a.push({id:p,name:p,type:"openapi",content:JSON.stringify(g)});let m=l.paths||{};for(let[p,g]of Object.entries(m))if(typeof g=="object"&&g!==null){let f=g,h=["get","post","put","patch","delete","head","options"];for(let v of h)v in f&&c.push({path:p,method:v.toUpperCase(),examples:[]})}}catch{}else if(t==="graphql")a.push({id:"graphql-schema",name:"GraphQL Schema",type:"graphql",content:e});else if(t==="pact")try{let u=M(e).interactions||[];for(let d of u){let m=d.request;m&&c.push({path:m.path||"/",method:(m.method||"GET").toUpperCase(),examples:[]})}}catch{}return{id:i,name:`${t}-contract`,version:s,type:t,provider:{name:"provider",version:"1.0.0"},consumers:[{name:n||"default",version:"1.0.0"}],endpoints:c,schemas:a}}convertValidationError(e){return{path:e.path,message:e.message,code:e.code,severity:"error"}}convertBreakingChange(e){return{type:e.type,location:e.location,description:e.description,impact:e.impact,affectedConsumers:e.affectedConsumers,migrationPath:e.migrationPath}}convertDeprecation(e){return{location:e.location,reason:e.reason,removalVersion:e.removalVersion,replacement:e.replacement}}generateDefaultCompatibility(e,t){return{isBackwardCompatible:!t||t.length===0,breakingChangeCount:t?.length||0,nonBreakingChangeCount:e.filter(n=>n.severity!=="error").length,deprecations:[]}}async verifyAgainstProvider(e,t,n,r,i){let s=[],a=[],c=Wo(e);if(!c.valid)return{provider:e,consumer:t,passed:!1,failures:[{endpoint:e,type:"validation-error",expected:"Valid HTTP/HTTPS URL",actual:c.error||"Invalid URL",message:`Provider URL validation failed: ${c.error}`}],warnings:[]};let l=this.buildContractFromContent(n,r,t);for(let u of l.endpoints)try{let d=`${e}${u.path}`,m=Wo(d);if(!m.valid){s.push({endpoint:`${u.method} ${u.path}`,type:"validation-error",expected:"Valid URL",actual:m.error||"Invalid URL",message:`URL validation failed: ${m.error}`});continue}let p=await fetch(d,{method:u.method==="GET"?"GET":"OPTIONS",headers:{Accept:"application/json"}});if(!p.ok&&p.status!==405&&(p.status===404?s.push({endpoint:`${u.method} ${u.path}`,type:"missing-endpoint",expected:"Endpoint should exist",actual:`Got ${p.status}`,message:"Endpoint not found at provider"}):a.push({endpoint:`${u.method} ${u.path}`,message:`Unexpected status ${p.status}`,severity:"medium"})),u.responseSchema&&p.ok){let g=await p.json(),f=l.schemas.find(h=>h.id===u.responseSchema);if(f){let h=await i.validateResponse(g,f);if(h.success&&!h.value.isValid)for(let v of h.value.errors)s.push({endpoint:`${u.method} ${u.path}`,type:"schema-mismatch",expected:`Schema ${u.responseSchema}`,actual:v.message,message:`Response does not match schema: ${v.message}`})}}}catch(d){a.push({endpoint:`${u.method} ${u.path}`,message:`Failed to verify: ${E(d)}`,severity:"high"})}return{provider:e,consumer:t,passed:s.length===0,failures:s,warnings:a}}generateRecommendations(e,t,n){let r=[],i=e.filter(a=>a.severity==="error").length;if(i>0&&r.push(`Fix ${i} validation error${i>1?"s":""} before deploying`),t&&t.length>0){let a=t.filter(c=>c.impact==="high").length;a>0&&r.push(`Address ${a} high-impact breaking change${a>1?"s":""} before release`),r.push("Coordinate with affected consumers before releasing breaking changes"),r.push("Consider versioning the API to maintain backward compatibility")}n&&(n.passed||(r.push(`Provider verification failed with ${n.failures.length} failure${n.failures.length>1?"s":""}`),n.failures.filter(l=>l.type==="missing-endpoint").length>0&&r.push("Ensure all contract endpoints are implemented in the provider"),n.failures.filter(l=>l.type==="schema-mismatch").length>0&&r.push("Update provider responses to match the contract schema")),n.warnings.length>0&&n.warnings.filter(c=>c.severity==="high").length>0&&r.push("Investigate high-severity verification warnings"));let s=e.filter(a=>a.severity==="warning").length;return s>0&&r.push(`Review ${s} warning${s>1?"s":""} for potential issues`),r.length===0&&r.push("Contract is valid and backward compatible"),r}},Gd={type:"object",properties:{contractPath:{type:"string",description:"Path to contract file"},contractContent:{type:"string",description:"Contract content as string"},providerUrl:{type:"string",description:"Provider URL for verification"},consumerName:{type:"string",description:"Consumer name for contract"},baselineVersion:{type:"string",description:"Baseline version for breaking change detection"},baselineContent:{type:"string",description:"Baseline contract content for comparison"},checkBreakingChanges:{type:"boolean",description:"Check for breaking changes",default:!0},format:{type:"string",description:"Contract format",enum:["openapi","pact","graphql","asyncapi"],default:"openapi"}}};k();var Kn=class extends A{config={name:"qe/visual/compare",description:"Visual regression testing with screenshot comparison, diff detection, and baseline management.",domain:"visual-accessibility",schema:jd,streaming:!0,timeout:3e5};visualTester=null;async getService(e){if(!this.visualTester){let t=e.memory??await O(),n=await U(e);this.visualTester=Ls({memory:t,llmRouter:n})}return this.visualTester}async execute(e,t){let{urls:n,viewports:r=[{width:1920,height:1080,name:"desktop"}],baselineDir:i=".visual-baselines",threshold:s=.1,fullPage:a=!0}=e;try{if(this.emitStream(t,{status:"capturing",message:`Capturing ${n.length} URLs across ${r.length} viewports`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};this.markAsRealData();let c=await this.getService(t),l=[],u=[];for(let m of n)for(let p of r){this.emitStream(t,{status:"comparing",message:`Comparing ${m} at ${p.width}x${p.height}`});let g={width:p.width,height:p.height,deviceScaleFactor:1,isMobile:p.isMobile||!1,hasTouch:p.isMobile||!1},f=await c.captureScreenshot(m,{viewport:g,fullPage:a});if(!f.success){l.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let h=f.value,v=await c.getBaseline(m,g);if(!v)await c.setBaseline(h),u.push(h.path.value),l.push({url:m,viewport:p,status:"new",diffPercentage:0,diffPixels:0,screenshotPath:h.path.value});else{let y=await c.compare(h,v.id);if(!y.success){l.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let C=y.value,b=C.diffPercentage<=s;l.push({url:m,viewport:p,status:b?"passed":"failed",diffPercentage:C.diffPercentage,diffPixels:C.diffPixels,screenshotPath:h.path.value,baselinePath:v.path.value,diffImagePath:C.diffImagePath?.value,regions:C.regions?.map(w=>({x:w.x,y:w.y,width:w.width,height:w.height,changeType:w.changeType,significance:w.significance}))})}}let d={total:l.length,passed:l.filter(m=>m.status==="passed").length,failed:l.filter(m=>m.status==="failed").length,new:l.filter(m=>m.status==="new").length,avgDiffPercentage:l.length>0?l.reduce((m,p)=>m+p.diffPercentage,0)/l.length:0};return this.emitStream(t,{status:"complete",message:`Visual comparison complete: ${d.passed}/${d.total} passed`,progress:100}),{success:!0,data:{comparisons:l,summary:d,newBaselines:u,recommendations:Bd(l,d)}}}catch(c){return{success:!1,error:`Visual comparison failed: ${E(c)}`}}}},Xn=class extends A{config={name:"qe/a11y/audit",description:"WCAG accessibility auditing with violation detection, contrast checking, and keyboard navigation testing.",domain:"visual-accessibility",schema:zd,streaming:!0,timeout:18e4};accessibilityTester=null;async getService(e){if(!this.accessibilityTester){let t=e.memory;this.accessibilityTester=new qs(t||await O(),{enableColorContrastCheck:!0,enableKeyboardCheck:!0})}return this.accessibilityTester}async execute(e,t){let{urls:n,standard:r="wcag21-aa",includeWarnings:i=!0,checkContrast:s=!0,checkKeyboard:a=!0}=e;try{if(this.emitStream(t,{status:"auditing",message:`Auditing ${n.length} URLs against ${r}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};this.markAsRealData();let c=await this.getService(t),l=[],u=Ud(r);for(let g of n){this.emitStream(t,{status:"scanning",message:`Scanning ${g}`});let f=await c.audit(g,{wcagLevel:u,includeWarnings:i});if(!f.success){l.push({url:g,score:0,passed:!1,violations:[],warnings:[],passedRules:0});continue}let h=f.value,v=[];if(s){let T=await c.checkContrast(g);if(T.success){let S=T.value.filter(x=>!x.passes);S.length>0&&(v=S.map(x=>({id:"color-contrast",impact:"serious",description:"Elements must have sufficient color contrast",help:`Element ${x.element} has contrast ratio ${x.ratio}:1 but requires ${x.requiredRatio}:1`,helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum",wcagCriteria:["1.4.3"],nodes:[{selector:x.element,html:`<${x.element.replace(".",' class="')}>...</${x.element.split(".")[0]}>`,failureSummary:`Contrast ratio ${x.ratio}:1 is below required ${x.requiredRatio}:1`,fixSuggestion:`Change foreground color to achieve at least ${x.requiredRatio}:1 contrast`}]})))}}let y=[];if(a){let T=await c.checkKeyboardNavigation(g);if(T.success){let S=T.value;for(let x of S.issues)y.push({id:x.type,impact:x.type==="no-focus-indicator"?"serious":"moderate",description:x.description,help:"Ensure keyboard navigation is fully supported",helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/focus-visible",wcagCriteria:["2.4.7"],nodes:[{selector:x.selector,html:`<element>${x.selector}</element>`,failureSummary:x.description,fixSuggestion:"Add visible focus styles with :focus or :focus-visible"}]});for(let x of S.traps)y.push({id:"keyboard-trap",impact:"critical",description:x.description,help:x.escapePath||"No escape path available",helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/no-keyboard-trap",wcagCriteria:["2.1.2"],nodes:[{selector:x.selector,html:`<element>${x.selector}</element>`,failureSummary:x.description,fixSuggestion:x.escapePath}]})}}let C=[...h.violations.map(T=>({id:T.id,impact:T.impact,description:T.description,help:T.help,helpUrl:T.helpUrl,wcagCriteria:T.wcagCriteria.map(S=>S.id),nodes:T.nodes.map(S=>({selector:S.selector,html:S.html,failureSummary:S.failureSummary,fixSuggestion:S.fixSuggestion}))})),...v,...y],b=h.incomplete.map(T=>({id:T.id,description:T.description,nodes:T.nodes.length})),w=C.some(T=>T.impact==="critical"||T.impact==="serious");l.push({url:g,score:h.score,passed:!w,violations:C,warnings:b,passedRules:h.passes.length})}let d={totalUrls:l.length,passingUrls:l.filter(g=>g.passed).length,avgScore:l.length>0?Math.round(l.reduce((g,f)=>g+f.score,0)/l.length):0,criticalViolations:l.reduce((g,f)=>g+f.violations.filter(h=>h.impact==="critical").length,0),seriousViolations:l.reduce((g,f)=>g+f.violations.filter(h=>h.impact==="serious").length,0),totalViolations:l.reduce((g,f)=>g+f.violations.length,0)},m=Hd(l),p=Vd(m);return this.emitStream(t,{status:"complete",message:`Audit complete: avg score ${d.avgScore}%`,progress:100}),{success:!0,data:{audits:l,summary:d,topIssues:m,remediationPlan:p}}}catch(c){return{success:!1,error:`Accessibility audit failed: ${E(c)}`}}}},jd={type:"object",properties:{urls:{type:"array",description:"URLs to capture and compare",items:{type:"string",description:"URL"}},viewports:{type:"array",description:"Viewport configurations",items:{type:"object",description:"Viewport",properties:{width:{type:"number",description:"Width in pixels"},height:{type:"number",description:"Height in pixels"},name:{type:"string",description:"Viewport name"}}}},baselineDir:{type:"string",description:"Directory for baseline images",default:".visual-baselines"},threshold:{type:"number",description:"Acceptable diff percentage (0-1)",minimum:0,maximum:1,default:.1},fullPage:{type:"boolean",description:"Capture full page",default:!0},hideSelectors:{type:"array",description:"CSS selectors to hide before capture",items:{type:"string",description:"Selector"}},waitForSelector:{type:"string",description:"Wait for selector before capture"}},required:["urls"]},zd={type:"object",properties:{urls:{type:"array",description:"URLs to audit",items:{type:"string",description:"URL"}},standard:{type:"string",description:"WCAG standard to validate against",enum:["wcag21-aa","wcag21-aaa","wcag22-aa","section508"],default:"wcag21-aa"},includeWarnings:{type:"boolean",description:"Include warnings in results",default:!0},checkContrast:{type:"boolean",description:"Check color contrast",default:!0},checkKeyboard:{type:"boolean",description:"Check keyboard navigation",default:!0},rules:{type:"array",description:"Specific rules to check",items:{type:"string",description:"Rule ID"}}},required:["urls"]};function Ud(o){return o==="wcag21-aaa"?"AAA":"AA"}function Bd(o,e){let t=[];return e.failed>0&&t.push(`Review ${e.failed} failed comparisons for intentional vs unintentional changes`),e.new>0&&t.push(`${e.new} new baselines created - review and approve if correct`),e.avgDiffPercentage>1&&t.push("Consider increasing diff threshold or reviewing major changes"),t.length>0?t:["All visual tests passed"]}function Hd(o){let e=new Map;for(let t of o)for(let n of t.violations){let r=e.get(n.id);r?(r.occurrences++,r.affectedUrls.includes(t.url)||r.affectedUrls.push(t.url)):e.set(n.id,{ruleId:n.id,description:n.description,occurrences:1,impact:n.impact,affectedUrls:[t.url]})}return Array.from(e.values()).sort((t,n)=>n.occurrences-t.occurrences)}function Vd(o){return o.map((e,t)=>({violationId:e.ruleId,description:e.description,fix:`Fix ${e.ruleId} across ${e.occurrences} occurrences`,effort:e.occurrences>10?"moderate":"minor",priority:t+1}))}k();var Yn=class extends A{config={name:"qe/chaos/inject",description:"Inject faults for chaos engineering. Supports latency, errors, CPU/memory stress, network issues, and more.",domain:"chaos-resilience",schema:Qd,streaming:!0,timeout:3e5};chaosEngineer=null;async getService(e){if(!this.chaosEngineer){let t=e.memory||await O(),n=await U(e);this.chaosEngineer=new $s({memory:t,llmRouter:n},{enableDryRun:!0,autoRollbackOnFailure:!0})}return this.chaosEngineer}async execute(e,t){let{faultType:n,target:r,duration:i=3e4,intensity:s=50,dryRun:a=!0,hypothesis:c,rollbackOnFailure:l=!0}=e,u=await this.getService(t);try{if(this.emitStream(t,{status:"preparing",message:`Preparing ${n} fault injection on ${r}`,dryRun:a}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let d=t.requestId||G(),m=this.buildExperiment(d,n,r,i,s,c,l);this.emitStream(t,{status:"verifying",message:"Verifying steady state"});let p=await u.verifySteadyState(m.steadyState),g=p.success&&p.value;if(!g&&!a)return{success:!1,error:"Steady state verification failed. System not in healthy state for chaos experiment."};let f=await u.createExperiment(m);if(!f.success)return{success:!1,error:`Failed to create experiment: ${f.error.message}`};this.emitStream(t,{status:"injecting",message:a?`[DRY RUN] Simulating ${n} fault`:`Injecting ${n} fault`});let h=!1,v,y="pending",C=[],b={faultDuration:i,targetAffected:!a};if(a)h=!1,y="completed",b=this.simulateMetrics(n,i,s),c&&(v=this.validateHypothesisText(c,b,C));else{let S=await u.runExperiment(d);if(S.success){let x=S.value;h=x.faultResults.some(F=>F.injected),v=x.hypothesisValidated,y=x.status;for(let F of x.incidents)C.push(this.convertIncident(F));b=this.extractMetrics(x,n,i)}else y="failed",C.push({type:"error",severity:"critical",message:S.error.message,timestamp:new Date().toISOString(),resolved:!1})}this.emitStream(t,{status:"monitoring",message:"Monitoring system behavior"});let w=this.collectIntensityIncidents(n,s,a);C.push(...w),!a&&C.some(S=>S.severity==="critical"&&!S.resolved)&&(y=l?"rolled-back":"failed");let T=this.generateRecommendations(n,b,C,v);return this.emitStream(t,{status:"complete",message:`Chaos experiment ${y}`,progress:100}),{success:!0,data:{experimentId:d,status:y,faultInjected:h,hypothesisValidated:v,steadyStateVerified:g,metrics:b,incidents:C,recommendations:T}}}catch(d){return{success:!1,error:`Chaos injection failed: ${E(d)}`}}}buildExperiment(e,t,n,r,i,s,a=!0){let c={id:`fault-${e}`,type:t,target:{type:"service",selector:n},duration:r,parameters:this.buildFaultParameters(t,i)},l={description:`Steady state for ${n}`,probes:[{name:"target-health",type:n.startsWith("http")?"http":"command",target:n.startsWith("http")?n:`echo "checking ${n}"`,expected:n.startsWith("http")?200:"OK",timeout:5e3}]},u=s||`System should remain stable under ${t} fault`;return{id:e,name:`${t}-experiment-${Date.now()}`,description:`Chaos experiment: ${t} on ${n}`,hypothesis:{statement:u,metrics:[{metric:t==="latency"?"response_time":"error_rate",operator:"lt",value:t==="latency"?5e3:50}],tolerances:[{metric:"availability",maxDeviation:20,unit:"percent"}]},steadyState:l,faults:[c],blastRadius:{scope:"single",maxAffected:1,excludeProduction:!0},rollbackPlan:{automatic:a,triggerConditions:[{type:"error-rate",condition:"error_rate > 50%"}],steps:[{order:1,action:"remove-fault",target:c.id,timeout:1e4}]},schedule:{type:"once"}}}buildFaultParameters(e,t){let n={};switch(e){case"latency":n.latencyMs=100+t*20;break;case"error":n.errorCode=500,n.errorRate=t/100;break;case"timeout":n.timeoutMs=5e3+t*250;break;case"cpu-stress":n.cpuPercent=t,n.cores=Math.max(1,Math.floor(t/25));break;case"memory-stress":n.memoryBytes=t/100*512*1024*1024;break;case"network-partition":n.partitionPercent=t;break;case"packet-loss":n.packetLossPercent=t;break;case"dns-failure":n.failureRate=t/100;break;case"process-kill":n.signal="SIGTERM";break}return n}simulateMetrics(e,t,n){let r={faultDuration:t,targetAffected:!1,recoveryTime:5e3+n*100};switch(e){case"latency":r.latencyP99=100+n*25;break;case"error":case"timeout":r.errorRate=n*.5;break;case"cpu-stress":case"memory-stress":r.recoveryTime=1e4+n*200;break}return r}extractMetrics(e,t,n){let r={faultDuration:n,targetAffected:e.faultResults.some(c=>c.injected&&c.affectedTargets>0)},i=e.metrics;e.endTime&&e.startTime&&(r.recoveryTime=e.endTime.getTime()-e.startTime.getTime());let s=i.find(c=>c.name.includes("latency")||c.name.includes("response"));s&&(r.latencyP99=s.value);let a=i.find(c=>c.name.includes("error")||c.name.includes("failure"));return a&&(r.errorRate=a.value),r}convertIncident(e){return{type:e.type,severity:e.severity,message:e.message,timestamp:e.timestamp instanceof Date?e.timestamp.toISOString():String(e.timestamp),resolved:e.resolved}}collectIntensityIncidents(e,t,n){let r=[];return n&&(t>70&&r.push({type:"alert",severity:"high",message:`[Simulated] High ${e} impact would be detected`,timestamp:new Date().toISOString(),resolved:!0}),t>90&&r.push({type:"degradation",severity:"critical",message:"[Simulated] Service degradation would occur",timestamp:new Date().toISOString(),resolved:!0})),r}validateHypothesisText(e,t,n){let r=e.toLowerCase();if(r.includes("recover")&&t.recoveryTime){let i=e.match(/(\d+)s/);if(i){let s=parseInt(i[1])*1e3;return t.recoveryTime<=s}}return r.includes("no critical")?!n.some(i=>i.severity==="critical"&&!i.resolved):r.includes("stable")||r.includes("remain")?!n.some(i=>i.severity==="critical"&&!i.resolved):!n.some(i=>i.severity==="critical"&&!i.resolved)}generateRecommendations(e,t,n,r){let i=[];switch(r===!1&&i.push("Hypothesis was not validated - review resilience patterns"),t.recoveryTime&&t.recoveryTime>3e4&&i.push("Recovery time exceeds 30s - consider adding circuit breakers"),t.errorRate&&t.errorRate>20&&i.push("High error rate observed - implement retry with backoff"),n.some(s=>s.severity==="critical")&&i.push("Critical incidents occurred - review fault tolerance mechanisms"),e){case"latency":t.latencyP99&&t.latencyP99>1e3&&i.push("P99 latency exceeds 1s - consider timeout configurations");break;case"network-partition":i.push("Ensure services can operate in degraded mode during network issues");break;case"cpu-stress":case"memory-stress":i.push("Review resource limits and auto-scaling policies");break;case"error":i.push("Implement proper error handling and fallback mechanisms");break;case"timeout":i.push("Configure appropriate timeout values and circuit breakers");break}return i.length===0&&i.push("System showed good resilience - continue regular chaos experiments"),i}},Qd={type:"object",properties:{faultType:{type:"string",description:"Type of fault to inject",enum:["latency","error","timeout","cpu-stress","memory-stress","network-partition","packet-loss","dns-failure","process-kill"]},target:{type:"string",description:"Target service, pod, or endpoint"},duration:{type:"number",description:"Fault duration in milliseconds",minimum:1e3,maximum:3e5,default:3e4},intensity:{type:"number",description:"Fault intensity (0-100)",minimum:0,maximum:100,default:50},dryRun:{type:"boolean",description:"Simulate without actual injection",default:!0},hypothesis:{type:"string",description:'Hypothesis to validate (e.g., "System should recover within 30s")'},rollbackOnFailure:{type:"boolean",description:"Auto-rollback on critical failure",default:!0}},required:["faultType","target"]};k();mt();var wt=class extends A{config={name:"qe/learning/optimize",description:"Cross-domain learning, pattern recognition, strategy optimization, and knowledge transfer.",domain:"learning-optimization",schema:Wd,streaming:!0,timeout:3e5};learningCoordinator=null;metricsOptimizer=null;transferSpecialist=null;async getServices(e){if(!this.learningCoordinator||!this.metricsOptimizer||!this.transferSpecialist){let t=e.memory||await O(),n=await U(e);this.learningCoordinator=new Gs({memory:t,llmRouter:n}),this.metricsOptimizer=new zs(t),this.transferSpecialist=new js(t)}return{learningCoordinator:this.learningCoordinator,metricsOptimizer:this.metricsOptimizer,transferSpecialist:this.transferSpecialist}}async execute(e,t){let{action:n,domain:r,experienceIds:i,targetDomain:s,objective:a}=e;try{if(this.emitStream(t,{status:"processing",message:`Executing ${n} action`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let c={action:n};switch(n){case"learn":c.learnResult=await this.executeLearn(r,i,t);break;case"optimize":if(!a)return{success:!1,error:"Objective is required for optimize action"};c.optimizeResult=await this.executeOptimize(r,a,t);break;case"transfer":if(!r||!s)return{success:!1,error:"Both domain and targetDomain are required for transfer action"};c.transferResult=await this.executeTransfer(r,s,t);break;case"patterns":c.patternResult=await this.executePatterns(r,t);break;case"dashboard":c.dashboardResult=await this.executeDashboard(t);break;default:return{success:!1,error:`Unknown action: ${n}`}}return this.emitStream(t,{status:"complete",message:`${n} complete`,progress:100}),{success:!0,data:c}}catch(c){return{success:!1,error:`Learning optimization failed: ${E(c)}`}}}async executeLearn(e,t,n){let r=e||"learning-optimization";if(this.isDemoMode(n))return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoLearnResult(r);let{learningCoordinator:i}=await this.getServices(n);this.emitStream(n,{status:"learning",message:`Learning from ${t?.length||"recent"} experiences`});let s=gt.lastNDays(7),a=await i.mineExperiences(r,s),c=[],l=0,u=0;if(a.success){l=a.value.experienceCount;for(let d of a.value.patterns)c.push({id:d.id,type:d.type,name:d.name,description:d.description,confidence:d.confidence,usageCount:d.usageCount,successRate:d.successRate});u=a.value.successRate>.5?(a.value.successRate-.5)*20:0}return t&&t.length>0&&(l=t.length),c.length===0?(this.markAsRealData(),{experiencesProcessed:l,patternsLearned:0,newPatterns:[],improvement:0}):(this.markAsRealData(),{experiencesProcessed:l,patternsLearned:c.length,newPatterns:c,improvement:u})}getDemoLearnResult(e){return{experiencesProcessed:150,patternsLearned:12,newPatterns:[{id:`pattern-${e}-001`,type:"optimization",name:"Parallel Execution Pattern",description:`Optimal parallelism settings discovered for ${e}`,confidence:.92,usageCount:45,successRate:.87},{id:`pattern-${e}-002`,type:"retry",name:"Exponential Backoff Pattern",description:"Effective retry strategy for flaky operations",confidence:.88,usageCount:32,successRate:.91},{id:`pattern-${e}-003`,type:"caching",name:"Result Caching Pattern",description:"Cache frequently computed results for faster access",confidence:.85,usageCount:28,successRate:.82}],improvement:15.5}}async executeOptimize(e,t,n){let{learningCoordinator:r,metricsOptimizer:i}=await this.getServices(n);this.emitStream(n,{status:"optimizing",message:`Optimizing for ${t.metric}`});let s=e||"learning-optimization",a=gt.lastNDays(30),c=await r.mineExperiences(s,a),l=[];if(c.success&&c.value.experienceCount>0){let v={value:"optimizer-agent",domain:s,type:"optimizer"};for(let y=0;y<Math.min(c.value.experienceCount,20);y++)l.push({id:`exp-${y}`,agentId:v,domain:s,action:"optimize",state:{context:{},metrics:{}},result:{success:oe()>.3,outcome:{[t.metric]:ce(70,100)},duration:ce(1e3,6e3)},reward:c.value.avgReward,timestamp:new Date})}let u={name:`${s}-current`,parameters:{parallelism:4,retryCount:3,timeout:3e4},expectedOutcome:{[t.metric]:70}},d=(t.constraints||[]).map(v=>({metric:v.metric,operator:v.operator,value:v.value})),m={metric:t.metric,direction:t.direction,constraints:d},p=u,g=0,f=.5,h=[];if(l.length>=20){let v=await i.optimizeStrategy(u,m,l);v.success&&(p={name:v.value.optimizedStrategy.name,parameters:v.value.optimizedStrategy.parameters,expectedOutcome:v.value.optimizedStrategy.expectedOutcome},g=v.value.improvement*100,f=v.value.confidence,h=v.value.validationResults)}else{let v={tags:[s,t.metric]},y=await i.recommendStrategy(v);y.success&&(p={name:y.value.name,parameters:y.value.parameters,expectedOutcome:y.value.expectedOutcome})}return{strategiesEvaluated:l.length>0?Math.min(l.length,12):1,bestStrategy:p,improvement:g,confidence:f,validationResults:h}}async executeTransfer(e,t,n){let{transferSpecialist:r}=await this.getServices(n);this.emitStream(n,{status:"transferring",message:`Transferring knowledge from ${e} to ${t}`});let i=await r.queryKnowledge({domain:e,minRelevance:.5,limit:50}),s=0,a=0,c=0,l=0;if(i.success){s=i.value.length;for(let d of i.value){let m=await r.transferKnowledge(d,t);m.success&&(a++,l+=m.value.relevanceScore,Math.abs(m.value.relevanceScore-d.relevanceScore)>.1&&c++)}}let u=s>0?a/s:0;return{sourcePatterns:s,transferredPatterns:a,adaptedPatterns:c,successRate:u,targetDomainUpdated:a>0}}async executePatterns(e,t){let{learningCoordinator:n}=await this.getServices(t),r=await this.getSONASnapshot(t);this.emitStream(t,{status:"analyzing",message:`Analyzing patterns${e?` for ${e}`:""}`});let i=await n.getPatternStats(e);if(!i.success)return{totalPatterns:0,byType:{},byDomain:{},topPatterns:[],avgConfidence:0,avgSuccessRate:0,sona:r};let s=i.value,a=s.topPatterns.map(c=>({id:c.id,type:c.type,name:c.name,description:c.description,confidence:c.confidence,usageCount:c.usageCount,successRate:c.successRate}));return{totalPatterns:s.totalPatterns,byType:s.byType,byDomain:s.byDomain,topPatterns:a,avgConfidence:s.avgConfidence,avgSuccessRate:s.avgSuccessRate,sona:r}}async executeDashboard(e){let{learningCoordinator:t,transferSpecialist:n}=await this.getServices(e),r=await this.getSONASnapshot(e);this.emitStream(e,{status:"aggregating",message:"Aggregating learning metrics"});let i=await t.getPatternStats(),s=await n.queryKnowledge({minRelevance:0,limit:1e3}),a=gt.lastNDays(1),c=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","learning-optimization"],l=0,u=[];for(let y of c){let C=await t.mineExperiences(y,a);C.success&&(l+=C.value.experienceCount,C.value.experienceCount>0&&u.push({domain:y,successRate:C.value.successRate}))}u.sort((y,C)=>C.successRate-y.successRate);let d=u.slice(0,3).map(y=>y.domain),m=i.success?i.value.totalPatterns:0,p=i.success?i.value.avgSuccessRate:0,g=p,f=[],h=new Date;for(let y=6;y>=0;y--){let C=new Date(h.getTime()-y*24*60*60*1e3),b=new Date(C.getTime()+1440*60*1e3),w=gt.create(C,b),T=0;for(let S of c.slice(0,3)){let x=await t.mineExperiences(S,w);x.success&&(T+=x.value.patterns.length)}f.push({timestamp:C.toISOString(),metric:"patterns-learned",value:T})}let v=[];return m>=100&&v.push({name:`Reached ${Math.floor(m/50)*50} patterns`,achievedAt:new Date(h.getTime()-2880*60*1e3).toISOString(),domain:"learning-optimization"}),p>=.8&&v.push({name:`${Math.round(p*100)}% pattern success rate`,achievedAt:new Date(h.getTime()-7200*60*1e3).toISOString(),domain:d[0]||"learning-optimization"}),{overallLearningRate:g,totalPatterns:m,totalKnowledge:s.success?s.value.length:0,experiencesLast24h:l,topPerformingDomains:d.length>0?d:["test-generation"],learningTrend:f,recentMilestones:v,sona:r}}async getSONASnapshot(e){let t=e.kernel?.getDomainAPI("learning-optimization");if(!t?.isSONAAvailable())return{available:!1,stats:null};try{return{available:!0,stats:await t.getSONAPersistedStats()}}catch(n){return this.logger.warn("Failed to read persisted SONA statistics",{requestId:e.requestId,error:E(n)}),{available:!1,stats:null}}}},Wd={type:"object",properties:{action:{type:"string",description:"Learning action to perform",enum:["learn","optimize","transfer","patterns","dashboard"]},domain:{type:"string",description:"Source domain for learning/optimization",enum:["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"]},experienceIds:{type:"array",description:"Specific experience IDs to learn from",items:{type:"string",description:"Experience ID"}},targetDomain:{type:"string",description:"Target domain for knowledge transfer"},objective:{type:"object",description:"Optimization objective",properties:{metric:{type:"string",description:"Metric to optimize"},direction:{type:"string",description:"maximize or minimize",enum:["maximize","minimize"]},constraints:{type:"array",description:"Optimization constraints",items:{type:"object",description:"Constraint"}}}}},required:["action"]};k();var Kd={type:"object",properties:{action:{type:"string",enum:["dream","insights","apply","history","status"],description:"Action to perform: dream (run cycle), insights (view pending), apply (create pattern), history (view past), status (current state)"},durationMs:{type:"number",description:"Duration of dream cycle in milliseconds (default: 30000, max: 60000)",default:3e4},minPatterns:{type:"number",description:"Minimum patterns required to start dreaming (default: 10)",default:10},insightId:{type:"string",description:"Insight ID to apply (required for apply action)"},limit:{type:"number",description:"Maximum results to return (default: 20)",default:20},loadFromReasoningBank:{type:"boolean",description:"Load patterns from ReasoningBank before dreaming (default: true)",default:!0}},required:["action"]},Rt=class extends A{config={name:"qe/learning/dream",description:"Trigger dream cycles for pattern discovery. Dreams find novel associations between patterns through spreading activation, generating actionable insights.",domain:"learning-optimization",schema:Kd,streaming:!1,timeout:12e4};engine=null;engineConfig=null;async getEngine(e){return this.engine&&e&&!this.configsEqual(this.engineConfig,e)&&this.engine&&(await this.engine.close().catch(()=>{}),this.engine=null,this.engineConfig=null),this.engine||(this.engine=ns(e),this.engineConfig=e||null,await this.engine.initialize()),this.engine}configsEqual(e,t){return e===t?!0:!e||!t?!1:e.maxDurationMs===t.maxDurationMs&&e.minConceptsRequired===t.minConceptsRequired}async loadPatternsFromReasoningBank(e){try{let t=await O(),n=hr(t);await n.initialize();try{let{getSharedRvfDualWriter:a}=await import("./shared-rvf-dual-writer-4BGDVPQ7.js"),c=await a();c&&n.setRvfDualWriter(c)}catch(a){process.env.DEBUG&&this.logger.info("RVF wiring skipped",{error:String(a)})}let r=await n.searchPatterns("",{limit:100,minConfidence:.3});if(!r.success||!r.value.length)return this.logger.info("No patterns found in ReasoningBank to load"),0;let i=r.value.map(a=>({id:a.pattern.id,name:a.pattern.name,description:a.pattern.description||`${a.pattern.patternType} pattern`,domain:a.pattern.qeDomain||"learning-optimization",patternType:a.pattern.patternType,confidence:a.pattern.confidence,successRate:a.pattern.successRate||.5})),s=await e.loadPatternsAsConcepts(i);return this.logger.info(`Loaded ${s} patterns as concepts from ReasoningBank`),s}catch(t){return this.logger.warn("Failed to load patterns from ReasoningBank",{error:String(t)}),0}}async execute(e,t){let{action:n}=e;try{switch(n){case"dream":return this.runDreamCycle(e,t);case"insights":return this.getPendingInsights(e,t);case"apply":return this.applyInsight(e,t);case"history":return this.getDreamHistory(e,t);case"status":return this.getDreamStatus(e,t);default:return{success:!1,error:`Unknown action: ${n}`,data:{action:n,success:!1,error:`Unknown action: ${n}`}}}}catch(r){let i=E(r);return{success:!1,error:i,data:{action:n,success:!1,error:i}}}}async runDreamCycle(e,t){let n=Math.min(e.durationMs||3e4,6e4),r=e.minPatterns||10,i=e.loadFromReasoningBank!==!1;this.logger.info(`Starting dream cycle (${n}ms, min: ${r} patterns)`);let s=await this.getEngine({maxDurationMs:n,minConceptsRequired:r});if(i){let u=await this.loadPatternsFromReasoningBank(s);this.logger.info(`Loaded ${u} patterns from ReasoningBank`)}let a=await s.dream(n),c={cycleId:a.cycle.id,status:a.cycle.status,durationMs:a.cycle.durationMs||0,conceptsProcessed:a.cycle.conceptsProcessed,associationsFound:a.cycle.associationsFound,insightsGenerated:a.cycle.insightsGenerated,activationStats:a.activationStats,patternsCreated:a.patternsCreated},l=a.insights.map(u=>({id:u.id,type:u.type,description:u.description,noveltyScore:u.noveltyScore,confidenceScore:u.confidenceScore,actionable:u.actionable,applied:u.applied||!1,suggestedAction:u.suggestedAction,createdAt:u.createdAt?.toISOString()||new Date().toISOString()}));return this.logger.info(`Dream cycle complete: ${a.cycle.insightsGenerated} insights, ${a.cycle.associationsFound} associations found`),{success:!0,data:{action:"dream",success:!0,dreamResult:c,insights:l}}}async getPendingInsights(e,t){let n=e.limit||20;return{success:!0,data:{action:"insights",success:!0,insights:(await(await this.getEngine()).getPendingInsights(n)).map(a=>({id:a.id,type:a.type,description:a.description,noveltyScore:a.noveltyScore,confidenceScore:a.confidenceScore,actionable:a.actionable,applied:a.applied||!1,suggestedAction:a.suggestedAction,createdAt:a.createdAt?.toISOString()||new Date().toISOString()}))}}}async applyInsight(e,t){if(!e.insightId)return{success:!1,error:"insightId is required for apply action",data:{action:"apply",success:!1,error:"insightId is required for apply action"}};try{let r=await(await this.getEngine()).applyInsight(e.insightId);return r.success?(this.logger.info(`Applied insight ${e.insightId} \u2192 REAL pattern ${r.patternId} in ReasoningBank`),{success:!0,data:{action:"apply",success:!0,applyResult:{insightId:e.insightId,...r}}}):{success:!1,error:r.error,data:{action:"apply",success:!1,error:r.error}}}catch(n){let r=E(n);return{success:!1,error:r,data:{action:"apply",success:!1,error:r}}}}async getDreamHistory(e,t){let n=e.limit||20;return{success:!0,data:{action:"history",success:!0,history:(await(await this.getEngine()).getDreamHistory(n)).map(a=>({id:a.id,startTime:a.startTime.toISOString(),endTime:a.endTime?.toISOString(),durationMs:a.durationMs,status:a.status,conceptsProcessed:a.conceptsProcessed,associationsFound:a.associationsFound,insightsGenerated:a.insightsGenerated}))}}}async getDreamStatus(e,t){let n=await this.getEngine(),r=n.isDreaming(),i=n.getCurrentCycle(),s=await n.getDreamHistory(100),a=await n.getPendingInsights(100),c=s.reduce((d,m)=>d+m.insightsGenerated,0),l=s[0];return{success:!0,data:{action:"status",success:!0,status:{isDreaming:r,currentCycle:i?{id:i.id,startTime:i.startTime.toISOString(),endTime:i.endTime?.toISOString(),durationMs:i.durationMs,status:i.status,conceptsProcessed:i.conceptsProcessed,associationsFound:i.associationsFound,insightsGenerated:i.insightsGenerated}:void 0,totalCycles:s.length,totalInsights:c,pendingInsights:a.length,lastDreamTime:l?.startTime.toISOString()}}}}resetInstanceCache(){this.engine&&(this.engine.close().catch(console.error),this.engine=null)}};k();var Jn=class extends A{config={name:"qe/analysis/token_usage",description:"Analyze token consumption patterns and identify optimization opportunities across agents and domains.",domain:"learning-optimization",schema:Xd,streaming:!1,timeout:3e4};async execute(e,t){let{operation:n,timeframe:r,agentId:i,domain:s}=e;try{if(this.isAborted(t))return{success:!1,error:"Operation aborted"};let a;switch(n){case"session":a=this.getSessionUsage(r);break;case"agent":a=this.getAgentUsage(i,r);break;case"domain":a=this.getDomainUsage(s,r);break;case"task":a=this.getTaskUsage(r);break;case"efficiency":a=this.getEfficiencyReport(r);break;case"dashboard":return{success:!0,data:{operation:"dashboard",timeframe:r||"all",summary:{totalTokens:0,totalCost:"$0.00",tokensSaved:0,savingsPercentage:0},optimization:{patternsReused:0,cacheHits:0,earlyExits:0,recommendations:[Yi()]}}};default:return{success:!1,error:`Unknown operation: ${n}`}}return{success:!0,data:a}}catch(a){return{success:!1,error:`Token usage analysis failed: ${E(a)}`}}}getSessionUsage(e){let t=ie.getSessionSummary(e),n={};for(let[i,s]of t.byAgent)n[i]={tokens:s.totalTokens,cost:W(s.totalCost),tasks:s.tasksExecuted};let r={};for(let[i,s]of t.byDomain)r[i]={tokens:s.totalTokens,cost:W(s.estimatedCostUsd||0)};return{operation:"session",timeframe:e||"all",summary:{totalTokens:t.totalUsage.totalTokens,totalCost:W(t.totalUsage.estimatedCostUsd||0),tokensSaved:t.optimizationStats.tokensSaved,savingsPercentage:t.optimizationStats.savingsPercentage},breakdown:{byAgent:Object.keys(n).length>0?n:void 0,byDomain:Object.keys(r).length>0?r:void 0},optimization:{patternsReused:t.optimizationStats.patternsReused,cacheHits:t.optimizationStats.cacheHits,earlyExits:t.optimizationStats.earlyExits,recommendations:this.generateSessionRecommendations(t)}}}getAgentUsage(e,t){let n=ie.getAgentMetrics(e,t),r=ie.getSessionSummary(t);if(e&&!Array.isArray(n)){let d=n,m=d.tasksExecuted>0?d.patternsReused/d.tasksExecuted:0;return{operation:"agent",timeframe:t||"all",summary:{totalTokens:d.totalTokens,totalCost:W(d.totalCost),tokensSaved:d.estimatedTokensSaved,savingsPercentage:this.calculateSavingsPercentage(d.totalTokens,d.estimatedTokensSaved)},optimization:{patternsReused:d.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateAgentRecommendations(d)},details:{agentMetrics:{agentId:d.agentId,totalInputTokens:d.totalInputTokens,totalOutputTokens:d.totalOutputTokens,totalTokens:d.totalTokens,totalCost:W(d.totalCost),tasksExecuted:d.tasksExecuted,patternsReused:d.patternsReused,tokensSaved:d.estimatedTokensSaved,efficiency:Math.round(m*100)}}}}let i=Array.isArray(n)?n:[n],s={},a=0,c=0,l=0,u=0;for(let d of i)s[d.agentId]={tokens:d.totalTokens,cost:W(d.totalCost),tasks:d.tasksExecuted},a+=d.totalTokens,c+=d.totalCost,l+=d.estimatedTokensSaved,u+=d.patternsReused;return{operation:"agent",timeframe:t||"all",summary:{totalTokens:a,totalCost:W(c),tokensSaved:l,savingsPercentage:this.calculateSavingsPercentage(a,l)},breakdown:{byAgent:Object.keys(s).length>0?s:void 0},optimization:{patternsReused:u,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateMultiAgentRecommendations(i)}}}getDomainUsage(e,t){let n=ie.getDomainMetrics(e,t),r=ie.getSessionSummary(t);if(e&&!(n instanceof Map)){let l=n;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:l.totalTokens,totalCost:W(l.estimatedCostUsd||0),tokensSaved:r.optimizationStats.tokensSaved,savingsPercentage:r.optimizationStats.savingsPercentage},optimization:{patternsReused:r.optimizationStats.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateDomainRecommendations(e,l)},details:{domainMetrics:{domain:e,inputTokens:l.inputTokens,outputTokens:l.outputTokens,totalTokens:l.totalTokens,cost:W(l.estimatedCostUsd||0)}}}}let i=n instanceof Map?n:new Map,s={},a=0,c=0;for(let[l,u]of i)s[l]={tokens:u.totalTokens,cost:W(u.estimatedCostUsd||0)},a+=u.totalTokens,c+=u.estimatedCostUsd||0;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:a,totalCost:W(c),tokensSaved:r.optimizationStats.tokensSaved,savingsPercentage:r.optimizationStats.savingsPercentage},breakdown:{byDomain:Object.keys(s).length>0?s:void 0},optimization:{patternsReused:r.optimizationStats.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateMultiDomainRecommendations(i)}}}getTaskUsage(e){let t=ie.getTaskMetrics(e),n=ie.getSessionSummary(e),r=t.slice(-100).map(i=>({taskId:i.taskId,agentId:i.agentId,domain:i.domain,operation:i.operation,tokens:i.usage.totalTokens,cost:W(i.usage.estimatedCostUsd||0),patternReused:i.patternReused,tokensSaved:i.tokensSaved||0,timestamp:new Date(i.timestamp).toISOString()}));return{operation:"task",timeframe:e||"all",summary:{totalTokens:n.totalUsage.totalTokens,totalCost:W(n.totalUsage.estimatedCostUsd||0),tokensSaved:n.optimizationStats.tokensSaved,savingsPercentage:n.optimizationStats.savingsPercentage},optimization:{patternsReused:n.optimizationStats.patternsReused,cacheHits:n.optimizationStats.cacheHits,earlyExits:n.optimizationStats.earlyExits,recommendations:[`${t.length} tasks analyzed in timeframe`]},details:{taskMetrics:r}}}getEfficiencyReport(e){let t=ie.getEfficiencyReport(e),n=ie.getSessionSummary(e);return{operation:"efficiency",timeframe:e||"all",summary:{totalTokens:t.totalTokensUsed,totalCost:W(t.totalTokensUsed*3e-6+t.totalTokensUsed*15e-6),tokensSaved:t.totalTokensSaved,savingsPercentage:t.savingsPercentage},optimization:{patternsReused:n.optimizationStats.patternsReused,cacheHits:n.optimizationStats.cacheHits,earlyExits:n.optimizationStats.earlyExits,recommendations:t.recommendations}}}generateSessionRecommendations(e){let t=[];if(e.totalUsage.totalTokens===0)return["No token usage recorded yet. Start executing tasks to track consumption."];let{patternsReused:n,cacheHits:r,earlyExits:i,savingsPercentage:s}=e.optimizationStats;return s<10&&t.push("Token savings below 10%. Enable pattern reuse and caching for better efficiency."),n===0&&e.byAgent.size>0&&t.push("No patterns reused. Consider enabling the pattern store for similar tasks."),r===0&&e.totalUsage.totalTokens>1e4&&t.push("No cache hits detected. Enable response caching to reduce API calls."),i===0&&e.byAgent.size>1&&t.push("Early exit optimization not used. Enable high-confidence pattern matching."),s>25&&t.push(`Excellent token efficiency! ${s.toFixed(1)}% savings achieved.`),t.length>0?t:["Token usage is within normal parameters."]}generateAgentRecommendations(e){let t=[];if(e.tasksExecuted===0)return["No tasks executed by this agent yet."];e.patternsReused/e.tasksExecuted<.1&&t.push("Low pattern reuse rate. Consider caching successful patterns.");let r=e.totalTokens/e.tasksExecuted;return r>5e3&&t.push(`High average tokens per task (${Math.round(r)}). Consider optimizing prompts.`),e.totalOutputTokens>e.totalInputTokens*2&&t.push("High output-to-input ratio. Request more concise responses."),t.length>0?t:["Agent token usage is efficient."]}generateMultiAgentRecommendations(e){let t=[];if(e.length===0)return["No agent data available."];let n=[...e].sort((s,a)=>a.totalTokens-s.totalTokens);n[0].totalTokens>0&&t.push(`Highest consumer: ${n[0].agentId} (${n[0].totalTokens.toLocaleString()} tokens)`);let r=e.reduce((s,a)=>s+a.totalTokens,0);return n[0].totalTokens/(r||1)>.5&&e.length>1&&t.push("Token usage imbalanced. Consider distributing workload across agents."),t}generateDomainRecommendations(e,t){let n=[];return t.totalTokens===0?[`No token usage recorded for ${e}.`]:(e==="test-generation"&&t.totalTokens>1e4&&n.push("Test generation consuming significant tokens. Consider batching test requests."),e==="code-intelligence"&&t.outputTokens>t.inputTokens*3&&n.push("Code intelligence generating verbose output. Consider summary-only mode."),n.length>0?n:[`${e} token usage is normal.`])}generateMultiDomainRecommendations(e){let t=[];if(e.size===0)return["No domain data available."];let n=Array.from(e.entries()).sort((r,i)=>i[1].totalTokens-r[1].totalTokens);return n[0][1].totalTokens>0&&t.push(`Highest consuming domain: ${n[0][0]} (${n[0][1].totalTokens.toLocaleString()} tokens)`),t}calculateSavingsPercentage(e,t){let n=e+t;return n===0?0:Math.round(t/n*1e4)/100}},Xd={type:"object",properties:{operation:{type:"string",description:"Type of analysis to perform",enum:["session","agent","domain","task","efficiency","dashboard"]},timeframe:{type:"string",description:"Time period to analyze",enum:["1h","24h","7d","30d"]},agentId:{type:"string",description:"Specific agent ID to analyze (for agent operation)"},domain:{type:"string",description:"Specific domain to analyze (for domain operation)",enum:["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"]}},required:["operation"]};k();function Pt(o){return o===void 0?null:typeof o!="number"||!Number.isInteger(o)||o<1?`constraints.maxSteps must be a positive integer, got ${String(o)}`:null}var Pi={coverage:{line:0,branch:0,function:0,target:80,measured:!1},quality:{testsPassing:0,totalTests:0,securityScore:100,performanceScore:100},fleet:{activeAgents:0,availableAgents:[],maxAgents:8},resources:{timeRemaining:3600,memoryAvailable:4096,parallelSlots:4},context:{environment:"development",riskLevel:"medium"},patterns:{available:0,reusable:0}};var Yd=[{name:"measure-coverage",description:"Run coverage analysis on the codebase to determine current coverage metrics",agentType:"qe-coverage-specialist",preconditions:{"coverage.measured":!1},effects:{"coverage.measured":!0},cost:2,estimatedDurationMs:3e4,successRate:.95,category:"coverage",qeDomain:"coverage-analysis",method:"analyze",params:{},implemented:!0},{name:"analyze-coverage-gaps",description:"Identify uncovered code paths and prioritize them by risk and complexity",agentType:"qe-gap-detector",preconditions:{"coverage.measured":!0},effects:{"coverage.gapsIdentified":!0},cost:1.5,estimatedDurationMs:15e3,successRate:.9,category:"coverage",qeDomain:"coverage-analysis",method:"detectGaps",params:{},implemented:!0},{name:"generate-coverage-tests",description:"Generate tests targeting identified coverage gaps using AI-powered analysis",agentType:"qe-test-generator",preconditions:{"coverage.gapsIdentified":!0},effects:{"coverage.line":{delta:10}},cost:4,estimatedDurationMs:6e4,successRate:.8,category:"coverage",qeDomain:"test-generation",method:"generateTests",params:{},implemented:!0},{name:"run-mutation-testing",description:"Run mutation testing to validate test effectiveness and find weak spots",agentType:"qe-mutation-tester",preconditions:{"coverage.line":{min:60}},effects:{"quality.mutationScore":{set:!0}},cost:5,estimatedDurationMs:12e4,successRate:.85,category:"coverage",qeDomain:"coverage-analysis",implemented:!1},{name:"prioritize-uncovered-paths",description:"Use sublinear O(log n) analysis to identify highest-risk uncovered paths",agentType:"qe-coverage-specialist",preconditions:{"coverage.gapsIdentified":!0},effects:{"coverage.riskPrioritized":!0},cost:1,estimatedDurationMs:1e4,successRate:.92,category:"coverage",qeDomain:"coverage-analysis",method:"calculateRisk",params:{},implemented:!0},{name:"generate-branch-tests",description:"Generate tests specifically targeting branch coverage improvements",agentType:"qe-test-generator",preconditions:{"coverage.measured":!0,"coverage.branch":{max:70}},effects:{"coverage.branch":{delta:8}},cost:3.5,estimatedDurationMs:45e3,successRate:.78,category:"coverage",qeDomain:"test-generation",method:"generateTests",params:{},implemented:!0}],Jd=[{name:"run-unit-tests",description:"Execute unit test suite with parallel execution",agentType:"qe-test-executor",preconditions:{},effects:{"quality.unitTestsRun":!0},cost:1,estimatedDurationMs:2e4,successRate:.95,category:"test",qeDomain:"test-execution",method:"runTests",params:{},implemented:!0},{name:"run-integration-tests",description:"Execute integration test suite with real database connections",agentType:"qe-test-executor",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.integrationTestsRun":!0},cost:2.5,estimatedDurationMs:45e3,successRate:.85,category:"test",qeDomain:"test-execution",method:"execute",params:{},implemented:!0},{name:"run-e2e-tests",description:"Execute end-to-end tests using Playwright or Cypress",agentType:"qe-e2e-tester",preconditions:{"quality.integrationTestsRun":!0},effects:{"quality.e2eTestsRun":!0},cost:4,estimatedDurationMs:9e4,successRate:.8,category:"test",qeDomain:"test-execution",method:"executeE2ETestSuite",params:{},implemented:!0},{name:"fix-failing-tests",description:"Analyze and fix failing tests based on error messages and stack traces",agentType:"qe-tdd-specialist",preconditions:{"quality.testsPassing":{max:90}},effects:{"quality.testsPassing":{delta:10}},cost:3,estimatedDurationMs:3e4,successRate:.75,category:"test",qeDomain:"test-generation",implemented:!1},{name:"fix-flaky-tests",description:"Identify and stabilize flaky tests by analyzing timing and async issues",agentType:"qe-flaky-hunter",preconditions:{"quality.flakyTests":{min:1}},effects:{"quality.flakyTests":{delta:-3}},cost:4,estimatedDurationMs:45e3,successRate:.7,category:"test",qeDomain:"test-execution",method:"detectFlaky",params:{},implemented:!0},{name:"generate-property-tests",description:"Generate property-based tests using fast-check or similar library",agentType:"qe-test-generator",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.propertyTestsGenerated":!0},cost:3.5,estimatedDurationMs:4e4,successRate:.82,category:"test",qeDomain:"test-generation",method:"generatePropertyTests",params:{},implemented:!0},{name:"run-contract-tests",description:"Execute consumer-driven contract tests using Pact or similar",agentType:"qe-contract-tester",preconditions:{"context.hasApiContracts":!0},effects:{"quality.contractTestsRun":!0},cost:2,estimatedDurationMs:25e3,successRate:.88,category:"test",qeDomain:"contract-testing",method:"verifyAllConsumers",params:{},implemented:!0}],Zd=[{name:"security-scan",description:"Run comprehensive security scan using SAST and dependency analysis",agentType:"qe-security-scanner",preconditions:{},effects:{"quality.securityScanned":!0},cost:2,estimatedDurationMs:3e4,successRate:.95,category:"security",qeDomain:"security-compliance",method:"runSecurityAudit",params:{},implemented:!0},{name:"fix-vulnerabilities",description:"Remediate identified security vulnerabilities and update dependencies",agentType:"qe-security-auditor",preconditions:{"quality.securityScanned":!0,"quality.vulnerabilities":{min:1}},effects:{"quality.vulnerabilities":{delta:-5},"quality.securityScore":{delta:10}},cost:5,estimatedDurationMs:6e4,successRate:.7,category:"security",qeDomain:"security-compliance",implemented:!1},{name:"owasp-audit",description:"Perform OWASP Top 10 security audit on the application",agentType:"qe-security-auditor",preconditions:{"quality.securityScanned":!0},effects:{"quality.owaspCompliant":!0},cost:3,estimatedDurationMs:45e3,successRate:.85,category:"security",qeDomain:"security-compliance",method:"runComplianceCheck",params:{standard:"owasp"},implemented:!0},{name:"scan-secrets",description:"Scan codebase for hardcoded secrets and credentials",agentType:"qe-security-scanner",preconditions:{},effects:{"quality.secretsScanned":!0},cost:1,estimatedDurationMs:15e3,successRate:.98,category:"security",qeDomain:"security-compliance",method:"runSecurityAudit",params:{includeSecrets:!0},implemented:!0},{name:"run-dast",description:"Run dynamic application security testing against running application",agentType:"qe-security-auditor",preconditions:{"context.environment":"staging"},effects:{"quality.dastCompleted":!0},cost:4.5,estimatedDurationMs:12e4,successRate:.8,category:"security",qeDomain:"security-compliance",method:"runDASTScan",params:{},implemented:!0}],em=[{name:"run-benchmarks",description:"Execute performance benchmarks to establish baseline metrics",agentType:"qe-performance-tester",preconditions:{},effects:{"quality.benchmarked":!0},cost:2,estimatedDurationMs:45e3,successRate:.9,category:"performance",qeDomain:"chaos-resilience",implemented:!1},{name:"load-test",description:"Run load testing with simulated concurrent traffic",agentType:"qe-load-tester",preconditions:{"context.environment":"staging"},effects:{"quality.loadTested":!0},cost:3.5,estimatedDurationMs:12e4,successRate:.85,category:"performance",qeDomain:"chaos-resilience",method:"runLoadTestSuite",params:{},implemented:!0},{name:"stress-test",description:"Run stress testing to find breaking points and system limits",agentType:"qe-chaos-engineer",preconditions:{"context.environment":"staging","quality.loadTested":!0},effects:{"quality.stressTested":!0},cost:4,estimatedDurationMs:9e4,successRate:.8,category:"performance",qeDomain:"chaos-resilience",method:"runTest",params:{type:"stress"},implemented:!0},{name:"profile-memory",description:"Profile memory usage and identify memory leaks",agentType:"qe-performance-tester",preconditions:{"quality.benchmarked":!0},effects:{"quality.memoryProfiled":!0},cost:2.5,estimatedDurationMs:6e4,successRate:.88,category:"performance",qeDomain:"chaos-resilience",implemented:!1},{name:"optimize-slow-tests",description:"Identify and optimize slow-running tests to improve CI/CD speed",agentType:"qe-performance-tester",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.testsOptimized":!0},cost:2,estimatedDurationMs:3e4,successRate:.82,category:"performance",qeDomain:"test-execution",implemented:!1}],tm=[{name:"analyze-complexity",description:"Measure cyclomatic and cognitive complexity of codebase",agentType:"code-analyzer",preconditions:{},effects:{"quality.complexityAnalyzed":!0},cost:1,estimatedDurationMs:15e3,successRate:.95,category:"analysis",qeDomain:"quality-assessment",method:"analyzeComplexity",params:{},implemented:!0},{name:"detect-code-smells",description:"Identify code smells and anti-patterns using static analysis",agentType:"code-analyzer",preconditions:{},effects:{"quality.smellsDetected":!0},cost:1.5,estimatedDurationMs:2e4,successRate:.9,category:"analysis",qeDomain:"code-intelligence",implemented:!1},{name:"analyze-dependencies",description:"Analyze dependency graph and identify circular or outdated dependencies",agentType:"code-analyzer",preconditions:{},effects:{"quality.dependenciesAnalyzed":!0},cost:1,estimatedDurationMs:15e3,successRate:.92,category:"analysis",qeDomain:"code-intelligence",method:"mapDependencies",params:{},implemented:!0},{name:"measure-technical-debt",description:"Calculate technical debt metrics and generate remediation plan",agentType:"code-analyzer",preconditions:{"quality.complexityAnalyzed":!0,"quality.smellsDetected":!0},effects:{"quality.technicalDebtMeasured":!0},cost:2,estimatedDurationMs:25e3,successRate:.88,category:"analysis",qeDomain:"code-intelligence",implemented:!1},{name:"build-knowledge-graph",description:"Build semantic knowledge graph of codebase for intelligent context retrieval",agentType:"qe-intelligence-builder",preconditions:{"quality.dependenciesAnalyzed":!0},effects:{"quality.knowledgeGraphBuilt":!0},cost:3,estimatedDurationMs:6e4,successRate:.85,category:"analysis",qeDomain:"code-intelligence",method:"index",params:{},implemented:!0}],nm=[{name:"spawn-test-agent",description:"Spawn additional test execution agent for parallel work",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{max:10}},effects:{"fleet.activeAgents":{delta:1}},cost:.5,estimatedDurationMs:5e3,successRate:.95,category:"fleet",qeDomain:"test-execution",implemented:!1},{name:"optimize-fleet-topology",description:"Reconfigure fleet topology for optimal task distribution",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:3}},effects:{"fleet.efficiency":{delta:15}},cost:1,estimatedDurationMs:1e4,successRate:.85,category:"fleet",implemented:!1},{name:"scale-down-fleet",description:"Reduce fleet size to conserve resources during low-activity periods",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:5}},effects:{"fleet.activeAgents":{delta:-2}},cost:.3,estimatedDurationMs:3e3,successRate:.98,category:"fleet",implemented:!1},{name:"spawn-specialist-agent",description:"Spawn a specialized agent for specific domain work",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{max:12},"context.specialistNeeded":!0},effects:{"fleet.activeAgents":{delta:1},"fleet.specialistAvailable":!0},cost:1,estimatedDurationMs:8e3,successRate:.9,category:"fleet",implemented:!1},{name:"rebalance-workload",description:"Redistribute tasks across agents based on current load",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:2}},effects:{"fleet.workloadBalanced":!0},cost:.5,estimatedDurationMs:5e3,successRate:.92,category:"fleet",implemented:!1}],rm=[{name:"generate-quality-report",description:"Generate comprehensive quality report combining all metrics",agentType:"qe-quality-gate",preconditions:{"coverage.measured":!0,"quality.unitTestsRun":!0},effects:{"quality.reported":!0},cost:1,estimatedDurationMs:1e4,successRate:.95,category:"quality",qeDomain:"quality-assessment",method:"analyzeQuality",params:{},implemented:!0},{name:"enforce-quality-gate",description:"Check if all quality gates pass and report status",agentType:"qe-quality-gate",preconditions:{"quality.reported":!0},effects:{"quality.gatePassed":!0},cost:.5,estimatedDurationMs:5e3,successRate:.9,category:"quality",qeDomain:"quality-assessment",method:"evaluateGate",params:{},implemented:!0},{name:"validate-requirements",description:"Validate that tests cover all documented requirements",agentType:"qe-requirements-validator",preconditions:{"context.hasRequirements":!0},effects:{"quality.requirementsValidated":!0},cost:2,estimatedDurationMs:2e4,successRate:.88,category:"quality",qeDomain:"requirements-validation",method:"validate",params:{},implemented:!0},{name:"predict-defects",description:"Use ML-based defect prediction to identify high-risk code areas",agentType:"qe-defect-predictor",preconditions:{"quality.complexityAnalyzed":!0,"coverage.measured":!0},effects:{"quality.defectsPredicted":!0},cost:2.5,estimatedDurationMs:3e4,successRate:.82,category:"quality",qeDomain:"defect-intelligence",method:"predictDefects",params:{},implemented:!0},{name:"generate-deployment-report",description:"Generate deployment readiness report with all quality metrics",agentType:"qe-quality-gate",preconditions:{"quality.gatePassed":!0,"quality.securityScanned":!0},effects:{"quality.deploymentReady":!0},cost:1.5,estimatedDurationMs:15e3,successRate:.9,category:"quality",qeDomain:"quality-assessment",method:"getDeploymentAdvice",params:{},implemented:!0}],im=[{name:"run-accessibility-audit",description:"Run WCAG 2.2 accessibility audit using axe-core or similar",agentType:"qe-accessibility-tester",preconditions:{"context.hasUI":!0},effects:{"quality.accessibilityAudited":!0},cost:2,estimatedDurationMs:3e4,successRate:.9,category:"quality",qeDomain:"visual-accessibility",method:"runAccessibilityAudit",params:{},implemented:!0},{name:"run-visual-regression",description:"Run visual regression testing with screenshot comparison",agentType:"qe-visual-tester",preconditions:{"context.hasUI":!0},effects:{"quality.visualRegressionRun":!0},cost:3,estimatedDurationMs:6e4,successRate:.85,category:"quality",qeDomain:"visual-accessibility",method:"runVisualTests",params:{},implemented:!0}],Ko=[...Yd,...Jd,...Zd,...em,...tm,...nm,...rm,...im];function sm(o){return`action-${o}`}function Xo(o){return{...o,id:sm(o.name),executionCount:0}}function me(){return Ko.map(Xo)}var Je=[{name:"achieve-90-percent-coverage",description:"Reach 90% line coverage through targeted test generation",conditions:{"coverage.line":{min:90}},priority:1,qeDomain:"coverage-analysis"},{name:"all-tests-passing",description:"All tests green with 100% pass rate",conditions:{"quality.testsPassing":{min:100}},priority:1,qeDomain:"test-execution"},{name:"security-compliant",description:"Pass security audit with no critical vulnerabilities",conditions:{"quality.securityScanned":!0,"quality.vulnerabilities":{max:0}},priority:2,qeDomain:"security-compliance"},{name:"deployment-ready",description:"Ready for production deployment with all quality gates passed",conditions:{"coverage.line":{min:80},"quality.testsPassing":{min:100},"quality.securityScanned":!0,"quality.gatePassed":!0},priority:1},{name:"performance-validated",description:"Performance benchmarks and load tests completed successfully",conditions:{"quality.benchmarked":!0,"quality.loadTested":!0},priority:2,qeDomain:"chaos-resilience"},{name:"code-quality-excellent",description:"Excellent code quality with low complexity and no code smells",conditions:{"quality.complexityAnalyzed":!0,"quality.smellsDetected":!0,"quality.technicalDebtMeasured":!0},priority:3,qeDomain:"code-intelligence"},{name:"full-test-suite",description:"Complete test suite with unit, integration, and e2e tests",conditions:{"quality.unitTestsRun":!0,"quality.integrationTestsRun":!0,"quality.e2eTestsRun":!0},priority:2,qeDomain:"test-execution"},{name:"accessibility-compliant",description:"WCAG 2.2 compliant with visual regression coverage",conditions:{"quality.accessibilityAudited":!0,"quality.visualRegressionRun":!0},priority:2,qeDomain:"visual-accessibility"}];X();import{randomUUID as Me}from"crypto";var Zn=1e3,ki=class{data=[];cmp;constructor(e){this.cmp=e}get length(){return this.data.length}push(e){this.data.push(e),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;let e=this.data[0],t=this.data.pop();return this.data.length>0&&(this.data[0]=t,this.sinkDown(0)),e}bubbleUp(e){for(;e>0;){let t=e-1>>1;if(this.cmp(this.data[e],this.data[t])<0)[this.data[e],this.data[t]]=[this.data[t],this.data[e]],e=t;else break}}sinkDown(e){let t=this.data.length;for(;;){let n=e,r=2*e+1,i=2*e+2;if(r<t&&this.cmp(this.data[r],this.data[n])<0&&(n=r),i<t&&this.cmp(this.data[i],this.data[n])<0&&(n=i),n!==e)[this.data[e],this.data[n]]=[this.data[n],this.data[e]],e=n;else break}}},am=new Set(["__proto__","constructor","prototype"]),er=class o{db=null;persistence=null;actions=new Map;initialized=!1;enablePlanReuse=!0;constructor(){}ensureDb(){if(!this.db)throw new Error("GOAPPlanner not initialized - call initialize() first");return this.db}async initialize(){if(this.initialized)return;this.persistence=Zi(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.ensureDb().prepare("SELECT COUNT(*) as count FROM goap_actions").get().count===0&&this.seedDefaultActions(),this.backfillActionMethodBindings(),this.backfillActionDurationEstimates(),await this.loadActions(),this.initialized=!0,console.log(`[GOAPPlanner] Initialized: ${this.persistence.getDbPath()}`)}seedDefaultActions(){let e=me(),t=this.ensureDb(),n=t.prepare(`
641
+ `).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")).map(e=>e.split(/[>=<!~\[]/)[0].trim().toLowerCase()).filter(Boolean)}function Qo(o,e){let t=[];for(let n of o){let r=_d[n];r&&t.push({id:`DEP-py-${n}-${r.cve}`,title:`Vulnerable Python dependency: ${n}`,severity:r.severity,category:"vulnerable-components",location:{file:e,dependency:{name:n,version:"any"}},description:r.desc,remediation:n==="python-jose"?"Migrate to PyJWT or joserfc":`Check for updates to ${n}`,cveId:r.cve,references:[`https://nvd.nist.gov/vuln/detail/${r.cve}`]})}return t}function Fd(o,e){let t=o.split(".").map(Number),n=e.split(".").map(Number);for(let r=0;r<3;r++){let i=t[r]||0,s=n[r]||0;if(i<s)return-1;if(i>s)return 1}return 0}function Ld(o){return[{id:"DAST-INFO-001",title:"DAST scan target noted",severity:"informational",category:"security-misconfiguration",location:{file:o},description:`DAST target ${o} recorded. Full DAST requires integration with a dynamic scanner (e.g., ZAP, Burp).`,remediation:"Configure a DAST tool to scan the live application",references:["https://owasp.org/www-project-zap/"]}]}function qd(o,e){let t=e.filter(n=>o==="owasp"?!0:o==="pci-dss"?n.category==="injection"||n.category==="sensitive-data":o==="gdpr"?n.category==="sensitive-data":!1);return{standard:o,passed:t.filter(n=>n.severity==="critical"||n.severity==="high").length===0,score:Math.max(0,100-t.length*15),violations:t.map(n=>({ruleId:n.id,ruleName:n.title,location:n.location,details:n.description,remediation:n.remediation}))}}function $d(o,e){let t=[];return e.critical>0&&t.push("URGENT: Address critical vulnerabilities immediately"),e.high>0&&t.push("Prioritize high-severity issues in next sprint"),o.some(n=>n.category==="injection")&&t.push("Review input validation across the application"),o.some(n=>n.category==="sensitive-data")&&t.push("Implement proper secrets management"),o.some(n=>n.category==="vulnerable-components")&&t.push("Run full dependency audit and update vulnerable packages"),t.length===0&&t.push("No critical issues found. Continue regular security reviews."),t}X();k();function Wo(o){try{let e=new URL(o);if(!["http:","https:"].includes(e.protocol))return{valid:!1,error:`Invalid protocol: ${e.protocol}. Only http/https allowed.`};let t=e.hostname.toLowerCase(),n=[/^localhost$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2[0-9]|3[01])\./,/^192\.168\./,/^0\.0\.0\.0$/,/^\[::1\]$/,/^169\.254\./];for(let r of n)if(r.test(t))return{valid:!1,error:`Blocked hostname: ${t}. Cannot access internal/private addresses.`};return{valid:!0}}catch{return{valid:!1,error:`Invalid URL format: ${o}`}}}var Wn=class extends A{config={name:"qe/contracts/validate",description:"Validate API contracts, detect breaking changes, and verify provider-consumer compatibility.",domain:"contract-testing",schema:Gd,streaming:!0,timeout:18e4};contractValidator=null;apiCompatibility=null;async getServices(e){if(!this.contractValidator||!this.apiCompatibility){let t=e.memory||await O(),n=await U(e);this.contractValidator=new Ns({memory:t,llmRouter:n}),this.apiCompatibility=new Fs(t)}return{contractValidator:this.contractValidator,apiCompatibility:this.apiCompatibility}}async execute(e,t){let{contractPath:n,contractContent:r,providerUrl:i,consumerName:s,baselineVersion:a,baselineContent:c,checkBreakingChanges:l=!0,format:u="openapi"}=e,{contractValidator:d,apiCompatibility:m}=await this.getServices(t);try{if(!n&&!r)return{success:!1,error:"Either contractPath or contractContent is required"};if(this.emitStream(t,{status:"validating",message:`Validating ${u} contract`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let p=r||n||"",g=[],f,h,v;if(u==="openapi"){let b=await d.validateOpenAPI(p);if(b.success){let w=b.value;for(let T of w.errors)g.push({path:T.path,message:T.message,code:T.code,severity:"error"});for(let T of w.warnings)g.push({path:"",message:T,code:"WARNING",severity:"warning"});this.emitStream(t,{status:"analyzed",message:`Found ${w.endpointCount} endpoints, ${w.schemaCount} schemas`})}}else{let b=this.buildContractFromContent(p,u,s),w=await d.validateContract(b);if(w.success){let T=w.value;for(let S of T.errors)g.push(this.convertValidationError(S));for(let S of T.warnings)g.push({path:"",message:S,code:"WARNING",severity:"warning"})}}if(l&&(a||c)){this.emitStream(t,{status:"comparing",message:"Detecting breaking changes"});let b=this.buildContractFromContent(p,u,s),w=this.buildContractFromContent(c||p,u,s,a),T=await m.compareVersions(w,b);T.success?(f=T.value.breakingChanges.map(S=>this.convertBreakingChange(S)),v={isBackwardCompatible:T.value.isCompatible,breakingChangeCount:T.value.breakingChanges.length,nonBreakingChangeCount:T.value.nonBreakingChanges.length,deprecations:T.value.deprecations.map(S=>this.convertDeprecation(S))}):v=this.generateDefaultCompatibility(g,f)}else v=this.generateDefaultCompatibility(g,f);i&&(this.emitStream(t,{status:"verifying",message:"Verifying against provider"}),h=await this.verifyAgainstProvider(i,s||"default",p,u,d));let y=g.filter(b=>b.severity==="error").length===0,C=this.generateRecommendations(g,f,h);return this.emitStream(t,{status:"complete",message:y?"Contract is valid":`Found ${g.length} issues`,progress:100}),{success:!0,data:{isValid:y,validationErrors:g,breakingChanges:f,verificationResult:h,compatibility:v,recommendations:C}}}catch(p){return{success:!1,error:`Contract validation failed: ${E(p)}`}}}buildContractFromContent(e,t,n,r){let i=`contract-${Date.now()}`,s=Ds.parse(r||"1.0.0"),a=[],c=[];if(t==="openapi")try{let l=M(e),d=l.components?.schemas||{};for(let[p,g]of Object.entries(d))a.push({id:p,name:p,type:"openapi",content:JSON.stringify(g)});let m=l.paths||{};for(let[p,g]of Object.entries(m))if(typeof g=="object"&&g!==null){let f=g,h=["get","post","put","patch","delete","head","options"];for(let v of h)v in f&&c.push({path:p,method:v.toUpperCase(),examples:[]})}}catch{}else if(t==="graphql")a.push({id:"graphql-schema",name:"GraphQL Schema",type:"graphql",content:e});else if(t==="pact")try{let u=M(e).interactions||[];for(let d of u){let m=d.request;m&&c.push({path:m.path||"/",method:(m.method||"GET").toUpperCase(),examples:[]})}}catch{}return{id:i,name:`${t}-contract`,version:s,type:t,provider:{name:"provider",version:"1.0.0"},consumers:[{name:n||"default",version:"1.0.0"}],endpoints:c,schemas:a}}convertValidationError(e){return{path:e.path,message:e.message,code:e.code,severity:"error"}}convertBreakingChange(e){return{type:e.type,location:e.location,description:e.description,impact:e.impact,affectedConsumers:e.affectedConsumers,migrationPath:e.migrationPath}}convertDeprecation(e){return{location:e.location,reason:e.reason,removalVersion:e.removalVersion,replacement:e.replacement}}generateDefaultCompatibility(e,t){return{isBackwardCompatible:!t||t.length===0,breakingChangeCount:t?.length||0,nonBreakingChangeCount:e.filter(n=>n.severity!=="error").length,deprecations:[]}}async verifyAgainstProvider(e,t,n,r,i){let s=[],a=[],c=Wo(e);if(!c.valid)return{provider:e,consumer:t,passed:!1,failures:[{endpoint:e,type:"validation-error",expected:"Valid HTTP/HTTPS URL",actual:c.error||"Invalid URL",message:`Provider URL validation failed: ${c.error}`}],warnings:[]};let l=this.buildContractFromContent(n,r,t);for(let u of l.endpoints)try{let d=`${e}${u.path}`,m=Wo(d);if(!m.valid){s.push({endpoint:`${u.method} ${u.path}`,type:"validation-error",expected:"Valid URL",actual:m.error||"Invalid URL",message:`URL validation failed: ${m.error}`});continue}let p=await fetch(d,{method:u.method==="GET"?"GET":"OPTIONS",headers:{Accept:"application/json"}});if(!p.ok&&p.status!==405&&(p.status===404?s.push({endpoint:`${u.method} ${u.path}`,type:"missing-endpoint",expected:"Endpoint should exist",actual:`Got ${p.status}`,message:"Endpoint not found at provider"}):a.push({endpoint:`${u.method} ${u.path}`,message:`Unexpected status ${p.status}`,severity:"medium"})),u.responseSchema&&p.ok){let g=await p.json(),f=l.schemas.find(h=>h.id===u.responseSchema);if(f){let h=await i.validateResponse(g,f);if(h.success&&!h.value.isValid)for(let v of h.value.errors)s.push({endpoint:`${u.method} ${u.path}`,type:"schema-mismatch",expected:`Schema ${u.responseSchema}`,actual:v.message,message:`Response does not match schema: ${v.message}`})}}}catch(d){a.push({endpoint:`${u.method} ${u.path}`,message:`Failed to verify: ${E(d)}`,severity:"high"})}return{provider:e,consumer:t,passed:s.length===0,failures:s,warnings:a}}generateRecommendations(e,t,n){let r=[],i=e.filter(a=>a.severity==="error").length;if(i>0&&r.push(`Fix ${i} validation error${i>1?"s":""} before deploying`),t&&t.length>0){let a=t.filter(c=>c.impact==="high").length;a>0&&r.push(`Address ${a} high-impact breaking change${a>1?"s":""} before release`),r.push("Coordinate with affected consumers before releasing breaking changes"),r.push("Consider versioning the API to maintain backward compatibility")}n&&(n.passed||(r.push(`Provider verification failed with ${n.failures.length} failure${n.failures.length>1?"s":""}`),n.failures.filter(l=>l.type==="missing-endpoint").length>0&&r.push("Ensure all contract endpoints are implemented in the provider"),n.failures.filter(l=>l.type==="schema-mismatch").length>0&&r.push("Update provider responses to match the contract schema")),n.warnings.length>0&&n.warnings.filter(c=>c.severity==="high").length>0&&r.push("Investigate high-severity verification warnings"));let s=e.filter(a=>a.severity==="warning").length;return s>0&&r.push(`Review ${s} warning${s>1?"s":""} for potential issues`),r.length===0&&r.push("Contract is valid and backward compatible"),r}},Gd={type:"object",properties:{contractPath:{type:"string",description:"Path to contract file"},contractContent:{type:"string",description:"Contract content as string"},providerUrl:{type:"string",description:"Provider URL for verification"},consumerName:{type:"string",description:"Consumer name for contract"},baselineVersion:{type:"string",description:"Baseline version for breaking change detection"},baselineContent:{type:"string",description:"Baseline contract content for comparison"},checkBreakingChanges:{type:"boolean",description:"Check for breaking changes",default:!0},format:{type:"string",description:"Contract format",enum:["openapi","pact","graphql","asyncapi"],default:"openapi"}}};k();var Kn=class extends A{config={name:"qe/visual/compare",description:"Visual regression testing with screenshot comparison, diff detection, and baseline management.",domain:"visual-accessibility",schema:jd,streaming:!0,timeout:3e5};visualTester=null;async getService(e){if(!this.visualTester){let t=e.memory??await O(),n=await U(e);this.visualTester=Ls({memory:t,llmRouter:n})}return this.visualTester}async execute(e,t){let{urls:n,viewports:r=[{width:1920,height:1080,name:"desktop"}],baselineDir:i=".visual-baselines",threshold:s=.1,fullPage:a=!0}=e;try{if(this.emitStream(t,{status:"capturing",message:`Capturing ${n.length} URLs across ${r.length} viewports`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};this.markAsRealData();let c=await this.getService(t),l=[],u=[];for(let m of n)for(let p of r){this.emitStream(t,{status:"comparing",message:`Comparing ${m} at ${p.width}x${p.height}`});let g={width:p.width,height:p.height,deviceScaleFactor:1,isMobile:p.isMobile||!1,hasTouch:p.isMobile||!1},f=await c.captureScreenshot(m,{viewport:g,fullPage:a});if(!f.success){l.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let h=f.value,v=await c.getBaseline(m,g);if(!v)await c.setBaseline(h),u.push(h.path.value),l.push({url:m,viewport:p,status:"new",diffPercentage:0,diffPixels:0,screenshotPath:h.path.value});else{let y=await c.compare(h,v.id);if(!y.success){l.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let C=y.value,b=C.diffPercentage<=s;l.push({url:m,viewport:p,status:b?"passed":"failed",diffPercentage:C.diffPercentage,diffPixels:C.diffPixels,screenshotPath:h.path.value,baselinePath:v.path.value,diffImagePath:C.diffImagePath?.value,regions:C.regions?.map(w=>({x:w.x,y:w.y,width:w.width,height:w.height,changeType:w.changeType,significance:w.significance}))})}}let d={total:l.length,passed:l.filter(m=>m.status==="passed").length,failed:l.filter(m=>m.status==="failed").length,new:l.filter(m=>m.status==="new").length,avgDiffPercentage:l.length>0?l.reduce((m,p)=>m+p.diffPercentage,0)/l.length:0};return this.emitStream(t,{status:"complete",message:`Visual comparison complete: ${d.passed}/${d.total} passed`,progress:100}),{success:!0,data:{comparisons:l,summary:d,newBaselines:u,recommendations:Bd(l,d)}}}catch(c){return{success:!1,error:`Visual comparison failed: ${E(c)}`}}}},Xn=class extends A{config={name:"qe/a11y/audit",description:"WCAG accessibility auditing with violation detection, contrast checking, and keyboard navigation testing.",domain:"visual-accessibility",schema:zd,streaming:!0,timeout:18e4};accessibilityTester=null;async getService(e){if(!this.accessibilityTester){let t=e.memory;this.accessibilityTester=new qs(t||await O(),{enableColorContrastCheck:!0,enableKeyboardCheck:!0})}return this.accessibilityTester}async execute(e,t){let{urls:n,standard:r="wcag21-aa",includeWarnings:i=!0,checkContrast:s=!0,checkKeyboard:a=!0}=e;try{if(this.emitStream(t,{status:"auditing",message:`Auditing ${n.length} URLs against ${r}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};this.markAsRealData();let c=await this.getService(t),l=[],u=Ud(r);for(let g of n){this.emitStream(t,{status:"scanning",message:`Scanning ${g}`});let f=await c.audit(g,{wcagLevel:u,includeWarnings:i});if(!f.success){l.push({url:g,score:0,passed:!1,violations:[],warnings:[],passedRules:0});continue}let h=f.value,v=[];if(s){let T=await c.checkContrast(g);if(T.success){let S=T.value.filter(x=>!x.passes);S.length>0&&(v=S.map(x=>({id:"color-contrast",impact:"serious",description:"Elements must have sufficient color contrast",help:`Element ${x.element} has contrast ratio ${x.ratio}:1 but requires ${x.requiredRatio}:1`,helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum",wcagCriteria:["1.4.3"],nodes:[{selector:x.element,html:`<${x.element.replace(".",' class="')}>...</${x.element.split(".")[0]}>`,failureSummary:`Contrast ratio ${x.ratio}:1 is below required ${x.requiredRatio}:1`,fixSuggestion:`Change foreground color to achieve at least ${x.requiredRatio}:1 contrast`}]})))}}let y=[];if(a){let T=await c.checkKeyboardNavigation(g);if(T.success){let S=T.value;for(let x of S.issues)y.push({id:x.type,impact:x.type==="no-focus-indicator"?"serious":"moderate",description:x.description,help:"Ensure keyboard navigation is fully supported",helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/focus-visible",wcagCriteria:["2.4.7"],nodes:[{selector:x.selector,html:`<element>${x.selector}</element>`,failureSummary:x.description,fixSuggestion:"Add visible focus styles with :focus or :focus-visible"}]});for(let x of S.traps)y.push({id:"keyboard-trap",impact:"critical",description:x.description,help:x.escapePath||"No escape path available",helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/no-keyboard-trap",wcagCriteria:["2.1.2"],nodes:[{selector:x.selector,html:`<element>${x.selector}</element>`,failureSummary:x.description,fixSuggestion:x.escapePath}]})}}let C=[...h.violations.map(T=>({id:T.id,impact:T.impact,description:T.description,help:T.help,helpUrl:T.helpUrl,wcagCriteria:T.wcagCriteria.map(S=>S.id),nodes:T.nodes.map(S=>({selector:S.selector,html:S.html,failureSummary:S.failureSummary,fixSuggestion:S.fixSuggestion}))})),...v,...y],b=h.incomplete.map(T=>({id:T.id,description:T.description,nodes:T.nodes.length})),w=C.some(T=>T.impact==="critical"||T.impact==="serious");l.push({url:g,score:h.score,passed:!w,violations:C,warnings:b,passedRules:h.passes.length})}let d={totalUrls:l.length,passingUrls:l.filter(g=>g.passed).length,avgScore:l.length>0?Math.round(l.reduce((g,f)=>g+f.score,0)/l.length):0,criticalViolations:l.reduce((g,f)=>g+f.violations.filter(h=>h.impact==="critical").length,0),seriousViolations:l.reduce((g,f)=>g+f.violations.filter(h=>h.impact==="serious").length,0),totalViolations:l.reduce((g,f)=>g+f.violations.length,0)},m=Hd(l),p=Vd(m);return this.emitStream(t,{status:"complete",message:`Audit complete: avg score ${d.avgScore}%`,progress:100}),{success:!0,data:{audits:l,summary:d,topIssues:m,remediationPlan:p}}}catch(c){return{success:!1,error:`Accessibility audit failed: ${E(c)}`}}}},jd={type:"object",properties:{urls:{type:"array",description:"URLs to capture and compare",items:{type:"string",description:"URL"}},viewports:{type:"array",description:"Viewport configurations",items:{type:"object",description:"Viewport",properties:{width:{type:"number",description:"Width in pixels"},height:{type:"number",description:"Height in pixels"},name:{type:"string",description:"Viewport name"}}}},baselineDir:{type:"string",description:"Directory for baseline images",default:".visual-baselines"},threshold:{type:"number",description:"Acceptable diff percentage (0-1)",minimum:0,maximum:1,default:.1},fullPage:{type:"boolean",description:"Capture full page",default:!0},hideSelectors:{type:"array",description:"CSS selectors to hide before capture",items:{type:"string",description:"Selector"}},waitForSelector:{type:"string",description:"Wait for selector before capture"}},required:["urls"]},zd={type:"object",properties:{urls:{type:"array",description:"URLs to audit",items:{type:"string",description:"URL"}},standard:{type:"string",description:"WCAG standard to validate against",enum:["wcag21-aa","wcag21-aaa","wcag22-aa","section508"],default:"wcag21-aa"},includeWarnings:{type:"boolean",description:"Include warnings in results",default:!0},checkContrast:{type:"boolean",description:"Check color contrast",default:!0},checkKeyboard:{type:"boolean",description:"Check keyboard navigation",default:!0},rules:{type:"array",description:"Specific rules to check",items:{type:"string",description:"Rule ID"}}},required:["urls"]};function Ud(o){return o==="wcag21-aaa"?"AAA":"AA"}function Bd(o,e){let t=[];return e.failed>0&&t.push(`Review ${e.failed} failed comparisons for intentional vs unintentional changes`),e.new>0&&t.push(`${e.new} new baselines created - review and approve if correct`),e.avgDiffPercentage>1&&t.push("Consider increasing diff threshold or reviewing major changes"),t.length>0?t:["All visual tests passed"]}function Hd(o){let e=new Map;for(let t of o)for(let n of t.violations){let r=e.get(n.id);r?(r.occurrences++,r.affectedUrls.includes(t.url)||r.affectedUrls.push(t.url)):e.set(n.id,{ruleId:n.id,description:n.description,occurrences:1,impact:n.impact,affectedUrls:[t.url]})}return Array.from(e.values()).sort((t,n)=>n.occurrences-t.occurrences)}function Vd(o){return o.map((e,t)=>({violationId:e.ruleId,description:e.description,fix:`Fix ${e.ruleId} across ${e.occurrences} occurrences`,effort:e.occurrences>10?"moderate":"minor",priority:t+1}))}k();var Yn=class extends A{config={name:"qe/chaos/inject",description:"Inject faults for chaos engineering. Supports latency, errors, CPU/memory stress, network issues, and more.",domain:"chaos-resilience",schema:Qd,streaming:!0,timeout:3e5};chaosEngineer=null;async getService(e){if(!this.chaosEngineer){let t=e.memory||await O(),n=await U(e);this.chaosEngineer=new $s({memory:t,llmRouter:n},{enableDryRun:!0,autoRollbackOnFailure:!0})}return this.chaosEngineer}async execute(e,t){let{faultType:n,target:r,duration:i=3e4,intensity:s=50,dryRun:a=!0,hypothesis:c,rollbackOnFailure:l=!0}=e,u=await this.getService(t);try{if(this.emitStream(t,{status:"preparing",message:`Preparing ${n} fault injection on ${r}`,dryRun:a}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let d=t.requestId||G(),m=this.buildExperiment(d,n,r,i,s,c,l);this.emitStream(t,{status:"verifying",message:"Verifying steady state"});let p=await u.verifySteadyState(m.steadyState),g=p.success&&p.value;if(!g&&!a)return{success:!1,error:"Steady state verification failed. System not in healthy state for chaos experiment."};let f=await u.createExperiment(m);if(!f.success)return{success:!1,error:`Failed to create experiment: ${f.error.message}`};this.emitStream(t,{status:"injecting",message:a?`[DRY RUN] Simulating ${n} fault`:`Injecting ${n} fault`});let h=!1,v,y="pending",C=[],b={faultDuration:i,targetAffected:!a};if(a)h=!1,y="completed",b=this.simulateMetrics(n,i,s),c&&(v=this.validateHypothesisText(c,b,C));else{let S=await u.runExperiment(d);if(S.success){let x=S.value;h=x.faultResults.some(F=>F.injected),v=x.hypothesisValidated,y=x.status;for(let F of x.incidents)C.push(this.convertIncident(F));b=this.extractMetrics(x,n,i)}else y="failed",C.push({type:"error",severity:"critical",message:S.error.message,timestamp:new Date().toISOString(),resolved:!1})}this.emitStream(t,{status:"monitoring",message:"Monitoring system behavior"});let w=this.collectIntensityIncidents(n,s,a);C.push(...w),!a&&C.some(S=>S.severity==="critical"&&!S.resolved)&&(y=l?"rolled-back":"failed");let T=this.generateRecommendations(n,b,C,v);return this.emitStream(t,{status:"complete",message:`Chaos experiment ${y}`,progress:100}),{success:!0,data:{experimentId:d,status:y,faultInjected:h,hypothesisValidated:v,steadyStateVerified:g,metrics:b,incidents:C,recommendations:T}}}catch(d){return{success:!1,error:`Chaos injection failed: ${E(d)}`}}}buildExperiment(e,t,n,r,i,s,a=!0){let c={id:`fault-${e}`,type:t,target:{type:"service",selector:n},duration:r,parameters:this.buildFaultParameters(t,i)},l={description:`Steady state for ${n}`,probes:[{name:"target-health",type:n.startsWith("http")?"http":"command",target:n.startsWith("http")?n:`echo "checking ${n}"`,expected:n.startsWith("http")?200:"OK",timeout:5e3}]},u=s||`System should remain stable under ${t} fault`;return{id:e,name:`${t}-experiment-${Date.now()}`,description:`Chaos experiment: ${t} on ${n}`,hypothesis:{statement:u,metrics:[{metric:t==="latency"?"response_time":"error_rate",operator:"lt",value:t==="latency"?5e3:50}],tolerances:[{metric:"availability",maxDeviation:20,unit:"percent"}]},steadyState:l,faults:[c],blastRadius:{scope:"single",maxAffected:1,excludeProduction:!0},rollbackPlan:{automatic:a,triggerConditions:[{type:"error-rate",condition:"error_rate > 50%"}],steps:[{order:1,action:"remove-fault",target:c.id,timeout:1e4}]},schedule:{type:"once"}}}buildFaultParameters(e,t){let n={};switch(e){case"latency":n.latencyMs=100+t*20;break;case"error":n.errorCode=500,n.errorRate=t/100;break;case"timeout":n.timeoutMs=5e3+t*250;break;case"cpu-stress":n.cpuPercent=t,n.cores=Math.max(1,Math.floor(t/25));break;case"memory-stress":n.memoryBytes=t/100*512*1024*1024;break;case"network-partition":n.partitionPercent=t;break;case"packet-loss":n.packetLossPercent=t;break;case"dns-failure":n.failureRate=t/100;break;case"process-kill":n.signal="SIGTERM";break}return n}simulateMetrics(e,t,n){let r={faultDuration:t,targetAffected:!1,recoveryTime:5e3+n*100};switch(e){case"latency":r.latencyP99=100+n*25;break;case"error":case"timeout":r.errorRate=n*.5;break;case"cpu-stress":case"memory-stress":r.recoveryTime=1e4+n*200;break}return r}extractMetrics(e,t,n){let r={faultDuration:n,targetAffected:e.faultResults.some(c=>c.injected&&c.affectedTargets>0)},i=e.metrics;e.endTime&&e.startTime&&(r.recoveryTime=e.endTime.getTime()-e.startTime.getTime());let s=i.find(c=>c.name.includes("latency")||c.name.includes("response"));s&&(r.latencyP99=s.value);let a=i.find(c=>c.name.includes("error")||c.name.includes("failure"));return a&&(r.errorRate=a.value),r}convertIncident(e){return{type:e.type,severity:e.severity,message:e.message,timestamp:e.timestamp instanceof Date?e.timestamp.toISOString():String(e.timestamp),resolved:e.resolved}}collectIntensityIncidents(e,t,n){let r=[];return n&&(t>70&&r.push({type:"alert",severity:"high",message:`[Simulated] High ${e} impact would be detected`,timestamp:new Date().toISOString(),resolved:!0}),t>90&&r.push({type:"degradation",severity:"critical",message:"[Simulated] Service degradation would occur",timestamp:new Date().toISOString(),resolved:!0})),r}validateHypothesisText(e,t,n){let r=e.toLowerCase();if(r.includes("recover")&&t.recoveryTime){let i=e.match(/(\d+)s/);if(i){let s=parseInt(i[1])*1e3;return t.recoveryTime<=s}}return r.includes("no critical")?!n.some(i=>i.severity==="critical"&&!i.resolved):r.includes("stable")||r.includes("remain")?!n.some(i=>i.severity==="critical"&&!i.resolved):!n.some(i=>i.severity==="critical"&&!i.resolved)}generateRecommendations(e,t,n,r){let i=[];switch(r===!1&&i.push("Hypothesis was not validated - review resilience patterns"),t.recoveryTime&&t.recoveryTime>3e4&&i.push("Recovery time exceeds 30s - consider adding circuit breakers"),t.errorRate&&t.errorRate>20&&i.push("High error rate observed - implement retry with backoff"),n.some(s=>s.severity==="critical")&&i.push("Critical incidents occurred - review fault tolerance mechanisms"),e){case"latency":t.latencyP99&&t.latencyP99>1e3&&i.push("P99 latency exceeds 1s - consider timeout configurations");break;case"network-partition":i.push("Ensure services can operate in degraded mode during network issues");break;case"cpu-stress":case"memory-stress":i.push("Review resource limits and auto-scaling policies");break;case"error":i.push("Implement proper error handling and fallback mechanisms");break;case"timeout":i.push("Configure appropriate timeout values and circuit breakers");break}return i.length===0&&i.push("System showed good resilience - continue regular chaos experiments"),i}},Qd={type:"object",properties:{faultType:{type:"string",description:"Type of fault to inject",enum:["latency","error","timeout","cpu-stress","memory-stress","network-partition","packet-loss","dns-failure","process-kill"]},target:{type:"string",description:"Target service, pod, or endpoint"},duration:{type:"number",description:"Fault duration in milliseconds",minimum:1e3,maximum:3e5,default:3e4},intensity:{type:"number",description:"Fault intensity (0-100)",minimum:0,maximum:100,default:50},dryRun:{type:"boolean",description:"Simulate without actual injection",default:!0},hypothesis:{type:"string",description:'Hypothesis to validate (e.g., "System should recover within 30s")'},rollbackOnFailure:{type:"boolean",description:"Auto-rollback on critical failure",default:!0}},required:["faultType","target"]};k();mt();var wt=class extends A{config={name:"qe/learning/optimize",description:"Cross-domain learning, pattern recognition, strategy optimization, and knowledge transfer.",domain:"learning-optimization",schema:Wd,streaming:!0,timeout:3e5};learningCoordinator=null;metricsOptimizer=null;transferSpecialist=null;async getServices(e){if(!this.learningCoordinator||!this.metricsOptimizer||!this.transferSpecialist){let t=e.memory||await O(),n=await U(e);this.learningCoordinator=new Gs({memory:t,llmRouter:n}),this.metricsOptimizer=new zs(t),this.transferSpecialist=new js(t)}return{learningCoordinator:this.learningCoordinator,metricsOptimizer:this.metricsOptimizer,transferSpecialist:this.transferSpecialist}}async execute(e,t){let{action:n,domain:r,experienceIds:i,targetDomain:s,objective:a}=e;try{if(this.emitStream(t,{status:"processing",message:`Executing ${n} action`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let c={action:n};switch(n){case"learn":c.learnResult=await this.executeLearn(r,i,t);break;case"optimize":if(!a)return{success:!1,error:"Objective is required for optimize action"};c.optimizeResult=await this.executeOptimize(r,a,t);break;case"transfer":if(!r||!s)return{success:!1,error:"Both domain and targetDomain are required for transfer action"};c.transferResult=await this.executeTransfer(r,s,t);break;case"patterns":c.patternResult=await this.executePatterns(r,t);break;case"dashboard":c.dashboardResult=await this.executeDashboard(t);break;default:return{success:!1,error:`Unknown action: ${n}`}}return this.emitStream(t,{status:"complete",message:`${n} complete`,progress:100}),{success:!0,data:c}}catch(c){return{success:!1,error:`Learning optimization failed: ${E(c)}`}}}async executeLearn(e,t,n){let r=e||"learning-optimization";if(this.isDemoMode(n))return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoLearnResult(r);let{learningCoordinator:i}=await this.getServices(n);this.emitStream(n,{status:"learning",message:`Learning from ${t?.length||"recent"} experiences`});let s=gt.lastNDays(7),a=await i.mineExperiences(r,s),c=[],l=0,u=0;if(a.success){l=a.value.experienceCount;for(let d of a.value.patterns)c.push({id:d.id,type:d.type,name:d.name,description:d.description,confidence:d.confidence,usageCount:d.usageCount,successRate:d.successRate});u=a.value.successRate>.5?(a.value.successRate-.5)*20:0}return t&&t.length>0&&(l=t.length),c.length===0?(this.markAsRealData(),{experiencesProcessed:l,patternsLearned:0,newPatterns:[],improvement:0}):(this.markAsRealData(),{experiencesProcessed:l,patternsLearned:c.length,newPatterns:c,improvement:u})}getDemoLearnResult(e){return{experiencesProcessed:150,patternsLearned:12,newPatterns:[{id:`pattern-${e}-001`,type:"optimization",name:"Parallel Execution Pattern",description:`Optimal parallelism settings discovered for ${e}`,confidence:.92,usageCount:45,successRate:.87},{id:`pattern-${e}-002`,type:"retry",name:"Exponential Backoff Pattern",description:"Effective retry strategy for flaky operations",confidence:.88,usageCount:32,successRate:.91},{id:`pattern-${e}-003`,type:"caching",name:"Result Caching Pattern",description:"Cache frequently computed results for faster access",confidence:.85,usageCount:28,successRate:.82}],improvement:15.5}}async executeOptimize(e,t,n){let{learningCoordinator:r,metricsOptimizer:i}=await this.getServices(n);this.emitStream(n,{status:"optimizing",message:`Optimizing for ${t.metric}`});let s=e||"learning-optimization",a=gt.lastNDays(30),c=await r.mineExperiences(s,a),l=[];if(c.success&&c.value.experienceCount>0){let v={value:"optimizer-agent",domain:s,type:"optimizer"};for(let y=0;y<Math.min(c.value.experienceCount,20);y++)l.push({id:`exp-${y}`,agentId:v,domain:s,action:"optimize",state:{context:{},metrics:{}},result:{success:oe()>.3,outcome:{[t.metric]:ce(70,100)},duration:ce(1e3,6e3)},reward:c.value.avgReward,timestamp:new Date})}let u={name:`${s}-current`,parameters:{parallelism:4,retryCount:3,timeout:3e4},expectedOutcome:{[t.metric]:70}},d=(t.constraints||[]).map(v=>({metric:v.metric,operator:v.operator,value:v.value})),m={metric:t.metric,direction:t.direction,constraints:d},p=u,g=0,f=.5,h=[];if(l.length>=20){let v=await i.optimizeStrategy(u,m,l);v.success&&(p={name:v.value.optimizedStrategy.name,parameters:v.value.optimizedStrategy.parameters,expectedOutcome:v.value.optimizedStrategy.expectedOutcome},g=v.value.improvement*100,f=v.value.confidence,h=v.value.validationResults)}else{let v={tags:[s,t.metric]},y=await i.recommendStrategy(v);y.success&&(p={name:y.value.name,parameters:y.value.parameters,expectedOutcome:y.value.expectedOutcome})}return{strategiesEvaluated:l.length>0?Math.min(l.length,12):1,bestStrategy:p,improvement:g,confidence:f,validationResults:h}}async executeTransfer(e,t,n){let{transferSpecialist:r}=await this.getServices(n);this.emitStream(n,{status:"transferring",message:`Transferring knowledge from ${e} to ${t}`});let i=await r.queryKnowledge({domain:e,minRelevance:.5,limit:50}),s=0,a=0,c=0,l=0;if(i.success){s=i.value.length;for(let d of i.value){let m=await r.transferKnowledge(d,t);m.success&&(a++,l+=m.value.relevanceScore,Math.abs(m.value.relevanceScore-d.relevanceScore)>.1&&c++)}}let u=s>0?a/s:0;return{sourcePatterns:s,transferredPatterns:a,adaptedPatterns:c,successRate:u,targetDomainUpdated:a>0}}async executePatterns(e,t){let{learningCoordinator:n}=await this.getServices(t),r=await this.getSONASnapshot(t);this.emitStream(t,{status:"analyzing",message:`Analyzing patterns${e?` for ${e}`:""}`});let i=await n.getPatternStats(e);if(!i.success)return{totalPatterns:0,byType:{},byDomain:{},topPatterns:[],avgConfidence:0,avgSuccessRate:0,sona:r};let s=i.value,a=s.topPatterns.map(c=>({id:c.id,type:c.type,name:c.name,description:c.description,confidence:c.confidence,usageCount:c.usageCount,successRate:c.successRate}));return{totalPatterns:s.totalPatterns,byType:s.byType,byDomain:s.byDomain,topPatterns:a,avgConfidence:s.avgConfidence,avgSuccessRate:s.avgSuccessRate,sona:r}}async executeDashboard(e){let{learningCoordinator:t,transferSpecialist:n}=await this.getServices(e),r=await this.getSONASnapshot(e);this.emitStream(e,{status:"aggregating",message:"Aggregating learning metrics"});let i=await t.getPatternStats(),s=await n.queryKnowledge({minRelevance:0,limit:1e3}),a=gt.lastNDays(1),c=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","learning-optimization"],l=0,u=[];for(let y of c){let C=await t.mineExperiences(y,a);C.success&&(l+=C.value.experienceCount,C.value.experienceCount>0&&u.push({domain:y,successRate:C.value.successRate}))}u.sort((y,C)=>C.successRate-y.successRate);let d=u.slice(0,3).map(y=>y.domain),m=i.success?i.value.totalPatterns:0,p=i.success?i.value.avgSuccessRate:0,g=p,f=[],h=new Date;for(let y=6;y>=0;y--){let C=new Date(h.getTime()-y*24*60*60*1e3),b=new Date(C.getTime()+1440*60*1e3),w=gt.create(C,b),T=0;for(let S of c.slice(0,3)){let x=await t.mineExperiences(S,w);x.success&&(T+=x.value.patterns.length)}f.push({timestamp:C.toISOString(),metric:"patterns-learned",value:T})}let v=[];return m>=100&&v.push({name:`Reached ${Math.floor(m/50)*50} patterns`,achievedAt:new Date(h.getTime()-2880*60*1e3).toISOString(),domain:"learning-optimization"}),p>=.8&&v.push({name:`${Math.round(p*100)}% pattern success rate`,achievedAt:new Date(h.getTime()-7200*60*1e3).toISOString(),domain:d[0]||"learning-optimization"}),{overallLearningRate:g,totalPatterns:m,totalKnowledge:s.success?s.value.length:0,experiencesLast24h:l,topPerformingDomains:d.length>0?d:["test-generation"],learningTrend:f,recentMilestones:v,sona:r}}async getSONASnapshot(e){let t=e.kernel?.getDomainAPI("learning-optimization");if(!t?.isSONAAvailable())return{available:!1,stats:null};try{return{available:!0,stats:await t.getSONAPersistedStats()}}catch(n){return this.logger.warn("Failed to read persisted SONA statistics",{requestId:e.requestId,error:E(n)}),{available:!1,stats:null}}}},Wd={type:"object",properties:{action:{type:"string",description:"Learning action to perform",enum:["learn","optimize","transfer","patterns","dashboard"]},domain:{type:"string",description:"Source domain for learning/optimization",enum:["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"]},experienceIds:{type:"array",description:"Specific experience IDs to learn from",items:{type:"string",description:"Experience ID"}},targetDomain:{type:"string",description:"Target domain for knowledge transfer"},objective:{type:"object",description:"Optimization objective",properties:{metric:{type:"string",description:"Metric to optimize"},direction:{type:"string",description:"maximize or minimize",enum:["maximize","minimize"]},constraints:{type:"array",description:"Optimization constraints",items:{type:"object",description:"Constraint"}}}}},required:["action"]};k();var Kd={type:"object",properties:{action:{type:"string",enum:["dream","insights","apply","history","status"],description:"Action to perform: dream (run cycle), insights (view pending), apply (create pattern), history (view past), status (current state)"},durationMs:{type:"number",description:"Duration of dream cycle in milliseconds (default: 30000, max: 60000)",default:3e4},minPatterns:{type:"number",description:"Minimum patterns required to start dreaming (default: 10)",default:10},insightId:{type:"string",description:"Insight ID to apply (required for apply action)"},limit:{type:"number",description:"Maximum results to return (default: 20)",default:20},loadFromReasoningBank:{type:"boolean",description:"Load patterns from ReasoningBank before dreaming (default: true)",default:!0}},required:["action"]},Rt=class extends A{config={name:"qe/learning/dream",description:"Trigger dream cycles for pattern discovery. Dreams find novel associations between patterns through spreading activation, generating actionable insights.",domain:"learning-optimization",schema:Kd,streaming:!1,timeout:12e4};engine=null;engineConfig=null;async getEngine(e){return this.engine&&e&&!this.configsEqual(this.engineConfig,e)&&this.engine&&(await this.engine.close().catch(()=>{}),this.engine=null,this.engineConfig=null),this.engine||(this.engine=ns(e),this.engineConfig=e||null,await this.engine.initialize()),this.engine}configsEqual(e,t){return e===t?!0:!e||!t?!1:e.maxDurationMs===t.maxDurationMs&&e.minConceptsRequired===t.minConceptsRequired}async loadPatternsFromReasoningBank(e){try{let t=await O(),n=hr(t);await n.initialize();try{let{getSharedRvfDualWriter:a}=await import("./shared-rvf-dual-writer-WML274E7.js"),c=await a();c&&n.setRvfDualWriter(c)}catch(a){process.env.DEBUG&&this.logger.info("RVF wiring skipped",{error:String(a)})}let r=await n.searchPatterns("",{limit:100,minConfidence:.3});if(!r.success||!r.value.length)return this.logger.info("No patterns found in ReasoningBank to load"),0;let i=r.value.map(a=>({id:a.pattern.id,name:a.pattern.name,description:a.pattern.description||`${a.pattern.patternType} pattern`,domain:a.pattern.qeDomain||"learning-optimization",patternType:a.pattern.patternType,confidence:a.pattern.confidence,successRate:a.pattern.successRate||.5})),s=await e.loadPatternsAsConcepts(i);return this.logger.info(`Loaded ${s} patterns as concepts from ReasoningBank`),s}catch(t){return this.logger.warn("Failed to load patterns from ReasoningBank",{error:String(t)}),0}}async execute(e,t){let{action:n}=e;try{switch(n){case"dream":return this.runDreamCycle(e,t);case"insights":return this.getPendingInsights(e,t);case"apply":return this.applyInsight(e,t);case"history":return this.getDreamHistory(e,t);case"status":return this.getDreamStatus(e,t);default:return{success:!1,error:`Unknown action: ${n}`,data:{action:n,success:!1,error:`Unknown action: ${n}`}}}}catch(r){let i=E(r);return{success:!1,error:i,data:{action:n,success:!1,error:i}}}}async runDreamCycle(e,t){let n=Math.min(e.durationMs||3e4,6e4),r=e.minPatterns||10,i=e.loadFromReasoningBank!==!1;this.logger.info(`Starting dream cycle (${n}ms, min: ${r} patterns)`);let s=await this.getEngine({maxDurationMs:n,minConceptsRequired:r});if(i){let u=await this.loadPatternsFromReasoningBank(s);this.logger.info(`Loaded ${u} patterns from ReasoningBank`)}let a=await s.dream(n),c={cycleId:a.cycle.id,status:a.cycle.status,durationMs:a.cycle.durationMs||0,conceptsProcessed:a.cycle.conceptsProcessed,associationsFound:a.cycle.associationsFound,insightsGenerated:a.cycle.insightsGenerated,activationStats:a.activationStats,patternsCreated:a.patternsCreated},l=a.insights.map(u=>({id:u.id,type:u.type,description:u.description,noveltyScore:u.noveltyScore,confidenceScore:u.confidenceScore,actionable:u.actionable,applied:u.applied||!1,suggestedAction:u.suggestedAction,createdAt:u.createdAt?.toISOString()||new Date().toISOString()}));return this.logger.info(`Dream cycle complete: ${a.cycle.insightsGenerated} insights, ${a.cycle.associationsFound} associations found`),{success:!0,data:{action:"dream",success:!0,dreamResult:c,insights:l}}}async getPendingInsights(e,t){let n=e.limit||20;return{success:!0,data:{action:"insights",success:!0,insights:(await(await this.getEngine()).getPendingInsights(n)).map(a=>({id:a.id,type:a.type,description:a.description,noveltyScore:a.noveltyScore,confidenceScore:a.confidenceScore,actionable:a.actionable,applied:a.applied||!1,suggestedAction:a.suggestedAction,createdAt:a.createdAt?.toISOString()||new Date().toISOString()}))}}}async applyInsight(e,t){if(!e.insightId)return{success:!1,error:"insightId is required for apply action",data:{action:"apply",success:!1,error:"insightId is required for apply action"}};try{let r=await(await this.getEngine()).applyInsight(e.insightId);return r.success?(this.logger.info(`Applied insight ${e.insightId} \u2192 REAL pattern ${r.patternId} in ReasoningBank`),{success:!0,data:{action:"apply",success:!0,applyResult:{insightId:e.insightId,...r}}}):{success:!1,error:r.error,data:{action:"apply",success:!1,error:r.error}}}catch(n){let r=E(n);return{success:!1,error:r,data:{action:"apply",success:!1,error:r}}}}async getDreamHistory(e,t){let n=e.limit||20;return{success:!0,data:{action:"history",success:!0,history:(await(await this.getEngine()).getDreamHistory(n)).map(a=>({id:a.id,startTime:a.startTime.toISOString(),endTime:a.endTime?.toISOString(),durationMs:a.durationMs,status:a.status,conceptsProcessed:a.conceptsProcessed,associationsFound:a.associationsFound,insightsGenerated:a.insightsGenerated}))}}}async getDreamStatus(e,t){let n=await this.getEngine(),r=n.isDreaming(),i=n.getCurrentCycle(),s=await n.getDreamHistory(100),a=await n.getPendingInsights(100),c=s.reduce((d,m)=>d+m.insightsGenerated,0),l=s[0];return{success:!0,data:{action:"status",success:!0,status:{isDreaming:r,currentCycle:i?{id:i.id,startTime:i.startTime.toISOString(),endTime:i.endTime?.toISOString(),durationMs:i.durationMs,status:i.status,conceptsProcessed:i.conceptsProcessed,associationsFound:i.associationsFound,insightsGenerated:i.insightsGenerated}:void 0,totalCycles:s.length,totalInsights:c,pendingInsights:a.length,lastDreamTime:l?.startTime.toISOString()}}}}resetInstanceCache(){this.engine&&(this.engine.close().catch(console.error),this.engine=null)}};k();var Jn=class extends A{config={name:"qe/analysis/token_usage",description:"Analyze token consumption patterns and identify optimization opportunities across agents and domains.",domain:"learning-optimization",schema:Xd,streaming:!1,timeout:3e4};async execute(e,t){let{operation:n,timeframe:r,agentId:i,domain:s}=e;try{if(this.isAborted(t))return{success:!1,error:"Operation aborted"};let a;switch(n){case"session":a=this.getSessionUsage(r);break;case"agent":a=this.getAgentUsage(i,r);break;case"domain":a=this.getDomainUsage(s,r);break;case"task":a=this.getTaskUsage(r);break;case"efficiency":a=this.getEfficiencyReport(r);break;case"dashboard":return{success:!0,data:{operation:"dashboard",timeframe:r||"all",summary:{totalTokens:0,totalCost:"$0.00",tokensSaved:0,savingsPercentage:0},optimization:{patternsReused:0,cacheHits:0,earlyExits:0,recommendations:[Yi()]}}};default:return{success:!1,error:`Unknown operation: ${n}`}}return{success:!0,data:a}}catch(a){return{success:!1,error:`Token usage analysis failed: ${E(a)}`}}}getSessionUsage(e){let t=ie.getSessionSummary(e),n={};for(let[i,s]of t.byAgent)n[i]={tokens:s.totalTokens,cost:W(s.totalCost),tasks:s.tasksExecuted};let r={};for(let[i,s]of t.byDomain)r[i]={tokens:s.totalTokens,cost:W(s.estimatedCostUsd||0)};return{operation:"session",timeframe:e||"all",summary:{totalTokens:t.totalUsage.totalTokens,totalCost:W(t.totalUsage.estimatedCostUsd||0),tokensSaved:t.optimizationStats.tokensSaved,savingsPercentage:t.optimizationStats.savingsPercentage},breakdown:{byAgent:Object.keys(n).length>0?n:void 0,byDomain:Object.keys(r).length>0?r:void 0},optimization:{patternsReused:t.optimizationStats.patternsReused,cacheHits:t.optimizationStats.cacheHits,earlyExits:t.optimizationStats.earlyExits,recommendations:this.generateSessionRecommendations(t)}}}getAgentUsage(e,t){let n=ie.getAgentMetrics(e,t),r=ie.getSessionSummary(t);if(e&&!Array.isArray(n)){let d=n,m=d.tasksExecuted>0?d.patternsReused/d.tasksExecuted:0;return{operation:"agent",timeframe:t||"all",summary:{totalTokens:d.totalTokens,totalCost:W(d.totalCost),tokensSaved:d.estimatedTokensSaved,savingsPercentage:this.calculateSavingsPercentage(d.totalTokens,d.estimatedTokensSaved)},optimization:{patternsReused:d.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateAgentRecommendations(d)},details:{agentMetrics:{agentId:d.agentId,totalInputTokens:d.totalInputTokens,totalOutputTokens:d.totalOutputTokens,totalTokens:d.totalTokens,totalCost:W(d.totalCost),tasksExecuted:d.tasksExecuted,patternsReused:d.patternsReused,tokensSaved:d.estimatedTokensSaved,efficiency:Math.round(m*100)}}}}let i=Array.isArray(n)?n:[n],s={},a=0,c=0,l=0,u=0;for(let d of i)s[d.agentId]={tokens:d.totalTokens,cost:W(d.totalCost),tasks:d.tasksExecuted},a+=d.totalTokens,c+=d.totalCost,l+=d.estimatedTokensSaved,u+=d.patternsReused;return{operation:"agent",timeframe:t||"all",summary:{totalTokens:a,totalCost:W(c),tokensSaved:l,savingsPercentage:this.calculateSavingsPercentage(a,l)},breakdown:{byAgent:Object.keys(s).length>0?s:void 0},optimization:{patternsReused:u,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateMultiAgentRecommendations(i)}}}getDomainUsage(e,t){let n=ie.getDomainMetrics(e,t),r=ie.getSessionSummary(t);if(e&&!(n instanceof Map)){let l=n;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:l.totalTokens,totalCost:W(l.estimatedCostUsd||0),tokensSaved:r.optimizationStats.tokensSaved,savingsPercentage:r.optimizationStats.savingsPercentage},optimization:{patternsReused:r.optimizationStats.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateDomainRecommendations(e,l)},details:{domainMetrics:{domain:e,inputTokens:l.inputTokens,outputTokens:l.outputTokens,totalTokens:l.totalTokens,cost:W(l.estimatedCostUsd||0)}}}}let i=n instanceof Map?n:new Map,s={},a=0,c=0;for(let[l,u]of i)s[l]={tokens:u.totalTokens,cost:W(u.estimatedCostUsd||0)},a+=u.totalTokens,c+=u.estimatedCostUsd||0;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:a,totalCost:W(c),tokensSaved:r.optimizationStats.tokensSaved,savingsPercentage:r.optimizationStats.savingsPercentage},breakdown:{byDomain:Object.keys(s).length>0?s:void 0},optimization:{patternsReused:r.optimizationStats.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateMultiDomainRecommendations(i)}}}getTaskUsage(e){let t=ie.getTaskMetrics(e),n=ie.getSessionSummary(e),r=t.slice(-100).map(i=>({taskId:i.taskId,agentId:i.agentId,domain:i.domain,operation:i.operation,tokens:i.usage.totalTokens,cost:W(i.usage.estimatedCostUsd||0),patternReused:i.patternReused,tokensSaved:i.tokensSaved||0,timestamp:new Date(i.timestamp).toISOString()}));return{operation:"task",timeframe:e||"all",summary:{totalTokens:n.totalUsage.totalTokens,totalCost:W(n.totalUsage.estimatedCostUsd||0),tokensSaved:n.optimizationStats.tokensSaved,savingsPercentage:n.optimizationStats.savingsPercentage},optimization:{patternsReused:n.optimizationStats.patternsReused,cacheHits:n.optimizationStats.cacheHits,earlyExits:n.optimizationStats.earlyExits,recommendations:[`${t.length} tasks analyzed in timeframe`]},details:{taskMetrics:r}}}getEfficiencyReport(e){let t=ie.getEfficiencyReport(e),n=ie.getSessionSummary(e);return{operation:"efficiency",timeframe:e||"all",summary:{totalTokens:t.totalTokensUsed,totalCost:W(t.totalTokensUsed*3e-6+t.totalTokensUsed*15e-6),tokensSaved:t.totalTokensSaved,savingsPercentage:t.savingsPercentage},optimization:{patternsReused:n.optimizationStats.patternsReused,cacheHits:n.optimizationStats.cacheHits,earlyExits:n.optimizationStats.earlyExits,recommendations:t.recommendations}}}generateSessionRecommendations(e){let t=[];if(e.totalUsage.totalTokens===0)return["No token usage recorded yet. Start executing tasks to track consumption."];let{patternsReused:n,cacheHits:r,earlyExits:i,savingsPercentage:s}=e.optimizationStats;return s<10&&t.push("Token savings below 10%. Enable pattern reuse and caching for better efficiency."),n===0&&e.byAgent.size>0&&t.push("No patterns reused. Consider enabling the pattern store for similar tasks."),r===0&&e.totalUsage.totalTokens>1e4&&t.push("No cache hits detected. Enable response caching to reduce API calls."),i===0&&e.byAgent.size>1&&t.push("Early exit optimization not used. Enable high-confidence pattern matching."),s>25&&t.push(`Excellent token efficiency! ${s.toFixed(1)}% savings achieved.`),t.length>0?t:["Token usage is within normal parameters."]}generateAgentRecommendations(e){let t=[];if(e.tasksExecuted===0)return["No tasks executed by this agent yet."];e.patternsReused/e.tasksExecuted<.1&&t.push("Low pattern reuse rate. Consider caching successful patterns.");let r=e.totalTokens/e.tasksExecuted;return r>5e3&&t.push(`High average tokens per task (${Math.round(r)}). Consider optimizing prompts.`),e.totalOutputTokens>e.totalInputTokens*2&&t.push("High output-to-input ratio. Request more concise responses."),t.length>0?t:["Agent token usage is efficient."]}generateMultiAgentRecommendations(e){let t=[];if(e.length===0)return["No agent data available."];let n=[...e].sort((s,a)=>a.totalTokens-s.totalTokens);n[0].totalTokens>0&&t.push(`Highest consumer: ${n[0].agentId} (${n[0].totalTokens.toLocaleString()} tokens)`);let r=e.reduce((s,a)=>s+a.totalTokens,0);return n[0].totalTokens/(r||1)>.5&&e.length>1&&t.push("Token usage imbalanced. Consider distributing workload across agents."),t}generateDomainRecommendations(e,t){let n=[];return t.totalTokens===0?[`No token usage recorded for ${e}.`]:(e==="test-generation"&&t.totalTokens>1e4&&n.push("Test generation consuming significant tokens. Consider batching test requests."),e==="code-intelligence"&&t.outputTokens>t.inputTokens*3&&n.push("Code intelligence generating verbose output. Consider summary-only mode."),n.length>0?n:[`${e} token usage is normal.`])}generateMultiDomainRecommendations(e){let t=[];if(e.size===0)return["No domain data available."];let n=Array.from(e.entries()).sort((r,i)=>i[1].totalTokens-r[1].totalTokens);return n[0][1].totalTokens>0&&t.push(`Highest consuming domain: ${n[0][0]} (${n[0][1].totalTokens.toLocaleString()} tokens)`),t}calculateSavingsPercentage(e,t){let n=e+t;return n===0?0:Math.round(t/n*1e4)/100}},Xd={type:"object",properties:{operation:{type:"string",description:"Type of analysis to perform",enum:["session","agent","domain","task","efficiency","dashboard"]},timeframe:{type:"string",description:"Time period to analyze",enum:["1h","24h","7d","30d"]},agentId:{type:"string",description:"Specific agent ID to analyze (for agent operation)"},domain:{type:"string",description:"Specific domain to analyze (for domain operation)",enum:["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization"]}},required:["operation"]};k();function Pt(o){return o===void 0?null:typeof o!="number"||!Number.isInteger(o)||o<1?`constraints.maxSteps must be a positive integer, got ${String(o)}`:null}var Pi={coverage:{line:0,branch:0,function:0,target:80,measured:!1},quality:{testsPassing:0,totalTests:0,securityScore:100,performanceScore:100},fleet:{activeAgents:0,availableAgents:[],maxAgents:8},resources:{timeRemaining:3600,memoryAvailable:4096,parallelSlots:4},context:{environment:"development",riskLevel:"medium"},patterns:{available:0,reusable:0}};var Yd=[{name:"measure-coverage",description:"Run coverage analysis on the codebase to determine current coverage metrics",agentType:"qe-coverage-specialist",preconditions:{"coverage.measured":!1},effects:{"coverage.measured":!0},cost:2,estimatedDurationMs:3e4,successRate:.95,category:"coverage",qeDomain:"coverage-analysis",method:"analyze",params:{},implemented:!0},{name:"analyze-coverage-gaps",description:"Identify uncovered code paths and prioritize them by risk and complexity",agentType:"qe-gap-detector",preconditions:{"coverage.measured":!0},effects:{"coverage.gapsIdentified":!0},cost:1.5,estimatedDurationMs:15e3,successRate:.9,category:"coverage",qeDomain:"coverage-analysis",method:"detectGaps",params:{},implemented:!0},{name:"generate-coverage-tests",description:"Generate tests targeting identified coverage gaps using AI-powered analysis",agentType:"qe-test-generator",preconditions:{"coverage.gapsIdentified":!0},effects:{"coverage.line":{delta:10}},cost:4,estimatedDurationMs:6e4,successRate:.8,category:"coverage",qeDomain:"test-generation",method:"generateTests",params:{},implemented:!0},{name:"run-mutation-testing",description:"Run mutation testing to validate test effectiveness and find weak spots",agentType:"qe-mutation-tester",preconditions:{"coverage.line":{min:60}},effects:{"quality.mutationScore":{set:!0}},cost:5,estimatedDurationMs:12e4,successRate:.85,category:"coverage",qeDomain:"coverage-analysis",implemented:!1},{name:"prioritize-uncovered-paths",description:"Use sublinear O(log n) analysis to identify highest-risk uncovered paths",agentType:"qe-coverage-specialist",preconditions:{"coverage.gapsIdentified":!0},effects:{"coverage.riskPrioritized":!0},cost:1,estimatedDurationMs:1e4,successRate:.92,category:"coverage",qeDomain:"coverage-analysis",method:"calculateRisk",params:{},implemented:!0},{name:"generate-branch-tests",description:"Generate tests specifically targeting branch coverage improvements",agentType:"qe-test-generator",preconditions:{"coverage.measured":!0,"coverage.branch":{max:70}},effects:{"coverage.branch":{delta:8}},cost:3.5,estimatedDurationMs:45e3,successRate:.78,category:"coverage",qeDomain:"test-generation",method:"generateTests",params:{},implemented:!0}],Jd=[{name:"run-unit-tests",description:"Execute unit test suite with parallel execution",agentType:"qe-test-executor",preconditions:{},effects:{"quality.unitTestsRun":!0},cost:1,estimatedDurationMs:2e4,successRate:.95,category:"test",qeDomain:"test-execution",method:"runTests",params:{},implemented:!0},{name:"run-integration-tests",description:"Execute integration test suite with real database connections",agentType:"qe-test-executor",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.integrationTestsRun":!0},cost:2.5,estimatedDurationMs:45e3,successRate:.85,category:"test",qeDomain:"test-execution",method:"execute",params:{},implemented:!0},{name:"run-e2e-tests",description:"Execute end-to-end tests using Playwright or Cypress",agentType:"qe-e2e-tester",preconditions:{"quality.integrationTestsRun":!0},effects:{"quality.e2eTestsRun":!0},cost:4,estimatedDurationMs:9e4,successRate:.8,category:"test",qeDomain:"test-execution",method:"executeE2ETestSuite",params:{},implemented:!0},{name:"fix-failing-tests",description:"Analyze and fix failing tests based on error messages and stack traces",agentType:"qe-tdd-specialist",preconditions:{"quality.testsPassing":{max:90}},effects:{"quality.testsPassing":{delta:10}},cost:3,estimatedDurationMs:3e4,successRate:.75,category:"test",qeDomain:"test-generation",implemented:!1},{name:"fix-flaky-tests",description:"Identify and stabilize flaky tests by analyzing timing and async issues",agentType:"qe-flaky-hunter",preconditions:{"quality.flakyTests":{min:1}},effects:{"quality.flakyTests":{delta:-3}},cost:4,estimatedDurationMs:45e3,successRate:.7,category:"test",qeDomain:"test-execution",method:"detectFlaky",params:{},implemented:!0},{name:"generate-property-tests",description:"Generate property-based tests using fast-check or similar library",agentType:"qe-test-generator",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.propertyTestsGenerated":!0},cost:3.5,estimatedDurationMs:4e4,successRate:.82,category:"test",qeDomain:"test-generation",method:"generatePropertyTests",params:{},implemented:!0},{name:"run-contract-tests",description:"Execute consumer-driven contract tests using Pact or similar",agentType:"qe-contract-tester",preconditions:{"context.hasApiContracts":!0},effects:{"quality.contractTestsRun":!0},cost:2,estimatedDurationMs:25e3,successRate:.88,category:"test",qeDomain:"contract-testing",method:"verifyAllConsumers",params:{},implemented:!0}],Zd=[{name:"security-scan",description:"Run comprehensive security scan using SAST and dependency analysis",agentType:"qe-security-scanner",preconditions:{},effects:{"quality.securityScanned":!0},cost:2,estimatedDurationMs:3e4,successRate:.95,category:"security",qeDomain:"security-compliance",method:"runSecurityAudit",params:{},implemented:!0},{name:"fix-vulnerabilities",description:"Remediate identified security vulnerabilities and update dependencies",agentType:"qe-security-auditor",preconditions:{"quality.securityScanned":!0,"quality.vulnerabilities":{min:1}},effects:{"quality.vulnerabilities":{delta:-5},"quality.securityScore":{delta:10}},cost:5,estimatedDurationMs:6e4,successRate:.7,category:"security",qeDomain:"security-compliance",implemented:!1},{name:"owasp-audit",description:"Perform OWASP Top 10 security audit on the application",agentType:"qe-security-auditor",preconditions:{"quality.securityScanned":!0},effects:{"quality.owaspCompliant":!0},cost:3,estimatedDurationMs:45e3,successRate:.85,category:"security",qeDomain:"security-compliance",method:"runComplianceCheck",params:{standard:"owasp"},implemented:!0},{name:"scan-secrets",description:"Scan codebase for hardcoded secrets and credentials",agentType:"qe-security-scanner",preconditions:{},effects:{"quality.secretsScanned":!0},cost:1,estimatedDurationMs:15e3,successRate:.98,category:"security",qeDomain:"security-compliance",method:"runSecurityAudit",params:{includeSecrets:!0},implemented:!0},{name:"run-dast",description:"Run dynamic application security testing against running application",agentType:"qe-security-auditor",preconditions:{"context.environment":"staging"},effects:{"quality.dastCompleted":!0},cost:4.5,estimatedDurationMs:12e4,successRate:.8,category:"security",qeDomain:"security-compliance",method:"runDASTScan",params:{},implemented:!0}],em=[{name:"run-benchmarks",description:"Execute performance benchmarks to establish baseline metrics",agentType:"qe-performance-tester",preconditions:{},effects:{"quality.benchmarked":!0},cost:2,estimatedDurationMs:45e3,successRate:.9,category:"performance",qeDomain:"chaos-resilience",implemented:!1},{name:"load-test",description:"Run load testing with simulated concurrent traffic",agentType:"qe-load-tester",preconditions:{"context.environment":"staging"},effects:{"quality.loadTested":!0},cost:3.5,estimatedDurationMs:12e4,successRate:.85,category:"performance",qeDomain:"chaos-resilience",method:"runLoadTestSuite",params:{},implemented:!0},{name:"stress-test",description:"Run stress testing to find breaking points and system limits",agentType:"qe-chaos-engineer",preconditions:{"context.environment":"staging","quality.loadTested":!0},effects:{"quality.stressTested":!0},cost:4,estimatedDurationMs:9e4,successRate:.8,category:"performance",qeDomain:"chaos-resilience",method:"runTest",params:{type:"stress"},implemented:!0},{name:"profile-memory",description:"Profile memory usage and identify memory leaks",agentType:"qe-performance-tester",preconditions:{"quality.benchmarked":!0},effects:{"quality.memoryProfiled":!0},cost:2.5,estimatedDurationMs:6e4,successRate:.88,category:"performance",qeDomain:"chaos-resilience",implemented:!1},{name:"optimize-slow-tests",description:"Identify and optimize slow-running tests to improve CI/CD speed",agentType:"qe-performance-tester",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.testsOptimized":!0},cost:2,estimatedDurationMs:3e4,successRate:.82,category:"performance",qeDomain:"test-execution",implemented:!1}],tm=[{name:"analyze-complexity",description:"Measure cyclomatic and cognitive complexity of codebase",agentType:"code-analyzer",preconditions:{},effects:{"quality.complexityAnalyzed":!0},cost:1,estimatedDurationMs:15e3,successRate:.95,category:"analysis",qeDomain:"quality-assessment",method:"analyzeComplexity",params:{},implemented:!0},{name:"detect-code-smells",description:"Identify code smells and anti-patterns using static analysis",agentType:"code-analyzer",preconditions:{},effects:{"quality.smellsDetected":!0},cost:1.5,estimatedDurationMs:2e4,successRate:.9,category:"analysis",qeDomain:"code-intelligence",implemented:!1},{name:"analyze-dependencies",description:"Analyze dependency graph and identify circular or outdated dependencies",agentType:"code-analyzer",preconditions:{},effects:{"quality.dependenciesAnalyzed":!0},cost:1,estimatedDurationMs:15e3,successRate:.92,category:"analysis",qeDomain:"code-intelligence",method:"mapDependencies",params:{},implemented:!0},{name:"measure-technical-debt",description:"Calculate technical debt metrics and generate remediation plan",agentType:"code-analyzer",preconditions:{"quality.complexityAnalyzed":!0,"quality.smellsDetected":!0},effects:{"quality.technicalDebtMeasured":!0},cost:2,estimatedDurationMs:25e3,successRate:.88,category:"analysis",qeDomain:"code-intelligence",implemented:!1},{name:"build-knowledge-graph",description:"Build semantic knowledge graph of codebase for intelligent context retrieval",agentType:"qe-intelligence-builder",preconditions:{"quality.dependenciesAnalyzed":!0},effects:{"quality.knowledgeGraphBuilt":!0},cost:3,estimatedDurationMs:6e4,successRate:.85,category:"analysis",qeDomain:"code-intelligence",method:"index",params:{},implemented:!0}],nm=[{name:"spawn-test-agent",description:"Spawn additional test execution agent for parallel work",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{max:10}},effects:{"fleet.activeAgents":{delta:1}},cost:.5,estimatedDurationMs:5e3,successRate:.95,category:"fleet",qeDomain:"test-execution",implemented:!1},{name:"optimize-fleet-topology",description:"Reconfigure fleet topology for optimal task distribution",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:3}},effects:{"fleet.efficiency":{delta:15}},cost:1,estimatedDurationMs:1e4,successRate:.85,category:"fleet",implemented:!1},{name:"scale-down-fleet",description:"Reduce fleet size to conserve resources during low-activity periods",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:5}},effects:{"fleet.activeAgents":{delta:-2}},cost:.3,estimatedDurationMs:3e3,successRate:.98,category:"fleet",implemented:!1},{name:"spawn-specialist-agent",description:"Spawn a specialized agent for specific domain work",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{max:12},"context.specialistNeeded":!0},effects:{"fleet.activeAgents":{delta:1},"fleet.specialistAvailable":!0},cost:1,estimatedDurationMs:8e3,successRate:.9,category:"fleet",implemented:!1},{name:"rebalance-workload",description:"Redistribute tasks across agents based on current load",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:2}},effects:{"fleet.workloadBalanced":!0},cost:.5,estimatedDurationMs:5e3,successRate:.92,category:"fleet",implemented:!1}],rm=[{name:"generate-quality-report",description:"Generate comprehensive quality report combining all metrics",agentType:"qe-quality-gate",preconditions:{"coverage.measured":!0,"quality.unitTestsRun":!0},effects:{"quality.reported":!0},cost:1,estimatedDurationMs:1e4,successRate:.95,category:"quality",qeDomain:"quality-assessment",method:"analyzeQuality",params:{},implemented:!0},{name:"enforce-quality-gate",description:"Check if all quality gates pass and report status",agentType:"qe-quality-gate",preconditions:{"quality.reported":!0},effects:{"quality.gatePassed":!0},cost:.5,estimatedDurationMs:5e3,successRate:.9,category:"quality",qeDomain:"quality-assessment",method:"evaluateGate",params:{},implemented:!0},{name:"validate-requirements",description:"Validate that tests cover all documented requirements",agentType:"qe-requirements-validator",preconditions:{"context.hasRequirements":!0},effects:{"quality.requirementsValidated":!0},cost:2,estimatedDurationMs:2e4,successRate:.88,category:"quality",qeDomain:"requirements-validation",method:"validate",params:{},implemented:!0},{name:"predict-defects",description:"Use ML-based defect prediction to identify high-risk code areas",agentType:"qe-defect-predictor",preconditions:{"quality.complexityAnalyzed":!0,"coverage.measured":!0},effects:{"quality.defectsPredicted":!0},cost:2.5,estimatedDurationMs:3e4,successRate:.82,category:"quality",qeDomain:"defect-intelligence",method:"predictDefects",params:{},implemented:!0},{name:"generate-deployment-report",description:"Generate deployment readiness report with all quality metrics",agentType:"qe-quality-gate",preconditions:{"quality.gatePassed":!0,"quality.securityScanned":!0},effects:{"quality.deploymentReady":!0},cost:1.5,estimatedDurationMs:15e3,successRate:.9,category:"quality",qeDomain:"quality-assessment",method:"getDeploymentAdvice",params:{},implemented:!0}],im=[{name:"run-accessibility-audit",description:"Run WCAG 2.2 accessibility audit using axe-core or similar",agentType:"qe-accessibility-tester",preconditions:{"context.hasUI":!0},effects:{"quality.accessibilityAudited":!0},cost:2,estimatedDurationMs:3e4,successRate:.9,category:"quality",qeDomain:"visual-accessibility",method:"runAccessibilityAudit",params:{},implemented:!0},{name:"run-visual-regression",description:"Run visual regression testing with screenshot comparison",agentType:"qe-visual-tester",preconditions:{"context.hasUI":!0},effects:{"quality.visualRegressionRun":!0},cost:3,estimatedDurationMs:6e4,successRate:.85,category:"quality",qeDomain:"visual-accessibility",method:"runVisualTests",params:{},implemented:!0}],Ko=[...Yd,...Jd,...Zd,...em,...tm,...nm,...rm,...im];function sm(o){return`action-${o}`}function Xo(o){return{...o,id:sm(o.name),executionCount:0}}function me(){return Ko.map(Xo)}var Je=[{name:"achieve-90-percent-coverage",description:"Reach 90% line coverage through targeted test generation",conditions:{"coverage.line":{min:90}},priority:1,qeDomain:"coverage-analysis"},{name:"all-tests-passing",description:"All tests green with 100% pass rate",conditions:{"quality.testsPassing":{min:100}},priority:1,qeDomain:"test-execution"},{name:"security-compliant",description:"Pass security audit with no critical vulnerabilities",conditions:{"quality.securityScanned":!0,"quality.vulnerabilities":{max:0}},priority:2,qeDomain:"security-compliance"},{name:"deployment-ready",description:"Ready for production deployment with all quality gates passed",conditions:{"coverage.line":{min:80},"quality.testsPassing":{min:100},"quality.securityScanned":!0,"quality.gatePassed":!0},priority:1},{name:"performance-validated",description:"Performance benchmarks and load tests completed successfully",conditions:{"quality.benchmarked":!0,"quality.loadTested":!0},priority:2,qeDomain:"chaos-resilience"},{name:"code-quality-excellent",description:"Excellent code quality with low complexity and no code smells",conditions:{"quality.complexityAnalyzed":!0,"quality.smellsDetected":!0,"quality.technicalDebtMeasured":!0},priority:3,qeDomain:"code-intelligence"},{name:"full-test-suite",description:"Complete test suite with unit, integration, and e2e tests",conditions:{"quality.unitTestsRun":!0,"quality.integrationTestsRun":!0,"quality.e2eTestsRun":!0},priority:2,qeDomain:"test-execution"},{name:"accessibility-compliant",description:"WCAG 2.2 compliant with visual regression coverage",conditions:{"quality.accessibilityAudited":!0,"quality.visualRegressionRun":!0},priority:2,qeDomain:"visual-accessibility"}];X();import{randomUUID as Me}from"crypto";var Zn=1e3,ki=class{data=[];cmp;constructor(e){this.cmp=e}get length(){return this.data.length}push(e){this.data.push(e),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;let e=this.data[0],t=this.data.pop();return this.data.length>0&&(this.data[0]=t,this.sinkDown(0)),e}bubbleUp(e){for(;e>0;){let t=e-1>>1;if(this.cmp(this.data[e],this.data[t])<0)[this.data[e],this.data[t]]=[this.data[t],this.data[e]],e=t;else break}}sinkDown(e){let t=this.data.length;for(;;){let n=e,r=2*e+1,i=2*e+2;if(r<t&&this.cmp(this.data[r],this.data[n])<0&&(n=r),i<t&&this.cmp(this.data[i],this.data[n])<0&&(n=i),n!==e)[this.data[e],this.data[n]]=[this.data[n],this.data[e]],e=n;else break}}},am=new Set(["__proto__","constructor","prototype"]),er=class o{db=null;persistence=null;actions=new Map;initialized=!1;enablePlanReuse=!0;constructor(){}ensureDb(){if(!this.db)throw new Error("GOAPPlanner not initialized - call initialize() first");return this.db}async initialize(){if(this.initialized)return;this.persistence=Zi(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.ensureDb().prepare("SELECT COUNT(*) as count FROM goap_actions").get().count===0&&this.seedDefaultActions(),this.backfillActionMethodBindings(),this.backfillActionDurationEstimates(),await this.loadActions(),this.initialized=!0,console.log(`[GOAPPlanner] Initialized: ${this.persistence.getDbPath()}`)}seedDefaultActions(){let e=me(),t=this.ensureDb(),n=t.prepare(`
642
642
  INSERT INTO goap_actions (id, name, description, category, preconditions, effects, cost, qe_domain, agent_type, method, params, implemented, estimated_duration_ms)
643
643
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
644
644
  `);for(let i of e){let s=`action-${Date.now()}-${Me().slice(0,8)}`;n.run(s,i.name,i.description,i.category,JSON.stringify(i.preconditions),JSON.stringify(i.effects),i.cost,i.qeDomain??null,i.agentType??null,i.method??null,i.params?JSON.stringify(i.params):null,i.implemented?1:0,i.estimatedDurationMs??null)}let r=t.prepare(`
@@ -689,7 +689,7 @@ Analyze the requirements above and return the complete QualityCriteriaAnalysis.`
689
689
  `).run(i,a,e)}validatePlanForState(e,t){let n=this.cloneState(t);for(let r of e.actions){if(!this.meetsConditions(n,r.preconditions))return!1;n=this.applyAction(n,r)}return!0}planSatisfiesConstraints(e,t,n,r){let i=r?.maxSteps??20;if(e.actions.length>i||r?.maxDurationMs!==void 0&&e.actions.reduce((l,u)=>l+(u.estimatedDurationMs??Zn),0)>r.maxDurationMs)return!1;let s=new Set(this.getAvailableActions(r).map(l=>l.id));if(!e.actions.every(l=>s.has(l.id)))return!1;let a=this.cloneState(t),c=0;for(let l of e.actions)c+=this.getActionCost(l,a),a=this.applyAction(a,l);return r?.maxCost!==void 0&&c>r.maxCost?!1:this.meetsConditions(a,n)}hashGoalConditions(e){let t=this.sortObjectKeys(e);return JSON.stringify(t)}sortObjectKeys(e){return e===null||typeof e!="object"?e:Array.isArray(e)?e.map(t=>this.sortObjectKeys(t)):Object.keys(e).sort().reduce((t,n)=>(t[n]=this.sortObjectKeys(e[n]),t),{})}extractStateVector(e){return[e.coverage.line/100,e.coverage.branch/100,e.coverage.function/100,e.coverage.measured?1:0,e.quality.testsPassing/100,e.quality.securityScore/100,e.quality.performanceScore/100,Math.min(e.fleet.activeAgents/10,1),Math.min(e.resources.timeRemaining/3600,1),Math.min(e.resources.parallelSlots/8,1)]}async addGoal(e){await this.initialize();let t=`goal-${Date.now()}-${Me().slice(0,8)}`;return this.ensureDb().prepare(`
690
690
  INSERT INTO goap_goals (id, name, description, conditions, priority, qe_domain)
691
691
  VALUES (?, ?, ?, ?, ?, ?)
692
- `).run(t,e.name,e.description??null,JSON.stringify(e.conditions),e.priority,e.qeDomain??null),t}async getGoals(){return await this.initialize(),this.ensureDb().prepare("SELECT * FROM goap_goals ORDER BY priority DESC").all().map(t=>({id:t.id,name:t.name,description:t.description??void 0,conditions:M(t.conditions),priority:t.priority,qeDomain:t.qe_domain}))}setPlanReuseEnabled(e){this.enablePlanReuse=e}isPlanReuseEnabled(){return this.enablePlanReuse}async getPlanReuseStats(){await this.initialize();let e=this.ensureDb(),t=e.prepare("SELECT COUNT(*) as count FROM goap_plan_signatures").get(),n=e.prepare("SELECT COUNT(*) as count FROM goap_plan_signatures WHERE usage_count > 0").get(),r=e.prepare("SELECT AVG(success_rate) as avg FROM goap_plan_signatures WHERE usage_count > 0").get();return{totalPlans:t.count,reusedPlans:n.count,reuseRate:t.count>0?n.count/t.count:0,avgSuccessRate:r.avg??0}}async close(){this.actions.clear(),this.db=null,this.persistence=null,this.initialized=!1}},xi=null;function Ie(){return xi||(xi=new er),xi}yc();mt();ue();k();X();import{randomUUID as Mi}from"crypto";var om={maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,maxReplans:3,parallelExecution:!1,recordWorldState:!0,useUnified:!0,dryRun:!1};function Jo(o,e=2e3){try{let t=typeof o=="string"?o:JSON.stringify(o);return t.length>e?`${t.slice(0,e)}...(truncated)`:t}catch{return String(o)}}function cm(o){if(o==null)return"unknown error";if(o instanceof Error||typeof o=="string")return E(o);let e=o.message;return typeof e=="string"?e:Jo(o,500)}var tr="__execution_cancelled__",Yo="cancelled",Ze=class{constructor(e,t,n,r,i){this.getDomainAPI=i;this.planner=e,this.spawner=t,this.config={...om,...r},this.config.useUnified||(this.db=Ki(n??":memory:",{walMode:!1}),this.db.pragma("journal_mode = WAL"))}getDomainAPI;db;planner;spawner;config;currentExecution=null;initialized=!1;unifiedMemory=null;async initialize(){if(!this.initialized){if(this.config.useUnified)try{this.unifiedMemory=Q(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[PlanExecutor] Using unified storage: ${this.unifiedMemory.getDbPath()}`)}catch(e){console.warn("[PlanExecutor] Failed to initialize unified storage, falling back to in-memory:",e),this.db=new(await import("./better-sqlite3-IYVR5EQY.js")).default(":memory:"),this.db.pragma("journal_mode = WAL"),this.unifiedMemory=null,this.createTables()}else this.createTables();this.initialized=!0}}createTables(){this.db.exec(`
692
+ `).run(t,e.name,e.description??null,JSON.stringify(e.conditions),e.priority,e.qeDomain??null),t}async getGoals(){return await this.initialize(),this.ensureDb().prepare("SELECT * FROM goap_goals ORDER BY priority DESC").all().map(t=>({id:t.id,name:t.name,description:t.description??void 0,conditions:M(t.conditions),priority:t.priority,qeDomain:t.qe_domain}))}setPlanReuseEnabled(e){this.enablePlanReuse=e}isPlanReuseEnabled(){return this.enablePlanReuse}async getPlanReuseStats(){await this.initialize();let e=this.ensureDb(),t=e.prepare("SELECT COUNT(*) as count FROM goap_plan_signatures").get(),n=e.prepare("SELECT COUNT(*) as count FROM goap_plan_signatures WHERE usage_count > 0").get(),r=e.prepare("SELECT AVG(success_rate) as avg FROM goap_plan_signatures WHERE usage_count > 0").get();return{totalPlans:t.count,reusedPlans:n.count,reuseRate:t.count>0?n.count/t.count:0,avgSuccessRate:r.avg??0}}async close(){this.actions.clear(),this.db=null,this.persistence=null,this.initialized=!1}},xi=null;function Ie(){return xi||(xi=new er),xi}yc();mt();ue();k();X();import{randomUUID as Mi}from"crypto";var om={maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,maxReplans:3,parallelExecution:!1,recordWorldState:!0,useUnified:!0,dryRun:!1};function Jo(o,e=2e3){try{let t=typeof o=="string"?o:JSON.stringify(o);return t.length>e?`${t.slice(0,e)}...(truncated)`:t}catch{return String(o)}}function cm(o){if(o==null)return"unknown error";if(o instanceof Error||typeof o=="string")return E(o);let e=o.message;return typeof e=="string"?e:Jo(o,500)}var tr="__execution_cancelled__",Yo="cancelled",Ze=class{constructor(e,t,n,r,i){this.getDomainAPI=i;this.planner=e,this.spawner=t,this.config={...om,...r},this.config.useUnified||(this.db=Ki(n??":memory:",{walMode:!1}),this.db.pragma("journal_mode = WAL"))}getDomainAPI;db;planner;spawner;config;currentExecution=null;initialized=!1;unifiedMemory=null;async initialize(){if(!this.initialized){if(this.config.useUnified)try{this.unifiedMemory=Q(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[PlanExecutor] Using unified storage: ${this.unifiedMemory.getDbPath()}`)}catch(e){console.warn("[PlanExecutor] Failed to initialize unified storage, falling back to in-memory:",e),this.db=new(await import("./better-sqlite3-IQKBFVAO.js")).default(":memory:"),this.db.pragma("journal_mode = WAL"),this.unifiedMemory=null,this.createTables()}else this.createTables();this.initialized=!0}}createTables(){this.db.exec(`
693
693
  CREATE TABLE IF NOT EXISTS goap_execution_steps (
694
694
  id TEXT PRIMARY KEY,
695
695
  plan_id TEXT NOT NULL,
@@ -739,4 +739,4 @@ Expected effects:`;for(let[n,r]of Object.entries(e.effects))typeof r=="object"&&
739
739
  `);t.steps.forEach((r,i)=>{n.run(r.id,t.planId,e,r.action.id,i,r.status,r.retries,r.startedAt.toISOString(),r.durationMs??null,r.agentId??null,r.agentOutput??null,r.worldStateBefore?JSON.stringify(r.worldStateBefore):null,r.worldStateAfter?JSON.stringify(r.worldStateAfter):null,r.error??null)}),t.status==="cancelled"&&n.run(`${e}-${Yo}`,t.planId,e,tr,t.steps.length,Yo,0,new Date().toISOString(),null,null,null,null,null,t.error??"Execution was cancelled");try{this.db.prepare(`
740
740
  UPDATE goap_plans SET status = ?, executed_at = COALESCE(executed_at, ?), completed_at = ?
741
741
  WHERE id = ?
742
- `).run(t.status==="completed"?"completed":t.status==="cancelled"?"cancelled":"failed",new Date(Date.now()-t.totalDurationMs).toISOString(),new Date().toISOString(),t.planId)}catch(r){console.warn("[PlanExecutor] Failed to update goap_plans status (non-fatal):",r)}}async updateActionStats(e,t,n){try{"updateActionStats"in this.planner&&await this.planner.updateActionStats(e,t,n)}catch(r){console.warn("[PlanExecutor] Failed to update action stats:",r)}}meetsConditions(e,t){for(let[n,r]of Object.entries(t))if(!this.checkCondition(e,n,r))return!1;return!0}checkCondition(e,t,n){let r=this.getStateValue(e,t);return typeof n=="string"||typeof n=="number"||typeof n=="boolean"?r===n:!(typeof n=="object"&&n!==null&&("min"in n&&n.min!==void 0&&(typeof r!="number"||r<n.min)||"max"in n&&n.max!==void 0&&(typeof r!="number"||r>n.max)||"eq"in n&&n.eq!==void 0&&r!==n.eq))}applyEffects(e,t){let n=this.cloneState(e);for(let[r,i]of Object.entries(t))this.applyEffect(n,r,i);return n}applyEffect(e,t,n){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean"){this.setStateValue(e,t,n);return}if(typeof n=="object"&&n!==null){let r=this.getStateValue(e,t);if("set"in n&&n.set!==void 0&&this.setStateValue(e,t,n.set),"delta"in n&&n.delta!==void 0&&typeof r=="number"){let i=Math.max(0,Math.min(100,r+n.delta));this.setStateValue(e,t,i)}}}getStateValue(e,t){let n=t.split("."),r=e;for(let i of n){if(r==null)return;r=r[i]}return r}setStateValue(e,t,n){let r=t.split("."),i=new Set(["__proto__","constructor","prototype"]);for(let c of r)if(i.has(c)){console.warn(`[PlanExecutor] Blocked prototype pollution attempt: ${t}`);return}let s=e;for(let c=0;c<r.length-1;c++){let l=r[c];Object.hasOwn(s,l)||Object.defineProperty(s,l,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0});let u=Object.getOwnPropertyDescriptor(s,l);if(!u)return;s=u.value}let a=r[r.length-1];Object.defineProperty(s,a,{value:n,writable:!0,enumerable:!0,configurable:!0})}cloneState(e){return{coverage:{...e.coverage},quality:{...e.quality},fleet:{...e.fleet,availableAgents:[...e.fleet.availableAgents]},resources:{...e.resources},context:{...e.context},patterns:{...e.patterns}}}delay(e){return new Promise(t=>setTimeout(t,e))}async close(){this.currentExecution&&await this.cancel(),this.db&&(this.unifiedMemory?console.log("[PlanExecutor] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[PlanExecutor] Database closed"))),this.unifiedMemory=null,this.initialized=!1}},et=class{successRate;executionDelay;constructor(e){this.successRate=e?.successRate??1,this.executionDelay=e?.executionDelay??100}async spawn(e,t){await new Promise(i=>setTimeout(i,this.executionDelay));let n=oe()<this.successRate,r=`mock-agent-${Mi().slice(0,8)}`;return n?{agentId:r,output:`Successfully executed task for ${e}: ${t.slice(0,50)}...`,success:!0}:{agentId:r,output:"",success:!1,error:`Simulated failure for ${e}`}}};function Ii(o,e){let t=new et({successRate:e?.successRate??1});return new Ze(o,t,e?.dbPath,e?.config)}import*as nr from"fs";import*as Ni from"path";Bt();var lm=["coverage.line","coverage.branch","coverage.function","coverage.target","coverage.measured","quality.testsPassing","quality.totalTests","quality.securityScore","quality.performanceScore","fleet.activeAgents","fleet.availableAgents","fleet.maxAgents","resources.timeRemaining","resources.memoryAvailable","resources.parallelSlots","context.environment","context.riskLevel","patterns.available","patterns.reusable"],Zo=Ni.join("coverage","coverage-summary.json"),um=32*1024*1024;async function dm(){try{let{getFleetState:o,isFleetInitialized:e}=await import("./core-handlers-CUEPOQIO.js");if(!e())return null;let{queen:t,kernel:n}=o();if(!t||!n)return null;let r=t.listAllAgents(),i=[...new Set(r.filter(s=>s.status==="running"||s.status==="idle").map(s=>s.type))].sort();return{activeAgents:r.filter(s=>s.status==="running").length,maxAgents:n.getConfig().maxConcurrentAgents,availableAgents:i}}catch{return null}}function Di(o){return typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=100}function mm(o=Ut()){let e=Ni.join(o,Zo);try{let t=nr.statSync(e);if(!t.isFile()||t.size>um)return null;let n=JSON.parse(nr.readFileSync(e,"utf-8")),r=n.total?.lines?.pct,i=n.total?.branches?.pct,s=n.total?.functions?.pct;return!Di(r)||!Di(i)||!Di(s)?null:{line:r,branch:i,function:s,source:Zo,measuredAt:t.mtime.toISOString()}}catch{return null}}function pm(){let o=Pi;return{coverage:{...o.coverage},quality:{...o.quality},fleet:{...o.fleet,availableAgents:[...o.fleet.availableAgents]},resources:{...o.resources},context:{...o.context},patterns:{...o.patterns}}}async function xt(o={}){let e=pm(),t={};for(let s of lm)t[s]="default";let n=await(o.readFleet??dm)();n&&(e.fleet.activeAgents=n.activeAgents,e.fleet.maxAgents=n.maxAgents,e.fleet.availableAgents=[...n.availableAgents],t["fleet.activeAgents"]="live",t["fleet.maxAgents"]="live",t["fleet.availableAgents"]="live");let r=(o.readCoverage??(()=>mm()))(),i;if(r){e.coverage.line=r.line,e.coverage.branch=r.branch,e.coverage.function=r.function,e.coverage.measured=!0;for(let s of["coverage.line","coverage.branch","coverage.function","coverage.measured"])t[s]="measured";i={source:r.source,measuredAt:r.measuredAt}}return{state:e,provenance:t,fleetInitialized:n!==null,coverageReport:i}}var De=o=>typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=100?null:"a number between 0 and 100",tt=o=>typeof o=="number"&&Number.isInteger(o)&&o>=0?null:"a non-negative integer",ec=o=>typeof o=="number"&&Number.isFinite(o)&&o>=0?null:"a non-negative number",gm=o=>typeof o=="boolean"?null:"a boolean",fm=o=>Array.isArray(o)&&o.every(e=>typeof e=="string")?null:"an array of strings",tc=(...o)=>e=>typeof e=="string"&&o.includes(e)?null:`one of ${o.join(", ")}`,hm={"coverage.line":De,"coverage.branch":De,"coverage.function":De,"coverage.target":De,"coverage.measured":gm,"quality.testsPassing":De,"quality.totalTests":tt,"quality.securityScore":De,"quality.performanceScore":De,"fleet.activeAgents":tt,"fleet.availableAgents":fm,"fleet.maxAgents":tt,"resources.timeRemaining":ec,"resources.memoryAvailable":ec,"resources.parallelSlots":tt,"context.environment":tc("development","staging","production"),"context.riskLevel":tc("low","medium","high"),"patterns.available":tt,"patterns.reusable":tt},Oi=["coverage","quality","fleet","resources","context","patterns"],_i=null;function ym(){if(!_i){let o=new Set;for(let e of me()){for(let t of Object.keys(e.preconditions))o.add(t);for(let t of Object.keys(e.effects))o.add(t)}for(let e of Je)for(let t of Object.keys(e.conditions))o.add(t);_i=o}return _i}function nc(o,e=[]){if(typeof o!="object"||o===null||Array.isArray(o))return"currentState must be an object";let t=new Set([...ym(),...e]);for(let[n,r]of Object.entries(o)){if(!Oi.includes(n))return`currentState.${n} is not a world-state section (expected one of ${Oi.join(", ")})`;if(typeof r!="object"||r===null||Array.isArray(r))return`currentState.${n} must be an object`;for(let[i,s]of Object.entries(r)){let a=`${n}.${i}`,c=hm[a];if(c){let l=c(s);if(l)return`currentState.${a} must be ${l}, got ${JSON.stringify(s)}`;continue}if(!t.has(a))return`currentState.${a} is not a known world-state field`;if(typeof s!="boolean"&&typeof s!="string"&&!(typeof s=="number"&&Number.isFinite(s)))return`currentState.${a} must be a boolean, string or finite number, got ${JSON.stringify(s)}`}}return null}function rc(o,e){let t=o.state,n={...o.provenance};for(let r of Oi){let i=e[r];if(!(typeof i!="object"||i===null||Array.isArray(i)))for(let[s,a]of Object.entries(i))s==="__proto__"||s==="constructor"||s==="prototype"||(t[r][s]=Array.isArray(a)?[...a]:a,n[`${r}.${s}`]="caller")}return{...o,provenance:n}}function rr(o){return Object.entries(o).filter(([,e])=>e==="default").map(([e])=>e).sort()}var ic=["maxCost","maxDurationMs","maxSteps","requiredAgentTypes","excludedActions"],At=class extends A{constructor(t={}){super();this.worldStateSources=t}worldStateSources;planner=null;config={name:"qe/planning/goap_plan",description:'Find optimal action plan to achieve a QE goal using A* search. Supports named goals (e.g., "achieve-90-percent-coverage") or custom goal conditions.',domain:"coordination",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{goal:{type:"string",description:'Goal name (e.g., "achieve-90-percent-coverage") or custom goal conditions as JSON object'},currentState:{type:"object",description:"Current world state (auto-detected if not provided). Contains coverage, quality, fleet, resources, context, and patterns."},constraints:{type:"object",description:"Plan constraints",properties:{maxCost:{type:"number",description:"Maximum total cost allowed"},maxDurationMs:{type:"number",description:"Maximum total duration in milliseconds"},maxSteps:{type:"number",description:"Maximum number of steps (actions) in the plan; positive integer",minimum:1},requiredAgentTypes:{type:"array",description:"Only use actions that these agent types can execute",items:{type:"string",description:"Agent type"}},excludedActions:{type:"array",description:"Exclude these specific action IDs",items:{type:"string",description:"Action ID"}}}}},required:["goal"]}}async getPlanner(){return this.planner||(this.planner=Ie(),await this.planner.initialize()),this.planner}resetInstanceCache(){this.planner=null}async execute(t,n){try{let r=this.validateConstraints(t.constraints);if(r)return{success:!1,error:r};let i=await this.getPlanner(),s;if(typeof t.goal=="string"){let m=await i.getGoals(),p=m.find(g=>g.name===t.goal);if(!p){let g=m.map(f=>f.name).join(", ");return{success:!1,error:`Unknown goal: ${t.goal}. Available goals: ${g||"none (seed actions first)"}`}}s=p.conditions}else s=t.goal;if(t.currentState!==void 0){let m=nc(t.currentState,[...i.getReferencedStateKeys(),...Object.keys(s)]);if(m)return{success:!1,error:`Invalid currentState: ${m}`}}let a=t.currentState?rc(await xt(this.worldStateSources),t.currentState):await xt(this.worldStateSources),c=a.state,l=rr(a.provenance),u=t.constraints?{maxCost:t.constraints.maxCost,maxDurationMs:t.constraints.maxDurationMs,maxSteps:t.constraints.maxSteps,requiredAgentTypes:t.constraints.requiredAgentTypes,excludedActions:t.constraints.excludedActions}:void 0,d=await i.findPlan(c,s,u);return d?(l.length===0?this.markAsRealData():this.markAsEstimatedData(),{success:!0,data:{planId:d.id,goal:t.goal,actions:d.actions.map(m=>({name:m.name,agentType:m.agentType,cost:m.cost,category:m.category,description:m.description})),totalCost:d.totalCost,estimatedDurationMs:d.estimatedDurationMs,stepCount:d.actions.length,reusedFrom:d.reusedFrom,similarityScore:d.similarityScore,stateProvenance:a.provenance,defaultedFields:l}}):{success:!1,error:`No valid plan found for the given goal and constraints${u?.maxSteps!==void 0?` (maxSteps: ${u.maxSteps} \u2014 the goal may need more steps)`:""}. Try relaxing constraints or seeding more actions.`}}catch(r){return{success:!1,error:E(r)}}}validateConstraints(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return"constraints must be an object";let n=t,r=Object.keys(n).filter(s=>!ic.includes(s));if(r.length>0)return`Unknown constraint(s): ${r.join(", ")}. Supported constraints: ${ic.join(", ")}`;for(let s of["maxCost","maxDurationMs"]){let a=n[s];if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||a<0))return`constraints.${s} must be a non-negative number, got ${String(a)}`}let i=Pt(n.maxSteps);if(i)return i;for(let s of["requiredAgentTypes","excludedActions"]){let a=n[s];if(a!==void 0&&(!Array.isArray(a)||!a.every(c=>typeof c=="string")))return`constraints.${s} must be an array of strings`}return null}};k();var kt=class extends A{planner=null;executor=null;config={name:"qe/planning/goap_execute",description:"Execute a GOAP plan. Each action dispatches to a real domain API method when the action is marked implemented and a kernel is available (run fleet_init first); actions with no real implementation, or with no domain/kernel available, fail with a specific reason rather than reporting a fabricated success. Supports dry-run mode to preview the plan without executing anything.",domain:"coordination",schema:this.buildSchema(),timeout:3e5};buildSchema(){return{type:"object",properties:{planId:{type:"string",description:"ID of plan to execute (from goap_plan result)"},dryRun:{type:"boolean",description:"Simulate execution without spawning agents (default: false)",default:!1},stepByStep:{type:"boolean",description:"Execute one step at a time (default: false)",default:!1},maxRetries:{type:"number",description:"Max retries per failed step (default: 2)",default:2,minimum:0,maximum:5}},required:["planId"]}}async getPlanner(){return this.planner||(this.planner=Ie(),await this.planner.initialize()),this.planner}async getExecutor(e){if(!this.executor){let t=await this.getPlanner(),n=r=>e?.getDomainAPI(r);this.executor=new Ze(t,new et,void 0,{maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,parallelExecution:!1,recordWorldState:!0},n),await this.executor.initialize()}return this.executor}resetInstanceCache(){this.planner=null,this.executor=null}async execute(e,t){try{let r=await(await this.getPlanner()).getPlan(e.planId);if(!r)return{success:!1,error:`Plan not found: ${e.planId}. Create a plan first using goap_plan.`};if(e.dryRun)return this.markAsRealData(),{success:!0,data:{planId:r.id,mode:"dry-run",status:"completed",stepsCompleted:r.actions.length,stepsFailed:0,totalDurationMs:r.estimatedDurationMs,steps:r.actions.map(c=>({action:c.name,status:"would-execute",retries:0,durationMs:c.estimatedDurationMs}))}};let i=await sn(t),s=await this.getExecutor(i);if(s.isExecuting())return{success:!1,error:"Another plan is currently executing. Wait for completion or cancel it."};let a=await s.execute(r,r.initialState);return this.markAsRealData(),{success:a.status==="completed",data:{planId:a.planId,mode:"execution",status:a.status,stepsCompleted:a.stepsCompleted,stepsFailed:a.stepsFailed,totalDurationMs:a.totalDurationMs,steps:a.steps.map(c=>({action:c.action.name,status:c.status,retries:c.retries,durationMs:c.durationMs,error:c.error})),error:a.error},error:a.status!=="completed"?a.error:void 0}}catch(n){return{success:!1,error:E(n)}}}};k();var Fi=["pending","executing","completed","failed","cancelled"],Mt=class extends A{constructor(t={}){super();this.worldStateSources=t}worldStateSources;planner=null;executor=null;config={name:"qe/planning/goap_status",description:"Get GOAP system status: world state, available goals, actions, or plans. Use to understand current state and available planning options.",domain:"coordination",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{type:{type:"string",description:"What to get status of",enum:["world","goals","actions","plans","execution"]},filter:{type:"object",description:"Optional filters",properties:{category:{type:"string",description:"Filter actions by category (test, security, coverage, etc.)"},status:{type:"string",description:"Filter plans by status (pending, executing, completed, failed, cancelled)",enum:[...Fi]},limit:{type:"number",description:"Maximum number of results (default: 20)",default:20,minimum:1,maximum:100}}}},required:["type"]}}async getPlanner(){return this.planner||(this.planner=Ie(),await this.planner.initialize()),this.planner}async getExecutor(){if(!this.executor){let t=await this.getPlanner();this.executor=Ii(t),await this.executor.initialize()}return this.executor}resetInstanceCache(){this.planner=null,this.executor=null}async execute(t,n){try{switch(t.type){case"world":return this.getWorldState();case"goals":return this.getGoals();case"actions":return this.getActions(t.filter?.category,t.filter?.limit);case"plans":return this.getPlans(t.filter?.status,t.filter?.limit);case"execution":return this.getExecutionStatus();default:return{success:!1,error:`Unknown status type: ${t.type}`}}}catch(r){return{success:!1,error:E(r)}}}async getWorldState(){let t=await xt(this.worldStateSources),{state:n,provenance:r}=t,i=l=>r[l]!=="default",s=(l,u)=>i(l)?u:null,a=rr(r);return["coverage.line","coverage.branch","coverage.function","quality.testsPassing","quality.securityScore","quality.performanceScore","fleet.activeAgents","fleet.maxAgents","resources.timeRemaining","resources.parallelSlots"].every(i)?this.markAsRealData():this.markAsEstimatedData(),{success:!0,data:{type:"world",data:{coverage:{line:s("coverage.line",n.coverage.line),branch:s("coverage.branch",n.coverage.branch),function:s("coverage.function",n.coverage.function),measured:n.coverage.measured,...t.coverageReport?{report:t.coverageReport}:{}},quality:{testsPassing:s("quality.testsPassing",n.quality.testsPassing),securityScore:s("quality.securityScore",n.quality.securityScore),performanceScore:s("quality.performanceScore",n.quality.performanceScore)},fleet:{initialized:t.fleetInitialized,activeAgents:n.fleet.activeAgents,maxAgents:s("fleet.maxAgents",n.fleet.maxAgents),availableAgents:[...n.fleet.availableAgents]},resources:{timeRemaining:s("resources.timeRemaining",n.resources.timeRemaining),parallelSlots:s("resources.parallelSlots",n.resources.parallelSlots)},provenance:r,defaultedFields:a}}}}async getGoals(){let n=await(await this.getPlanner()).getGoals();return this.markAsRealData(),{success:!0,data:{type:"goals",data:{goals:n.map(r=>({id:r.id,name:r.name,description:r.description,priority:r.priority,conditionCount:Object.keys(r.conditions).length})),count:n.length}}}}async getActions(t,n=50){let r=[],i=me(),s=t?i.filter(c=>c.category===t):i;r=s.slice(0,n).map((c,l)=>({id:`action-${l}`,name:c.name,category:c.category,agentType:c.agentType,cost:c.cost,successRate:c.successRate}));let a={};for(let c of i)a[c.category]=(a[c.category]||0)+1;return this.markAsRealData(),{success:!0,data:{type:"actions",data:{actions:r,count:s.length,byCategory:a}}}}async getPlans(t,n=20){if(t!==void 0&&!Fi.includes(t))return{success:!1,error:`filter.status must be one of: ${Fi.join(", ")}`};let r=await this.getPlanner(),[{plans:i,count:s,invalidPlanIds:a},c]=await Promise.all([r.listPlanSummaries(t,n),r.getPlanReuseStats()]);return this.markAsRealData(),{success:!0,data:{type:"plans",data:{plans:i,count:s,...a?{invalidPlanIds:a}:{},reuseStats:{totalPlans:c.totalPlans,reusedPlans:c.reusedPlans,reuseRate:c.reuseRate,avgSuccessRate:c.avgSuccessRate}}}}}async getExecutionStatus(){let n=(await this.getExecutor()).isExecuting();return this.markAsRealData(),{success:!0,data:{type:"execution",data:{isExecuting:n,message:n?"Plan execution in progress":"No active execution"}}}}};k();mt();ue();k();k();mt();var It={HEALTH:"qe/mincut/health",ANALYZE:"qe/mincut/analyze",STRENGTHEN:"qe/mincut/strengthen"};function Gi(){return gr()}function wm(){return fr()}var Li=class extends A{config={name:It.HEALTH,description:"Analyze swarm topology health using MinCut algorithms. Reports connectivity, weak points, and health trends.",domain:"coordination",schema:{type:"object",properties:{agents:{type:"array",description:"Agent vertices to add to the graph before analysis"},edges:{type:"array",description:"Edges to add between agents"},includeWeakVertices:{type:"boolean",description:"Include detailed weak vertex analysis",default:!0},includeHistory:{type:"boolean",description:"Include historical health data",default:!1}},additionalProperties:!0}};async execute(e,t){let n=Gi(),r=wm(),i=ve();if(e.agents)for(let l of e.agents)n.hasVertex(l.id)||n.addVertex({id:l.id,type:"agent",domain:l.domain,weight:l.weight??1,createdAt:new Date});if(e.edges)for(let l of e.edges)n.hasVertex(l.source)&&n.hasVertex(l.target)&&(n.hasEdge(l.source,l.target)||n.addEdge({source:l.source,target:l.target,weight:l.weight??1,type:"coordination",bidirectional:!0}));let s=r.checkHealth(),a=e.includeWeakVertices!==!1?i.findWeakVertices(n):[],c={health:{status:s.status,minCutValue:s.minCutValue,healthyThreshold:s.healthyThreshold,warningThreshold:s.warningThreshold,weakVertexCount:s.weakVertexCount,trend:s.trend},topology:{vertexCount:n.vertexCount,edgeCount:n.edgeCount,isConnected:n.isConnected()}};return e.includeWeakVertices!==!1&&a.length>0&&(c.weakVertices=a.map(l=>({id:l.vertexId,domain:l.vertex?.domain,weightedDegree:l.weightedDegree,riskScore:l.riskScore,reason:l.reason}))),e.includeHistory&&(c.history=s.history.map(l=>({timestamp:l.timestamp,value:l.value}))),this.markAsRealData(),{success:!0,data:c,metadata:this.createMetadata(t.startTime,t.requestId)}}},qi=class extends A{config={name:It.ANALYZE,description:"Deep analysis of swarm topology using MinCut algorithms. Identifies weak points, suggests improvements.",domain:"coordination",schema:{type:"object",properties:{weaknessThreshold:{type:"number",description:"Threshold for weak vertex detection"},includePartitioningPoints:{type:"boolean",description:"Include analysis of potential partitioning points",default:!1}},additionalProperties:!0}};async execute(e,t){let n=Gi(),r=ve(),i=r.getMinCutValue(n),s=r.getMinDegreeVertex(n),a=r.findWeakVertices(n,e.weaknessThreshold),c=r.suggestEdgeAdditions(n,2),l={minCutValue:i,minDegreeVertex:s,weakVertices:a.map(u=>({id:u.vertexId,weightedDegree:u.weightedDegree,riskScore:u.riskScore,reason:u.reason,suggestions:u.suggestions.map(d=>({type:d.type,priority:d.priority,estimatedImprovement:d.estimatedImprovement}))})),suggestedEdges:c.map(u=>({source:u.source,target:u.target,weight:u.weight}))};return e.includePartitioningPoints&&(l.partitioningPoints=r.findPartitioningPoints(n)),this.markAsRealData(),{success:!0,data:l,metadata:this.createMetadata(t.startTime,t.requestId)}}},$i=class extends A{config={name:It.STRENGTHEN,description:"Strengthen swarm topology by adding edges between weak and strong vertices.",domain:"coordination",schema:{type:"object",properties:{targetImprovement:{type:"number",description:"Target improvement in MinCut value",default:1},targetVertices:{type:"array",description:"Specific vertices to strengthen"},apply:{type:"boolean",description:"Apply changes (true) or simulate (false)",default:!1}},additionalProperties:!0}};async execute(e,t){let n=Gi(),r=ve(),i=r.getMinCutValue(n),s=e.targetImprovement??1,a=r.suggestEdgeAdditions(n,s),c=[];if(e.apply)for(let u of a)n.addEdge({source:u.source,target:u.target,weight:u.weight,type:"coordination",bidirectional:!0}),c.push({type:"add_edge",source:u.source,target:u.target,weight:u.weight});else for(let u of a)c.push({type:"add_edge",source:u.source,target:u.target,weight:u.weight});let l=r.getMinCutValue(n);return this.markAsRealData(),{success:!0,data:{beforeMinCut:i,afterMinCut:e.apply?l:i+s,improvement:e.apply?l-i:s,actionsApplied:c,applied:e.apply??!1},metadata:this.createMetadata(t.startTime,t.requestId)}}},oc=[new Li,new qi,new $i];k();var ji=null,ir=null;async function Dt(){return ji||ir||(ir=(async()=>{let o=gn({embedding:{model:"all-MiniLM-L6-v2",cacheSize:1e3,normalize:!0,hyperbolic:!1,curvature:-1},autoInitialize:!1});return await o.initialize(),ji=o,console.error("[EmbeddingTool] ONNX adapter initialized"),o})(),ir)}var nt=class extends A{config={name:"qe/embeddings/generate",description:"Generate a vector embedding for text using local ONNX model",domain:"learning-optimization",schema:{type:"object",properties:{text:{type:"string",description:"Text to generate embedding for",minLength:1,maxLength:1e4},hyperbolic:{type:"boolean",description:"Use hyperbolic space for hierarchical data",default:!1}},required:["text"]}};async execute(e,t){let n=performance.now();try{let r=await Dt(),i=await r.generateEmbedding(e.text);e.hyperbolic&&(i=r.toHyperbolic(i));let s=performance.now()-n;return this.markAsRealData(),{success:!0,data:{embedding:Array.from(i.vector),dimension:i.dimensions,isHyperbolic:i.isHyperbolic,latencyMs:s,model:i.model}}}catch(r){return{success:!1,error:`Embedding generation failed: ${E(r)}`}}}},rt=class extends A{config={name:"qe/embeddings/compare",description:"Compare semantic similarity between two texts",domain:"learning-optimization",schema:{type:"object",properties:{text1:{type:"string",description:"First text to compare",minLength:1},text2:{type:"string",description:"Second text to compare",minLength:1},metric:{type:"string",description:"Similarity metric",enum:["cosine","euclidean","poincare"],default:"cosine"}},required:["text1","text2"]}};async execute(e,t){let n=performance.now();try{let r=await Dt(),i=e.metric||"cosine",s=i==="cosine"?"cosine":i==="euclidean"?"euclidean":"poincare",a=await r.compareSimilarity(e.text1,e.text2,s),c=performance.now()-n;return this.markAsRealData(),{success:!0,data:{similarity:a,metric:i,isSimilar:a>.7,latencyMs:c}}}catch(r){return{success:!1,error:`Similarity comparison failed: ${E(r)}`}}}},it=class extends A{config={name:"qe/embeddings/search",description:"Search for semantically similar texts using vector search",domain:"learning-optimization",schema:{type:"object",properties:{query:{type:"string",description:"Query text to search for",minLength:1},namespace:{type:"string",description:"Namespace to search in",default:"default"},topK:{type:"number",description:"Number of results to return",minimum:1,maximum:100,default:10},threshold:{type:"number",description:"Minimum similarity threshold (0-1)",minimum:0,maximum:1,default:.5}},required:["query"]}};async execute(e,t){let n=performance.now();try{let i=await(await Dt()).searchByText(e.query,{metric:"cosine",topK:e.topK??10,threshold:e.threshold??.5,namespace:e.namespace}),s=performance.now()-n;return this.markAsRealData(),{success:!0,data:{results:i.map(a=>({text:a.text,score:a.score,metadata:a.metadata})),totalFound:i.length,latencyMs:s}}}catch(r){return{success:!1,error:`Search failed: ${E(r)}`}}}},st=class extends A{config={name:"qe/embeddings/store",description:"Store text with its embedding for later retrieval",domain:"learning-optimization",schema:{type:"object",properties:{text:{type:"string",description:"Text to store",minLength:1},id:{type:"string",description:"Optional ID for the stored embedding"},namespace:{type:"string",description:"Namespace for organization",default:"default"},metadata:{type:"object",description:"Additional metadata to store"}},required:["text"]}};async execute(e,t){let n=performance.now();try{let r=await Dt(),i=e.namespace||"default",s=await r.generateAndStore(e.text,{id:e.id,namespace:i,customData:e.metadata}),a=performance.now()-n;return this.markAsRealData(),{success:!0,data:{id:s.id,namespace:s.namespace||i,latencyMs:a}}}catch(r){return{success:!1,error:`Store failed: ${E(r)}`}}}},at=class extends A{config={name:"qe/embeddings/stats",description:"Get ONNX embedding system statistics",domain:"learning-optimization",schema:{type:"object",properties:{}}};async execute(e,t){try{let n=await Dt(),r=n.getStats(),i=await n.getHealth(),s=r.cacheHits+r.cacheMisses,a=s>0?r.cacheHits/s:0;return this.markAsRealData(),{success:!0,data:{totalGenerated:r.totalGenerated,vectorsStored:r.vectorsStored,cache:{hits:r.cacheHits,misses:r.cacheMisses,hitRate:a},model:{name:r.currentModel,dimension:r.currentModel==="all-MiniLM-L6-v2"?384:768},healthy:i.available}}}catch(n){return{success:!1,error:`Stats failed: ${E(n)}`}}}},Rm=new nt,Pm=new rt,xm=new it,Am=new st,km=new at;k();var Mm={type:"object",properties:{nodes:{type:"array",description:"Array of nodes to check for coherence. Each node must have an id and embedding vector."},energyThreshold:{type:"number",description:"Custom energy threshold for contradiction detection (default: 0.4)",minimum:0,maximum:1}},required:["nodes"]},_t=class extends A{config={name:"qe/coherence/check",description:"Check mathematical coherence of beliefs/facts using Prime Radiant sheaf cohomology. Detects contradictions and computes coherence energy for multi-agent coordination.",domain:"learning-optimization",schema:Mm,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await be(Ce)),this.coherenceService}resetInstanceCache(){this.coherenceService&&(this.coherenceService.dispose(),this.coherenceService=null)}async execute(e,t){let n=Date.now(),{nodes:r,energyThreshold:i=.4}=e;if(!r||r.length===0)return{success:!1,error:"At least one node is required for coherence check"};for(let s of r)if(!s.embedding||!Array.isArray(s.embedding))return{success:!1,error:`Node ${s.id} has invalid embedding - must be an array of numbers`};try{let s=await this.getService(),a=r.map(m=>({id:m.id,embedding:m.embedding,weight:m.weight??1,metadata:m.metadata})),c=await s.checkCoherence(a),l=[...c.recommendations,...this.generateAdditionalRecommendations(c,i)],u=c.contradictions.map(m=>({nodeIds:m.nodeIds,severity:String(m.severity),description:m.description||`Contradiction between nodes ${m.nodeIds[0]} and ${m.nodeIds[1]}`})),d=Date.now()-n;return this.markAsRealData(),{success:!0,data:{isCoherent:c.isCoherent,energy:c.energy,lane:c.lane,contradictions:u,recommendations:l,nodeCount:r.length,executionTimeMs:d,usedFallback:c.usedFallback}}}catch(s){return s instanceof Error&&s.message.includes("WASM")?(this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{isCoherent:!0,energy:.1,lane:"reflex",contradictions:[],recommendations:["WASM module unavailable - coherence check running in fallback mode","Install prime-radiant-advanced-wasm for full coherence verification"],nodeCount:r.length,executionTimeMs:Date.now()-n,usedFallback:!0}}):{success:!1,error:E(s)}}}generateAdditionalRecommendations(e,t){let n=[];switch(e.energy>t&&n.push(`High coherence energy (${e.energy.toFixed(3)}) detected - review contradicting beliefs`),e.lane){case"reflex":n.push("Low energy - safe for immediate execution");break;case"retrieval":n.push("Moderate energy - consider fetching additional context");break;case"heavy":n.push("High energy - deep analysis recommended");break;case"human":n.push("Critical energy - escalate to Queen coordinator");break}return n}};var Im=["rename","framework-transfer","reordered-steps","distractor-terminology","cross-domain-transfer"],RR=[["async-race","observe completion before assertion","await the operation","increase the timeout","completion probe","unit","vitest"],["stale-cache","invalidate on every state mutation","invalidate the cache","retry the read","freshness assertion","integration","redis"],["transaction-leak","rollback isolates each test","rollback the transaction","truncate a shared table","row-count check","database","postgres"],["clock-skew","compare times in one clock domain","inject a monotonic clock","widen the time window","clock boundary check","unit","node"],["event-loss","subscribe before publishing","register the listener first","publish twice","delivery assertion","events","eventemitter"],["resource-leak","release resources on every exit","close in a finally block","raise the pool limit","handle-count check","integration","playwright"],["eventual-consistency","poll the observable state","poll with a bounded deadline","sleep for a fixed delay","state convergence","distributed","kubernetes"],["identity-confusion","compare canonical identities","normalize the identifier","use display names","identity equality","security","oauth"],["partial-write","publish only complete state","commit through an atomic swap","ignore missing fields","atomicity check","filesystem","node"],["order-dependence","tests start from isolated state","reset state in setup","force alphabetical order","shuffle repeat","unit","jest"],["schema-drift","validate at the boundary","reject the incompatible schema","cast the payload","schema validator","api","zod"],["backpressure-loss","producer respects consumer capacity","await the drain signal","increase buffer memory","loss counter","performance","streams"],["retry-duplication","retries preserve idempotency","attach an idempotency key","disable all retries","duplicate detector","api","fetch"],["permission-bypass","authorization precedes mutation","check permission before write","hide the user interface","denial assertion","security","express"],["encoding-mismatch","encode and decode with one charset","set UTF-8 explicitly","strip non-ASCII text","round-trip equality","api","json"],["pagination-gap","cursor advances from the last item","use the returned cursor","increase page size","set equality","api","graphql"],["cancellation-leak","cancellation propagates to children","forward the abort signal","wait for natural completion","abort observation","integration","abortcontroller"],["floating-point-boundary","compare numeric results by tolerance","use an error bound","round every input","relative-error check","unit","vitest"],["locale-dependence","format under an explicit locale","pass the locale explicitly","update the snapshot locally","multi-locale check","ui","intl"],["lock-starvation","lock acquisition remains fair","queue lock waiters","raise retry count","bounded-wait check","concurrency","mutex"]].map(([o,e,t,n,r,i,s])=>({mechanism:o,invariant:e,action:t,wrongAction:n,oracle:r,domain:i,framework:s}));var Dm=Object.freeze([...Im]);Wi();k();var GR=Gt.create("qe-unified-memory");var Om={"test-suites":{dimensions:Se.DIMENSIONS,M:8,efConstruction:100,efSearch:50,metric:"cosine",namespace:"test-suites-hnsw",maxElements:1e5},coverage:{dimensions:Se.DIMENSIONS,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},defects:{dimensions:Se.DIMENSIONS,M:32,efConstruction:400,efSearch:200,metric:"cosine",namespace:"defects-hnsw",maxElements:1e5},quality:{dimensions:Se.DIMENSIONS,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"quality-hnsw",maxElements:1e5},learning:{dimensions:Se.DIMENSIONS,M:24,efConstruction:300,efSearch:150,metric:"cosine",namespace:"learning-hnsw",maxElements:1e5},coordination:{dimensions:Se.DIMENSIONS,M:8,efConstruction:100,efSearch:50,metric:"cosine",namespace:"coordination-hnsw",maxElements:5e4}},Nm={enableHNSW:{"test-suites":!0,coverage:!0,defects:!0,quality:!0,learning:!0,coordination:!0},defaultNamespace:"qe-unified",enableCrossDomainSearch:!0,embeddingDimension:Se.DIMENSIONS};Wi();k();import{randomUUID as Fm}from"crypto";var zi=Gt.create("MemoryAuditor"),Ui={batchSize:50,energyThreshold:.4,hotspotThreshold:.6,maxRecommendations:10},sr=class{constructor(e,t,n=Ui){this.coherenceService=e;this.eventBus=t;this.config=n}coherenceService;eventBus;config;isAuditing=!1;async auditPatterns(e){let t=Date.now();await this.emitEvent("memory:audit_started",{totalPatterns:e.length,timestamp:new Date});try{let n=this.groupByDomain(e),r=[],i=0,s=0;for(let[p,g]of Object.entries(n)){if(g.length<2)continue;let f=this.patternsToNodes(g),h=await this.coherenceService.checkCoherence(f);s+=h.energy,i+=h.contradictions.length,h.energy>this.config.hotspotThreshold&&r.push({domain:p,patternIds:g.map(v=>v.id),energy:h.energy,description:this.describeHotspot(h,p)})}let a=Object.keys(n).length,c=a>0?s/a:0,l=await this.identifyHotspots(e),u=await this.generateRecommendations(l,e),d=Date.now()-t,m={totalPatterns:e.length,scannedPatterns:e.length,contradictionCount:i,globalEnergy:c,hotspots:l,recommendations:u,duration:d,timestamp:new Date};return await this.emitEvent("memory:audit_completed",{result:m,timestamp:new Date}),m}catch(n){try{await this.emitEvent("memory:audit_failed",{error:E(n),timestamp:new Date})}catch(r){zi.warn("Failed to emit audit_failed event",{error:E(r)})}throw n}}async identifyHotspots(e){let t=[],n=this.groupByDomain(e);for(let[r,i]of Object.entries(n)){if(i.length<2)continue;let s=this.patternsToNodes(i),a=await this.coherenceService.checkCoherence(s);a.energy>this.config.hotspotThreshold&&t.push({domain:r,patternIds:i.map(c=>c.id),energy:a.energy,description:this.describeHotspot(a,r)})}return t}async generateRecommendations(e,t){let n=[],r=new Map(t.map(i=>[i.id,i]));for(let i of e){let s=i.patternIds.map(u=>r.get(u)).filter(u=>u!==void 0),a=this.findDuplicates(s);a.length>0&&n.push({type:"merge",patternIds:a,reason:`Detected ${a.length} similar patterns in ${i.domain} domain`,priority:"high"});let c=this.findOutdated(s);c.length>0&&n.push({type:"remove",patternIds:c,reason:`Found ${c.length} outdated patterns with low usage/success`,priority:"medium"}),i.energy>.7&&n.push({type:"review",patternIds:i.patternIds,reason:`Critical coherence energy (${i.energy.toFixed(2)}) in ${i.domain}`,priority:"high"});let l=this.findBroadPatterns(s);l.length>0&&n.push({type:"split",patternIds:l,reason:`Found ${l.length} overly generic patterns that should be specialized`,priority:"low"})}return n.sort((i,s)=>this.priorityValue(s.priority)-this.priorityValue(i.priority)).slice(0,this.config.maxRecommendations)}async runBackgroundAudit(e){if(this.isAuditing){zi.warn("Audit already in progress, skipping");return}this.isAuditing=!0;try{await this.emitEvent("memory:audit_progress",{status:"fetching_patterns",timestamp:new Date});let t=await e();await this.emitEvent("memory:audit_progress",{status:"analyzing_coherence",totalPatterns:t.length,timestamp:new Date});let n=await this.auditPatterns(t);await this.emitEvent("memory:audit_progress",{status:"completed",result:n,timestamp:new Date})}catch(t){await this.emitEvent("memory:audit_progress",{status:"failed",error:E(t),timestamp:new Date})}finally{this.isAuditing=!1}}groupByDomain(e){let t={};for(let n of e){let r=n.qeDomain;t[r]||(t[r]=[]),t[r].push(n)}return t}patternsToNodes(e){return e.map(t=>({id:t.id,embedding:t.embedding||this.createFallbackEmbedding(t),weight:t.qualityScore,metadata:{name:t.name,description:t.description,domain:t.qeDomain,confidence:t.confidence,usageCount:t.usageCount,successRate:t.successRate}}))}createFallbackEmbedding(e){let t=`${e.name} ${e.description}`,n=[];for(let r=0;r<64;r++){let i=t.charCodeAt(r%t.length);n.push(i/255*2-1)}return n}describeHotspot(e,t){let n=e.energy.toFixed(2),r=e.contradictions.length;return r>0?`${t} has ${r} contradiction(s) with energy ${n}`:`${t} has high coherence energy (${n}) indicating potential inconsistencies`}findDuplicates(e){let t=[],n=new Map;for(let r of e){let i=this.normalizeText(`${r.name} ${r.description}`);n.has(i)||n.set(i,[]),n.get(i).push(r.id)}for(let[r,i]of n)i.length>1&&t.push(...i.slice(1));return t}findOutdated(e){return e.filter(t=>t.usageCount<5&&t.successRate<.5).map(t=>t.id)}findBroadPatterns(e){return e.filter(t=>{let n=/generic|general|common|basic/i.test(t.name),r=t.context?.tags,i=!r||r.length<2;return n||i}).map(t=>t.id)}normalizeText(e){return e.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim()}priorityValue(e){switch(e){case"high":return 3;case"medium":return 2;case"low":return 1;default:return 0}}async emitEvent(e,t){if(this.eventBus)try{await this.eventBus.publish({id:`memory-audit-${Date.now()}-${Fm().split("-")[0]}`,type:e,source:"learning-optimization",timestamp:new Date,payload:t})}catch(n){zi.warn("Failed to emit event",{eventType:e,error:E(n)})}}};function Bi(o,e,t){return new sr(o,e,{...Ui,...t})}k();var Lm={type:"object",properties:{namespace:{type:"string",description:"Namespace to audit (default: qe-patterns)",default:"qe-patterns"},maxPatterns:{type:"number",description:"Maximum patterns to scan (default: 1000)",default:1e3,minimum:1,maximum:1e4},energyThreshold:{type:"number",description:"Energy threshold for flagging issues (default: 0.4)",default:.4,minimum:0,maximum:1},includeDetails:{type:"boolean",description:"Include detailed pattern information in results",default:!1}},required:[]},Ot=class extends A{config={name:"qe/coherence/audit",description:"Audit QE memory for contradictions and coherence issues. Scans patterns, detects hotspots, and generates remediation recommendations.",domain:"learning-optimization",schema:Lm,streaming:!1,timeout:6e4};coherenceService=null;auditor=null;async getService(){return this.coherenceService||(this.coherenceService=await be(Ce)),this.coherenceService}resetInstanceCache(){this.coherenceService&&(this.coherenceService.dispose(),this.coherenceService=null),this.auditor=null}async execute(e,t){let{namespace:n="qe-patterns",maxPatterns:r=1e3,energyThreshold:i=.4}=e;try{let s=await this.getService();this.auditor||(this.auditor=Bi(s,void 0,{energyThreshold:i,hotspotThreshold:i+.2,maxRecommendations:10}));let a=await O(),c=pr(a,{namespace:n,embeddingDimension:384});await c.initialize();let l=await c.search("",{limit:r,useVectorSearch:!1}),u=l.success?l.value.map(p=>p.pattern):[],d;u.length>0?d=await this.auditor.auditPatterns(u):d={totalPatterns:0,scannedPatterns:0,contradictionCount:0,globalEnergy:0,hotspots:[],recommendations:[],duration:0,timestamp:new Date};let m=this.calculateHealthScore(d);return this.markAsRealData(),{success:!0,data:{totalPatterns:d.totalPatterns,scannedPatterns:d.scannedPatterns,contradictionCount:d.contradictionCount,globalEnergy:d.globalEnergy,hotspots:d.hotspots.map(p=>({domain:p.domain,patternIds:p.patternIds,energy:p.energy,description:p.description})),recommendations:d.recommendations.map(p=>({type:p.type,patternIds:p.patternIds,reason:p.reason,priority:p.priority})),durationMs:d.duration,timestamp:d.timestamp.toISOString(),healthScore:m}}}catch(s){return s instanceof Error&&s.message.includes("WASM")?(this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{totalPatterns:0,scannedPatterns:0,contradictionCount:0,globalEnergy:0,hotspots:[],recommendations:[{type:"review",patternIds:[],reason:"WASM module unavailable - install prime-radiant-advanced-wasm for full audit",priority:"medium"}],durationMs:0,timestamp:new Date().toISOString(),healthScore:100}}):{success:!1,error:E(s)}}}calculateHealthScore(e){let t=100;t-=Math.min(30,e.contradictionCount*5),t-=Math.min(30,e.globalEnergy*50),t-=Math.min(20,e.hotspots.length*5);let n=e.recommendations.filter(r=>r.priority==="high").length;return t-=Math.min(20,n*5),Math.max(0,Math.round(t))}};k();function qm(o){let e="Each vote must be { agentId: string, verdict: string | number | boolean, confidence: number 0-1 }.";for(let t=0;t<o.length;t++){let n=o[t];if(typeof n!="object"||n===null||Array.isArray(n))return`votes[${t}] must be an object. ${e}`;let{agentId:r,verdict:i,confidence:s}=n;if(typeof r!="string"||r.trim()==="")return`votes[${t}].agentId must be a non-empty string. ${e}`;let a=typeof i;if(a!=="string"&&a!=="number"&&a!=="boolean")return`votes[${t}].verdict is required (string, number, or boolean), got ${i===null?"null":a}. ${e}`;if(typeof s!="number"||!Number.isFinite(s)||s<0||s>1)return`votes[${t}].confidence must be a number between 0 and 1, got ${JSON.stringify(s)??"undefined"}. ${e}`}return null}var $m={type:"object",properties:{votes:{type:"array",description:"Array of agent votes to verify for consensus (at least 2). Each vote is an object { agentId: string, verdict: string | number | boolean, confidence: number 0-1, agentType?: string, reasoning?: string }.",items:{type:"object",description:"One agent vote",properties:{agentId:{type:"string",description:"Agent identifier",minLength:1},agentType:{type:"string",description:"Agent type (default: worker)"},confidence:{type:"number",description:"Confidence in the verdict",minimum:0,maximum:1},reasoning:{type:"string",description:"Optional reasoning text"}},required:["agentId","verdict","confidence"]}},confidenceThreshold:{type:"number",description:"Minimum confidence threshold (0-1, default: 0.5)",default:.5,minimum:0,maximum:1}},required:["votes"]},Nt=class extends A{config={name:"qe/coherence/consensus",description:"Verify multi-agent consensus mathematically using spectral analysis. Detects false consensus where agents appear to agree but have divergent beliefs.",domain:"learning-optimization",schema:$m,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await be(Ce)),this.coherenceService}resetInstanceCache(){this.coherenceService&&(this.coherenceService.dispose(),this.coherenceService=null)}async execute(e,t){let n=Date.now(),{votes:r,confidenceThreshold:i=.5}=e;if(!r||r.length===0)return{success:!1,error:"At least one vote is required for consensus verification"};if(r.length<2)return{success:!1,error:"At least two votes are required to verify consensus"};let s=qm(r);if(s)return{success:!1,error:s};try{let a=await this.getService(),c=r.map(p=>({agentId:p.agentId,agentType:p.agentType||"worker",verdict:p.verdict,confidence:p.confidence,reasoning:p.reasoning,timestamp:new Date})),l=await a.verifyConsensus(c),u=l.recommendation,d=r.reduce((p,g)=>p+g.confidence,0)/r.length;d<i&&(u=`Low average confidence (${(d*100).toFixed(1)}%) - consider gathering more evidence. `+u);let m=Date.now()-n;return this.markAsRealData(),{success:!0,data:{isValid:l.isValid,isFalseConsensus:l.isFalseConsensus,confidence:l.confidence,fiedlerValue:l.fiedlerValue,collapseRisk:l.collapseRisk,recommendation:u,usedFallback:l.usedFallback,executionTimeMs:m}}}catch(a){if(a instanceof Error&&a.message.includes("WASM")){let c=this.simpleMajorityAnalysis(r);return this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{...c,recommendation:`Running in fallback mode (simple analysis): ${ts(es(r))} across ${r.length} votes. Install prime-radiant-advanced-wasm for spectral consensus analysis.`,usedFallback:!0,executionTimeMs:Date.now()-n}}}return{success:!1,error:E(a)}}}simpleMajorityAnalysis(e){let t=new Map;for(let s of e){let a=String(s.verdict);t.set(a,(t.get(a)||0)+1)}let n=0;for(let s of t.values())s>n&&(n=s);let r=n/e.length,i=e.reduce((s,a)=>s+a.confidence,0)/e.length;return{isValid:r>=.5&&i>=.5,isFalseConsensus:!1,confidence:i,fiedlerValue:0,collapseRisk:1-r}}};k();var Gm={type:"object",properties:{swarmState:{type:"object",description:"Current state of the swarm including agents and task info"},riskThreshold:{type:"number",description:"Risk threshold for warning (0-1, default: 0.5)",default:.5,minimum:0,maximum:1}},required:["swarmState"]},Ft=class extends A{config={name:"qe/coherence/collapse",description:"Predict swarm collapse risk using spectral analysis. Identifies vulnerable vertices and provides mitigation recommendations.",domain:"learning-optimization",schema:Gm,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await be(Ce)),this.coherenceService}resetInstanceCache(){this.coherenceService&&(this.coherenceService.dispose(),this.coherenceService=null)}async execute(e,t){let n=Date.now(),{swarmState:r,riskThreshold:i=.5}=e;if(!r)return{success:!1,error:"swarmState is required"};if(!r.agents||r.agents.length<1)return{success:!1,error:"At least one agent is required in swarmState"};try{let s=await this.getService(),a={agents:r.agents.map(g=>({agentId:g.agentId,agentType:g.agentType||"worker",health:Number.isFinite(g.health)?g.health:1,beliefs:[],lastActivity:new Date,errorCount:g.errorCount??0,successRate:Number.isFinite(g.successRate)?g.successRate:1})),activeTasks:Number.isFinite(r.activeTasks)?r.activeTasks:0,pendingTasks:Number.isFinite(r.pendingTasks)?r.pendingTasks:0,errorRate:Number.isFinite(r.errorRate)?r.errorRate:0,utilization:Number.isFinite(r.utilization)?r.utilization:0,timestamp:new Date},c=await s.predictCollapse(a),l=Number.isFinite(c.risk)?c.risk:0,u=this.categorizeRisk(l),d=[...c.recommendations,...this.generateAdditionalRecommendations(c,r)],m=Date.now()-n;this.markAsRealData();let p=u==="high"||u==="critical"||u==="medium"&&l>=i;return{success:!0,data:{risk:l,isAtRisk:p,riskLevel:u,fiedlerValue:c.fiedlerValue,collapseImminent:c.collapseImminent,weakVertices:c.weakVertices,recommendations:d,executionTimeMs:m,usedFallback:c.usedFallback}}}catch(s){if(s instanceof Error&&s.message.includes("WASM")){let a=this.heuristicAnalysis(r,i);return this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{...a,recommendations:["Running in fallback mode (heuristic analysis)","Install prime-radiant-advanced-wasm for spectral collapse prediction",...a.recommendations],usedFallback:!0,executionTimeMs:Date.now()-n}}}return{success:!1,error:E(s)}}}categorizeRisk(e){return!Number.isFinite(e)||e<.25?"low":e<.5?"medium":e<.75?"high":"critical"}generateAdditionalRecommendations(e,t){let n=[];t.errorRate>.1&&n.push(`High system error rate (${(t.errorRate*100).toFixed(1)}%) - investigate root causes`),t.utilization>.85&&n.push(`High resource utilization (${(t.utilization*100).toFixed(1)}%) - consider scaling`),t.pendingTasks>t.activeTasks*2&&n.push(`Large task backlog (${t.pendingTasks} pending) - may need more agents`);let r=t.agents.filter(i=>i.health<.5);return r.length>0&&n.push(`${r.length} agent(s) with low health - consider replacement`),e.risk>=.75&&n.unshift("\u26A0\uFE0F CRITICAL: Immediate action required to prevent collapse"),n}heuristicAnalysis(e,t){let n=0,r=[],i=[],s=Number.isFinite(e.errorRate)?e.errorRate:0,a=Number.isFinite(e.utilization)?e.utilization:0,c=Number.isFinite(e.pendingTasks)?e.pendingTasks:0,l=Number.isFinite(e.activeTasks)?e.activeTasks:0,u=e.agents.map(f=>Number.isFinite(f.health)?f.health:1),d=u.length>0?u.reduce((f,h)=>f+h,0)/u.length:1;n+=(1-d)*.3,n+=Math.min(.25,s*2.5),a>.7&&(n+=(a-.7)*.5);let m=c/Math.max(1,l);m>1&&(n+=Math.min(.2,(m-1)*.1)),e.agents.forEach((f,h)=>{(u[h]<.5||(f.errorCount??0)>5)&&i.push(f.agentId)}),n=Math.min(1,n),n>=t&&(r.push("Consider reducing task load"),r.push("Monitor agent health closely")),i.length>0&&r.push(`Reinforce weak agents: ${i.join(", ")}`),n<.25&&r.push("Swarm appears stable - continue normal operations");let p=this.categorizeRisk(n),g=p==="high"||p==="critical"||p==="medium"&&n>=t;return{risk:n,isAtRisk:g,riskLevel:p,fiedlerValue:0,collapseImminent:n>=.75,weakVertices:i,recommendations:r}}};var cc=[new _t,new Ot,new Nt,new Ft],lc={COHERENCE_CHECK:"qe/coherence/check",COHERENCE_AUDIT:"qe/coherence/audit",COHERENCE_CONSENSUS:"qe/coherence/consensus",COHERENCE_COLLAPSE:"qe/coherence/collapse"};var Lt=(S=>(S.PROBLEM_UNDERSTANDING="H1.1-problem-understanding",S.RULE_OF_THREE="H1.2-rule-of-three",S.PROBLEM_COMPLEXITY="H1.3-problem-complexity",S.USER_NEEDS_IDENTIFICATION="H2.1-user-needs-identification",S.USER_NEEDS_SUITABILITY="H2.2-user-needs-suitability",S.USER_NEEDS_VALIDATION="H2.3-user-needs-validation",S.BUSINESS_NEEDS_IDENTIFICATION="H3.1-business-needs-identification",S.USER_VS_BUSINESS_BALANCE="H3.2-user-vs-business-balance",S.KPI_IMPACT_ANALYSIS="H3.3-kpi-impact-analysis",S.ORACLE_PROBLEM_DETECTION="H4.1-oracle-problem-detection",S.WHAT_MUST_NOT_CHANGE="H4.2-what-must-not-change",S.SUPPORTING_DATA_ANALYSIS="H4.3-supporting-data-analysis",S.GUI_FLOW_IMPACT="H5.1-gui-flow-impact",S.USER_FEELINGS_IMPACT="H5.2-user-feelings-impact",S.CROSS_FUNCTIONAL_IMPACT="H5.3-cross-functional-impact",S.DATA_DEPENDENT_IMPACT="H5.4-data-dependent-impact",S.COMPETITIVE_ANALYSIS="H6.1-competitive-analysis",S.DOMAIN_INSPIRATION="H6.2-domain-inspiration",S.INNOVATIVE_SOLUTIONS="H6.3-innovative-solutions",S.EXACTNESS_AND_CLARITY="H7.1-exactness-and-clarity",S.INTUITIVE_DESIGN="H7.2-intuitive-design",S.COUNTER_INTUITIVE_DESIGN="H7.3-counter-intuitive-design",S.CONSISTENCY_ANALYSIS="H7.4-consistency-analysis",S))(Lt||{});var ar=class{enabledHeuristics;minConfidence;constructor(e={}){this.enabledHeuristics=e.enabledHeuristics||Object.values(Lt),this.minConfidence=e.minConfidence||.7}async applyAll(e,t,n,r){let i=[];for(let s of this.enabledHeuristics){let a=await this.apply(s,e,t,n,r);i.push(a)}return i}async apply(e,t,n,r,i){let s=this.getHeuristicCategory(e),a=[],c=[],l=[],u=75;switch(e){case"H7.4-consistency-analysis":t.domMetrics?.semanticStructure?.hasHeader&&t.domMetrics?.semanticStructure?.hasFooter?(u=85,a.push("Consistent page structure with header and footer")):(u=60,l.push("Add consistent header/footer structure"));break;case"H7.2-intuitive-design":{let d=t.domMetrics?.semanticStructure?.hasNav,m=t.accessibility?.focusableElementsCount||0;d&&m>10?(u=82,a.push("Intuitive navigation and interaction design")):(u=55,c.push({description:"Navigation or interaction patterns unclear",severity:"medium"}));break}case"H7.1-exactness-and-clarity":{u=70;let d=t.domMetrics?.semanticStructure,m=[d?.hasHeader,d?.hasMain,d?.hasNav,d?.hasFooter].filter(Boolean).length;u=50+m*10,m>=3?a.push("Strong visual hierarchy with semantic HTML elements"):m>=2?(a.push("Moderate visual hierarchy - some semantic elements present"),l.push("Add more semantic HTML5 elements for clarity")):(c.push({description:"Weak visual hierarchy - missing semantic structure",severity:"high"}),l.push("Implement semantic HTML5: header, nav, main, footer")),t.metadata?.description&&t.metadata.description.length>20&&(u+=10,a.push("Page has descriptive metadata"));break}case"H7.3-counter-intuitive-design":{u=85;let d=!t.domMetrics?.semanticStructure?.hasNav&&(t.domMetrics?.interactiveElements||0)>10,m=!t.domMetrics?.semanticStructure?.hasHeader&&!t.domMetrics?.semanticStructure?.hasFooter;d&&(u=45,c.push({description:"Navigation structure may be counter-intuitive",severity:"high"}),l.push("Add semantic navigation elements")),m&&(u-=15,c.push({description:"Page structure lacks expected header/footer",severity:"medium"})),u>75&&a.push("No counter-intuitive design patterns detected");break}case"H5.2-user-feelings-impact":{let d=t.accessibility?.altTextsCoverage||0,m=t.performance?.loadTime||0,p=t.accessibility?.ariaLabelsCount||0,g=t.accessibility?.focusableElementsCount||0;u=60,d>=90?(u+=20,a.push("Excellent accessibility (90%+ alt coverage) creates inclusive, positive experience")):d>=70?(u+=12,a.push("Good accessibility creates generally positive user feelings")):d<50&&(u-=15,c.push({description:"Poor accessibility (<50% alt coverage) frustrates users with disabilities",severity:"high"}),l.push("Improve alt text coverage to at least 80% for better accessibility")),p>5&&(u+=8,a.push("Strong ARIA labeling enhances screen reader experience")),m<1500?(u+=15,a.push("Very fast load time (<1.5s) delights users")):m<2500?(u+=8,a.push("Fast load time enhances user satisfaction")):m>4e3?(u-=20,c.push({description:"Very slow load time (>4s) causes significant frustration",severity:"critical"}),l.push("Optimize page load time - target under 2.5 seconds")):m>3e3&&(u-=12,c.push({description:"Slow load time causes user frustration",severity:"high"})),t.errorIndicators?.hasErrorMessages&&(u-=12,c.push({description:"Visible errors reduce user confidence and satisfaction",severity:"high"}),l.push("Review and fix visible error messages")),g>20?(u+=5,a.push("Rich interactive elements provide user control and engagement")):g<5&&(u-=8,c.push({description:"Limited interactivity may feel restrictive",severity:"medium"})),u=Math.max(20,Math.min(100,u));break}case"H5.1-gui-flow-impact":{let d=t.domMetrics?.interactiveElements||0,m=t.domMetrics?.forms||0;d>20&&(u=75,a.push(`${d} interactive elements provide user control`)),m>0&&(a.push(`${m} forms impact user input flows`),u=Math.min(100,u+10)),d===0&&(u=30,c.push({description:"Limited user interaction capability",severity:"high"}));break}case"H5.3-cross-functional-impact":u=70,t.accessibility&&(t.accessibility.altTextsCoverage||0)<100&&a.push("Content team needed for alt text creation"),t.performance&&(t.performance.loadTime||0)>2e3&&a.push("Engineering team needed for performance optimization"),n.complexity==="complex"&&a.push("QA team needed for comprehensive testing"),u=70+a.length*5;break;case"H5.4-data-dependent-impact":t.domMetrics?.forms&&t.domMetrics.forms>0?(u=75,a.push(`${t.domMetrics.forms} forms depend on backend data processing`)):(u=50,a.push("Limited data-dependent features"));break;case"H1.1-problem-understanding":u=n.clarityScore,n.clarityScore>80?a.push("Problem is well-defined"):c.push({description:"Problem clarity needs improvement",severity:"medium"}),a.push(...n.breakdown);break;case"H1.2-rule-of-three":u=n.potentialFailures.length>=3?85:60,a.push(`${n.potentialFailures.length} potential failure modes identified`),n.potentialFailures.length<3&&l.push("Identify at least 3 potential failure modes (Rule of Three)");break;case"H1.3-problem-complexity":u=n.complexity==="simple"?90:n.complexity==="moderate"?75:60,a.push(`Problem complexity: ${n.complexity}`);break;case"H2.1-user-needs-identification":{u=r.alignmentScore,a.push(`${r.needs.length} user needs identified`);let d=r.needs.filter(m=>m.priority==="must-have").length;a.push(`${d} must-have features`),r.challenges.length>0&&c.push({description:`${r.challenges.length} user need challenges found`,severity:"medium"});break}case"H2.2-user-needs-suitability":u=r.suitability==="excellent"?95:r.suitability==="good"?80:r.suitability==="adequate"?65:45,a.push(`User needs suitability: ${r.suitability}`);break;case"H2.3-user-needs-validation":{let d=r.needs.filter(m=>m.addressed).length;u=r.needs.length>0?d/r.needs.length*100:50,a.push(`${d}/${r.needs.length} needs validated and addressed`);break}case"H3.1-business-needs-identification":u=i.alignmentScore,a.push(`Primary goal: ${i.primaryGoal}`),a.push(`${i.kpisAffected.length} KPIs affected`),a.push(`${i.crossTeamImpact.length} cross-team impacts`);break;case"H3.2-user-vs-business-balance":{let d=100-Math.abs(r.alignmentScore-i.alignmentScore);u=d,d>80?a.push("Good balance between user and business needs"):(c.push({description:"Imbalance between user and business priorities",severity:"medium"}),l.push("Align user and business objectives more closely"));break}case"H3.3-kpi-impact-analysis":u=i.impactsKPIs?85:50,a.push(`KPIs impacted: ${i.kpisAffected.join(", ")}`),i.compromisesUX&&(c.push({description:"Business ease compromises user experience",severity:"high"}),u-=20);break;case"H4.1-oracle-problem-detection":u=75,a.push("Oracle problem detection capability active");break;case"H4.2-what-must-not-change":u=80,t.domMetrics?.semanticStructure?.hasMain&&a.push("Main content structure is immutable"),t.accessibility&&(t.accessibility.focusableElementsCount||0)>0&&a.push("Keyboard navigation support must be maintained");break;case"H4.3-supporting-data-analysis":{u=75,(t.domMetrics?.forms||0)>0||(t.domMetrics?.interactiveElements||0)>20?(u=82,a.push("Sufficient data points for informed decision-making")):(u=60,c.push({description:"Limited data for comprehensive analysis",severity:"medium"}),l.push("Collect more user interaction data"));break}case"H6.1-competitive-analysis":u=70,a.push("Competitive analysis capability available"),t.domMetrics?.semanticStructure?.hasNav&&t.domMetrics?.interactiveElements&&t.domMetrics.interactiveElements>15?(u=78,a.push("Navigation and interaction patterns follow industry standards")):l.push("Compare interaction patterns with leading competitors");break;case"H6.2-domain-inspiration":{u=72,t.accessibility&&(t.accessibility.ariaLabelsCount||0)>0?(u=80,a.push("Modern accessibility patterns show domain inspiration")):l.push("Research domain-specific design patterns and best practices");break}case"H6.3-innovative-solutions":{u=65,(t.accessibility?.landmarkRoles||0)>3?(u=75,a.push("Advanced accessibility features show innovative thinking")):l.push("Explore innovative UX patterns to differentiate experience");break}default:s==="user-needs"?u=r.alignmentScore:s==="business-needs"?u=i.alignmentScore:s==="problem"&&(u=n.clarityScore);break}return{id:e,name:this.getHeuristicName(e),category:s,applied:!0,score:Math.min(100,Math.max(0,u)),findings:a,issues:c,recommendations:l}}getHeuristicCategory(e){return e.includes("problem")?"problem":e.includes("user-needs")||e.includes("user-vs")?"user-needs":e.includes("business")?"business-needs":e.includes("oracle")||e.includes("balance")||e.includes("what-must")||e.includes("supporting-data")?"balance":e.includes("impact")||e.includes("gui-flow")||e.includes("feelings")||e.includes("cross-functional")||e.includes("data-dependent")?"impact":e.includes("competitive")||e.includes("inspiration")||e.includes("innovative")?"creativity":"design"}getHeuristicName(e){return{"H1.1-problem-understanding":"Problem Understanding","H1.2-rule-of-three":"Rule of Three","H1.3-problem-complexity":"Problem Complexity","H2.1-user-needs-identification":"User Needs Identification","H2.2-user-needs-suitability":"User Needs Suitability","H2.3-user-needs-validation":"User Needs Validation","H3.1-business-needs-identification":"Business Needs Identification","H3.2-user-vs-business-balance":"User vs Business Balance","H3.3-kpi-impact-analysis":"KPI Impact Analysis","H4.1-oracle-problem-detection":"Oracle Problem Detection","H4.2-what-must-not-change":"What Must Not Change","H4.3-supporting-data-analysis":"Supporting Data Analysis","H5.1-gui-flow-impact":"GUI Flow Impact","H5.2-user-feelings-impact":"User Feelings Impact","H5.3-cross-functional-impact":"Cross-Functional Impact","H5.4-data-dependent-impact":"Data-Dependent Impact","H6.1-competitive-analysis":"Competitive Analysis","H6.2-domain-inspiration":"Domain Inspiration","H6.3-innovative-solutions":"Innovative Solutions","H7.1-exactness-and-clarity":"Exactness & Clarity","H7.2-intuitive-design":"Intuitive Design","H7.3-counter-intuitive-design":"Counter-Intuitive Design","H7.4-consistency-analysis":"Consistency Analysis"}[e]||e}};var or=class{minSeverity;constructor(e="medium"){this.minSeverity=e}detect(e,t,n){let r=[];Math.abs(t.alignmentScore-n.alignmentScore)>20&&r.push({type:"user-vs-business",description:"Significant gap between user needs and business objectives",severity:"high",stakeholders:["Users","Business"],resolutionApproach:["Gather supporting data from both perspectives","Facilitate discussion between stakeholders","Find compromise solutions that address both needs"]}),(t.challenges.length>0||n.compromisesUX)&&r.push({type:"unclear-criteria",description:"Quality criteria unclear due to conflicting information",severity:"medium",missingInfo:t.challenges,resolutionApproach:["Collect missing information from stakeholders","Define clear acceptance criteria"]});let i=(e.title||"").toLowerCase(),s=(e.metadata?.description||"").toLowerCase();return(i.includes("hotel")||i.includes("booking")||i.includes("travel")||i.includes("shop")||i.includes("store")||s.includes("book"))&&(n.kpisAffected.some(a=>a.toLowerCase().includes("conversion")||a.toLowerCase().includes("engagement"))&&r.push({type:"user-vs-business",description:"Potential conflict between conversion optimization (business) and user experience quality (user trust)",severity:"medium",stakeholders:["Marketing","Product","Users"],resolutionApproach:["A/B test aggressive vs. subtle conversion tactics","Measure both conversion rate and user satisfaction metrics","Balance urgency messaging with transparent communication"]}),r.push({type:"unclear-criteria",description:"Unclear criteria for price display timing - when to show fees, taxes, and final price",severity:"medium",stakeholders:["Users","Legal","Business"],resolutionApproach:["Define regulatory compliance requirements for price display","Balance business desire for competitive base pricing vs user need for full price transparency","Establish clear standards for fee disclosure timing"]})),(i.includes("blog")||i.includes("article")||i.includes("news")||i.includes("magazine")||i.includes("testing"))&&r.push({type:"user-vs-business",description:"Content depth (user need) vs. publication frequency (business engagement goals) trade-off",severity:"low",stakeholders:["Readers","Content Team","Editorial"],resolutionApproach:["Define content quality standards and acceptance criteria","Balance editorial calendar with quality thresholds","Consider mix of in-depth and quick-read content formats"]}),(i.includes("health")||i.includes("medical")||i.includes("patient")||i.includes("care")||i.includes("nhs"))&&(r.push({type:"stakeholder-conflict",description:"Healthcare compliance requirements may conflict with streamlined user experience",severity:"medium",stakeholders:["Patients","Healthcare Providers","Compliance","Legal"],resolutionApproach:["Map regulatory requirements to UX touchpoints","Identify where compliance can be achieved without friction","Engage compliance team early in UX design reviews","Document consent and data handling requirements clearly"]}),e.accessibility&&(e.accessibility.altTextsCoverage||0)<80&&r.push({type:"technical-constraint",description:"Healthcare accessibility requirements not fully met - critical for patient inclusivity",severity:"high",stakeholders:["Patients","Accessibility Team","Legal"],resolutionApproach:["Prioritize WCAG 2.1 AA compliance for healthcare content","Ensure screen reader compatibility for medical information","Test with assistive technology users"]})),(i.includes("bank")||i.includes("finance")||i.includes("payment")||i.includes("money"))&&r.push({type:"stakeholder-conflict",description:"Security requirements vs user convenience - authentication friction vs fraud prevention",severity:"high",stakeholders:["Users","Security Team","Product","Compliance"],resolutionApproach:["Implement risk-based authentication to reduce friction for trusted sessions","Use biometrics where available for convenient yet secure access","A/B test authentication flows for security effectiveness and user completion rates"]}),((e.domMetrics?.totalElements||0)>500||(e.domMetrics?.interactiveElements||0)>50)&&r.push({type:"technical-constraint",description:"Platform technical limitations may restrict advanced UX features or accessibility enhancements",severity:"low",stakeholders:["Development","Product","Users"],resolutionApproach:["Evaluate platform capabilities and constraints","Prioritize features based on user impact vs. implementation complexity","Consider gradual enhancement approach"]}),e.performance&&(e.performance.loadTime||0)>3e3&&r.push({type:"technical-constraint",description:"Performance optimization needed but may require trade-offs with visual richness",severity:"medium",stakeholders:["Users","Development","Design"],resolutionApproach:["Profile and identify performance bottlenecks","Consider progressive loading for visual elements","Balance image quality with load time"]}),r.filter(a=>this.meetsMinimumSeverity(a.severity))}meetsMinimumSeverity(e){let t=["low","medium","high","critical"],n=t.indexOf(this.minSeverity);return t.indexOf(e)>=n}};var cr=class o{static LOAD_TIME_FEELINGS=[[4001,1/0,"Impatient - Very slow load time causes significant frustration"],[3001,4e3,"Impatient - Slow load time causes frustration"],[2001,3e3,"Mildly Annoyed - Noticeable load time"],[0,1499,"Delighted - Fast load time enhances experience"],[1500,1999,"Satisfied - Good load time meets expectations"]];static DOMAIN_REQUIREMENTS=[[["health","medical","care"],["Must comply with healthcare accessibility standards","Must protect patient data privacy"]],[["bank","finance","payment"],["Must maintain PCI DSS compliance for payment data","Must support secure authentication flows"]]];static VISIBLE_SCORE_ADJUSTMENTS=[[["Positive","Satisfied","Delighted"],20],[["Oriented"],10],[["Frustrated","Confused","Impatient"],-15],[["Disoriented"],-10]];analyze(e,t){let n=this.analyzeEndUserFlow(e),r=this.analyzeInternalFlow(e),i=this.analyzeUserFeelings(e),s=this.analyzePerformance(e),a=this.analyzeSecurity(e),c=this.analyzeImmutableRequirements(e,t),l=this.calculateVisibleScore(n,i),u=this.calculateInvisibleScore(s,a),d=Math.round((l+u)/2);return{visible:{guiFlow:{forEndUser:n,forInternalUser:r},userFeelings:i,score:l},invisible:{performance:s,security:a,score:u},immutableRequirements:c,overallImpactScore:d}}analyzeEndUserFlow(e){let t=[],n=e.domMetrics?.interactiveElements||0,r=e.domMetrics?.forms||0;return n>0&&t.push(`${n} interactive elements affect user journey`),r>0&&t.push(`${r} forms impact user input flows`),e.domMetrics?.semanticStructure?.hasNav&&t.push("Navigation structure enables exploration flow"),e.domMetrics?.semanticStructure?.hasMain&&t.push("Clear main content area guides user focus"),t}analyzeInternalFlow(e){let t=[];return(e.domMetrics?.forms||0)>0&&t.push("Form submissions create data processing workflows"),e.domMetrics?.semanticStructure?.hasAside&&t.push("Sidebar content may require separate management"),t}analyzeUserFeelings(e){let t=[],n=e.accessibility?.altTextsCoverage||0;n>80?t.push("Positive - Good accessibility creates inclusive experience"):n>=50?t.push("Neutral - Moderate accessibility; some users may struggle"):n<50&&t.push("Frustrated - Poor accessibility excludes some users");let r=e.performance?.loadTime||0;for(let[i,s,a]of o.LOAD_TIME_FEELINGS)if(r>=i&&r<=s){t.push(a);break}return e.errorIndicators?.hasErrorMessages&&t.push("Confused - Visible errors reduce confidence"),this.analyzeStructureFeelings(e,t),t}analyzeStructureFeelings(e,t){let n=e.domMetrics?.semanticStructure;if(!n)return;let r=[n.hasHeader,n.hasNav,n.hasMain,n.hasFooter].filter(Boolean).length;r>=3?t.push("Oriented - Clear page structure helps navigation"):r<2&&t.push("Disoriented - Unclear page structure may confuse users")}analyzePerformance(e){let t=[],n=e.performance?.loadTime||0;return n>2e3&&t.push(`Load time ${n}ms impacts user retention`),e.metadata?.viewport||t.push("Missing viewport tag affects mobile performance"),e.performance?.firstContentfulPaint&&e.performance.firstContentfulPaint>2500&&t.push(`First Contentful Paint ${e.performance.firstContentfulPaint}ms delays perceived readiness`),t}analyzeSecurity(e){let t=[];return(e.domMetrics?.forms||0)>0&&t.push("Form data handling requires secure transmission"),e.accessibility&&(e.accessibility.ariaLabelsCount||0)>0&&t.push("ARIA labels may expose internal element names - review for sensitive info"),t}analyzeImmutableRequirements(e,t){let n=[];e.domMetrics?.semanticStructure?.hasMain&&n.push("Must maintain main content accessibility"),e.accessibility&&(e.accessibility.focusableElementsCount||0)>0&&n.push("Must support keyboard navigation"),t.complexity==="complex"&&n.push("Must maintain system stability with complex interactions");let r=(e.title||"").toLowerCase();for(let[i,s]of o.DOMAIN_REQUIREMENTS)i.some(a=>r.includes(a))&&n.push(...s);return n}calculateVisibleScore(e,t){let n=50;e.length>0&&(n+=15);for(let[r,i]of o.VISIBLE_SCORE_ADJUSTMENTS)t.some(s=>r.some(a=>s.includes(a)))&&(n+=i);return Math.max(0,Math.min(100,n))}calculateInvisibleScore(e,t){let n=50;return e.length===0&&(n+=20),t.length===0&&(n+=10),e.length>2&&(n-=15),Math.max(0,Math.min(100,n))}};k();var jm={type:"object",properties:{target:{type:"string",description:"Target URL or identifier to analyze"},context:{type:"object",description:"Pre-collected QX context (optional)"},mode:{type:"string",description:"Analysis mode: full, quick, or targeted",enum:["full","quick","targeted"],default:"full"},heuristics:{type:"array",description:"Specific heuristics to apply (default: all)"},minOracleSeverity:{type:"string",description:"Minimum oracle problem severity to report",enum:["low","medium","high","critical"],default:"medium"},includeCreativity:{type:"boolean",description:"Include creativity analysis from diverse domains",default:!0},includeDesign:{type:"boolean",description:"Include design quality analysis",default:!0}},required:["target"]},qt=class extends A{config={name:"qe/qx/analyze",description:"Comprehensive Quality Experience (QX) analysis combining QA and UX perspectives. Applies 23+ programmatic heuristics, detects oracle problems, and analyzes impacts. QX = Marriage between QA (Quality Advocacy) and UX (User Experience).",domain:"quality-assessment",schema:jm,streaming:!0,timeout:18e4};async execute(e,t){let{target:n,context:r=this.createMinimalContext(n),mode:i="full",heuristics:s,minOracleSeverity:a="medium",includeCreativity:c=!0,includeDesign:l=!0}=e;try{this.emitStream(t,{status:"starting",message:`Starting QX analysis for: ${n}`,phase:"initialization"}),this.emitStream(t,{status:"analyzing",phase:"problem-analysis"});let u=this.analyzeProblem(r);if(this.isAborted(t))return{success:!1,error:"Operation aborted"};this.emitStream(t,{status:"analyzing",phase:"user-needs"});let d=this.analyzeUserNeeds(r,u);this.emitStream(t,{status:"analyzing",phase:"business-needs"});let m=this.analyzeBusinessNeeds(r,u);this.emitStream(t,{status:"analyzing",phase:"creativity"});let p=c?this.analyzeCreativity(r,u):this.createMinimalCreativityAnalysis();this.emitStream(t,{status:"analyzing",phase:"design"});let g=l?this.analyzeDesign(r):this.createMinimalDesignAnalysis();this.emitStream(t,{status:"analyzing",phase:"oracle-detection"});let h=new or(a).detect(r,d,m);this.emitStream(t,{status:"analyzing",phase:"impact-analysis"});let y=new cr().analyze(r,u);this.emitStream(t,{status:"analyzing",phase:"heuristics",count:23});let b=await new ar({enabledHeuristics:s||Object.values(Lt)}).applyAll(r,u,d,m);this.emitStream(t,{status:"analyzing",phase:"recommendations"});let w=this.generateRecommendations(u,d,m,h,y,b),T=this.calculateOverallScore(u,d,m,p,g,y,b),S=this.scoreToGrade(T),x={overallScore:T,grade:S,timestamp:new Date().toISOString(),target:n,problemAnalysis:u,userNeeds:d,businessNeeds:m,creativityAnalysis:p,designAnalysis:g,oracleProblems:h,impactAnalysis:y,heuristics:b,recommendations:w,context:r};return this.emitStream(t,{status:"complete",score:T,grade:S,heuristicsApplied:b.length,oracleProblemsFound:h.length}),{success:!0,data:x,metadata:this.createMetadata(t.startTime,t.requestId)}}catch(u){return{success:!1,error:`QX analysis failed: ${E(u)}`}}}analyzeProblem(e){let t=e.title||"Untitled page",n=e.metadata?.description||"",r=e.errorIndicators?.hasErrorMessages||!1,i=`Evaluate quality experience of "${t}"`;n&&(i+=` - ${n.substring(0,100)}`);let s=e.domMetrics?.totalElements||0,a=e.domMetrics?.interactiveElements||0,c=e.domMetrics?.forms||0,l;s>500||a>50||c>3?l="complex":s>200||a>20||c>1?l="moderate":l="simple";let u=[];e.domMetrics?.semanticStructure?.hasNav&&u.push("Navigation structure"),c>0&&u.push(`Form interactions (${c} forms)`),a>0&&u.push(`User interactions (${a} elements)`),e.accessibility&&u.push("Accessibility compliance"),e.performance&&u.push("Performance metrics");let d=[],m=t.toLowerCase();for((m.includes("health")||m.includes("care")||m.includes("nhs"))&&(d.push({description:"Healthcare information may not be accessible to users with visual impairments",severity:"high",likelihood:"likely"}),d.push({description:"Patient journey complexity may cause confusion during registration or booking",severity:"medium",likelihood:"possible"}),d.push({description:"Emergency contact information may not be prominently visible",severity:"high",likelihood:"possible"})),e.domMetrics?.semanticStructure?.hasMain||d.push({description:"Missing main content landmark - users may struggle to find primary content",severity:"medium",likelihood:"likely"}),e.accessibility&&(e.accessibility.altTextsCoverage||0)<80&&d.push({description:"Poor image alt text coverage - screen reader users affected",severity:"high",likelihood:"very-likely"}),r&&d.push({description:"Visible error messages detected - potential usability issues",severity:"medium",likelihood:"likely"}),e.performance&&(e.performance.loadTime||0)>3e3&&d.push({description:"Slow load time - user frustration and abandonment risk",severity:"high",likelihood:"very-likely"});d.length<3;)l==="complex"?d.push({description:"Complex interaction flows may confuse first-time users",severity:"medium",likelihood:"possible"}):l==="moderate"?d.push({description:"Multiple interactive elements increase cognitive load",severity:"low",likelihood:"possible"}):d.push({description:"Limited interactivity may not meet user expectations",severity:"low",likelihood:"possible"});let p=50;return t&&t!=="Untitled page"&&(p+=15),n&&(p+=15),u.length>=3&&(p+=10),e.domMetrics?.semanticStructure?.hasMain&&(p+=10),p=Math.min(100,p),{problemStatement:i,complexity:l,breakdown:u,potentialFailures:d.slice(0,5),clarityScore:p}}analyzeUserNeeds(e,t){let n=[],r=[],i=e.domMetrics?.semanticStructure,s=e.accessibility,a=e.domMetrics?.interactiveElements||0,c=e.domMetrics?.forms||0;i?.hasNav?n.push({description:"Clear navigation to find content",priority:"must-have",addressed:!0}):(r.push("Missing navigation structure - users cannot easily explore site"),n.push({description:"Clear navigation to find content",priority:"must-have",addressed:!1})),a>0&&n.push({description:"Interactive elements for engagement",priority:"must-have",addressed:!0}),s&&(s.focusableElementsCount||0)>0?n.push({description:"Keyboard navigation support",priority:"must-have",addressed:!0}):(r.push("Limited keyboard navigation - inaccessible to some users"),n.push({description:"Keyboard navigation support",priority:"must-have",addressed:!1})),i?.hasHeader&&n.push({description:"Consistent page header for orientation",priority:"should-have",addressed:!0}),i?.hasFooter&&n.push({description:"Footer with supporting information",priority:"should-have",addressed:!0}),s&&(s.altTextsCoverage||0)>50?n.push({description:"Image descriptions for screen readers",priority:"should-have",addressed:!0}):s&&(s.altTextsCoverage||0)<50&&(r.push("Poor alt text coverage - images not accessible"),n.push({description:"Image descriptions for screen readers",priority:"should-have",addressed:!1})),e.performance&&(e.performance.loadTime||0)<3e3?n.push({description:"Fast page load time",priority:"should-have",addressed:!0}):e.performance&&(e.performance.loadTime||0)>=3e3&&(r.push("Slow load time - user frustration risk"),n.push({description:"Fast page load time",priority:"should-have",addressed:!1})),i?.hasAside&&n.push({description:"Supplementary content sections",priority:"nice-to-have",addressed:!0}),s&&(s.landmarkRoles||0)>3&&n.push({description:"Rich ARIA landmarks for navigation",priority:"nice-to-have",addressed:!0}),c>0&&n.push({description:"Form interactions for user input",priority:"nice-to-have",addressed:!0});let l=n.filter(m=>m.priority==="must-have"&&m.addressed).length,u;r.length===0&&l>=3?u="excellent":r.length<=1&&l>=2?u="good":r.length<=2&&l>=2?u="adequate":u="poor";let d=40;return d+=l*10,d+=n.filter(m=>m.priority==="should-have"&&m.addressed).length*5,d+=n.filter(m=>m.priority==="nice-to-have"&&m.addressed).length*2,d-=r.length*8,d=Math.max(0,Math.min(100,d)),{needs:n,suitability:u,challenges:r,alignmentScore:d}}analyzeBusinessNeeds(e,t){let n=e.domMetrics?.forms||0,r=e.domMetrics?.interactiveElements||0,i=e.performance,s=e.errorIndicators?.hasErrorMessages||!1,a,c=[];n>2?(a="business-ease",c=["Form completion rate","Lead generation","User sign-ups"]):r>30?(a="user-experience",c=["Time on site","Click-through rate","User engagement"]):(a="balanced",c=["Content consumption","Bounce rate","Page views"]);let l=(e.title||"").toLowerCase();(l.includes("health")||l.includes("care"))&&c.push("Patient satisfaction","Appointment completion rate","Information accessibility");let u=[];n>0&&(u.push({team:"Marketing",impactType:"positive",description:"Form conversion optimization needed"}),u.push({team:"Development",impactType:"neutral",description:"Form validation and submission handling"})),e.accessibility&&(e.accessibility.altTextsCoverage||0)<100&&u.push({team:"Content",impactType:"negative",description:"Image alt text creation required"}),i&&(i.loadTime||0)>2e3&&u.push({team:"Engineering",impactType:"negative",description:"Performance optimization needed"}),t.complexity==="complex"&&u.push({team:"QA",impactType:"neutral",description:"Comprehensive testing strategy required"});let d=!1;s&&(d=!0),e.accessibility&&(e.accessibility.altTextsCoverage||0)<50&&(d=!0),i&&(i.loadTime||0)>4e3&&(d=!0);let m=50;return c.length>0&&(m+=15),u.length>0&&(m+=10),d||(m+=20),m=Math.min(100,m),{primaryGoal:a,kpisAffected:c,crossTeamImpact:u,compromisesUX:d,impactsKPIs:c.length>0,alignmentScore:m}}analyzeCreativity(e,t){let n=[];(t.complexity==="complex"||t.complexity==="moderate")&&(n.push({description:"Question fundamental assumptions about user mental models and expected workflows",inspirationSource:"philosophy",applicability:"high",novelty:"moderately-novel"}),e.errorIndicators?.hasErrorMessages&&n.push({description:"Apply diagnostic testing - systematically isolate error sources through controlled scenarios",inspirationSource:"medicine",applicability:"high",novelty:"moderately-novel"})),e.domMetrics?.forms&&e.domMetrics.forms>0&&n.push({description:"Test checkout/form flows like fashion retail - focus on friction points, abandonment triggers",inspirationSource:"e-commerce",applicability:"high",novelty:"incremental"}),n.push({description:"Analyze through diverse demographic lenses (age, gender, culture, ability) for inclusive testing",inspirationSource:"social science",applicability:"high",novelty:"moderately-novel"}),e.domMetrics?.interactiveElements&&e.domMetrics.interactiveElements>20&&n.push({description:'Test for "game-breaking" exploits - unexpected interaction sequences, boundary conditions',inspirationSource:"gaming",applicability:"medium",novelty:"highly-novel"});let r=[...new Set(n.map(a=>a.inspirationSource))],i=["Unexperienced user perspective (fresh eyes)","Power user perspective (efficiency focus)","Accessibility perspective (assistive tech users)","International perspective (cultural differences)"],s=50;return s+=n.length*8,s+=r.length*5,s=Math.min(100,s),{innovativeApproaches:n,domainsExplored:r,perspectives:i,creativityScore:s,notes:["Creativity draws from diverse domains to uncover unconventional testing approaches","Higher complexity problems benefit from cross-disciplinary inspiration",`Applied ${n.length} creative approaches from ${r.length} domains`]}}analyzeDesign(e){let t=[],n=[];e.domMetrics?.semanticStructure?.hasNav&&t.push("Navigation structure clearly defined with semantic <nav> element"),e.domMetrics?.semanticStructure?.hasMain&&t.push("Main content area clearly identified"),e.domMetrics?.semanticStructure?.hasHeader&&e.domMetrics?.semanticStructure?.hasFooter&&t.push("Header and footer provide clear page structure");let r=e.accessibility?.ariaLabelsCount||0,i=e.domMetrics?.interactiveElements||0;i>0&&r<i*.5&&n.push("Many interactive elements lack ARIA labels for clarity");let s=50+t.length*15-n.length*10;s=Math.max(0,Math.min(100,s));let a=s>=80?"excellent":s>=60?"good":s>=40?"adequate":"poor",c=[],l=[],u=!0;e.domMetrics?.semanticStructure?.hasNav&&c.push("Standard navigation placement"),e.domMetrics?.semanticStructure?.hasHeader&&c.push("Header follows common layout conventions"),!e.domMetrics?.semanticStructure?.hasNav&&i>10&&(u=!1,l.push("Non-standard navigation pattern may confuse users from different regions"));let d=50+c.length*15;u||(d-=20),d=Math.max(0,Math.min(100,d));let m=Math.round((s+d)/2);return{exactness:{clarity:a,clearElements:t,unclearElements:n,score:s},intuitive:{followsConventions:u,intuitivePatterns:c,culturalIssues:l,score:d},counterIntuitive:{deviations:[],innovativeJustification:!1,freshEyesPerspective:!0,issuesCount:0},overallDesignScore:m}}generateRecommendations(e,t,n,r,i,s){let a=[],c=1;for(let l of s){for(let u of l.issues)(u.severity==="critical"||u.severity==="high")&&a.push({principle:l.name,recommendation:u.description,severity:u.severity,impact:u.severity==="critical"?90:75,effort:"medium",priority:c++,category:"qx"});for(let u of l.recommendations)a.push({principle:l.name,recommendation:u,severity:"medium",impact:60,effort:"medium",priority:c++,category:"qx"})}for(let l of r)a.push({principle:`Oracle: ${l.type}`,recommendation:l.description,severity:l.severity,impact:l.severity==="critical"?95:l.severity==="high"?80:60,effort:"high",priority:c++,category:"process",evidence:l.resolutionApproach});for(let l of t.challenges)a.push({principle:"User Needs",recommendation:l,severity:"medium",impact:65,effort:"medium",priority:c++,category:"ux"});return a.sort((l,u)=>{let d={critical:0,high:1,medium:2,low:3},m=d[l.severity]-d[u.severity];return m!==0?m:u.impact-l.impact}).slice(0,15)}calculateOverallScore(e,t,n,r,i,s,a){let c=a.reduce((u,d)=>u+d.score,0)/a.length||0,l=e.clarityScore*.1+t.alignmentScore*.2+n.alignmentScore*.15+r.creativityScore*.1+i.overallDesignScore*.15+(100-s.overallImpactScore)*.1+c*.2;return Math.round(Math.max(0,Math.min(100,l)))}scoreToGrade(e){return e>=90?"A":e>=80?"B":e>=70?"C":e>=60?"D":"F"}createMinimalContext(e){return{url:e,title:e}}createMinimalCreativityAnalysis(){return{innovativeApproaches:[],domainsExplored:[],perspectives:[],creativityScore:50,notes:["Creativity analysis skipped"]}}createMinimalDesignAnalysis(){return{exactness:{clarity:"adequate",clearElements:[],unclearElements:[],score:50},intuitive:{followsConventions:!0,intuitivePatterns:[],culturalIssues:[],score:50},counterIntuitive:{deviations:[],innovativeJustification:!1,freshEyesPerspective:!1,issuesCount:0},overallDesignScore:50}}emitStream(e,t){e.streaming&&e.onStream&&e.onStream(t)}isAborted(e){return e.abortSignal?.aborted||!1}createMetadata(e,t){return{executionTime:Date.now()-e,timestamp:new Date().toISOString(),requestId:t}}},bk=new qt;var Vk={TEST_GENERATE:"qe/tests/generate",TEST_EXECUTE:"qe/tests/execute",COVERAGE_ANALYZE:"qe/coverage/analyze",COVERAGE_GAPS:"qe/coverage/gaps",QUALITY_EVALUATE:"qe/quality/evaluate",QUALITY_GATE:"qe/quality/gate",DEFECT_PREDICT:"qe/defects/predict",REQUIREMENTS_VALIDATE:"qe/requirements/validate",QUALITY_CRITERIA:"qe/requirements/quality-criteria",CODE_ANALYZE:"qe/code/analyze",CODE_C4:"qe/code/c4",SECURITY_SCAN:"qe/security/scan",CONTRACT_VALIDATE:"qe/contracts/validate",VISUAL_COMPARE:"qe/visual/compare",A11Y_AUDIT:"qe/a11y/audit",CHAOS_INJECT:"qe/chaos/inject",LEARNING_OPTIMIZE:"qe/learning/optimize",LEARNING_DREAM:"qe/learning/dream",TOKEN_USAGE:"qe/analysis/token_usage",GOAP_PLAN:"qe/planning/goap_plan",GOAP_EXECUTE:"qe/planning/goap_execute",GOAP_STATUS:"qe/planning/goap_status",...It,EMBEDDING_GENERATE:"qe/embeddings/generate",EMBEDDING_COMPARE:"qe/embeddings/compare",EMBEDDING_SEARCH:"qe/embeddings/search",EMBEDDING_STORE:"qe/embeddings/store",EMBEDDING_STATS:"qe/embeddings/stats",...lc,QX_ANALYZE:"qe/qx/analyze",TEST_SCHEDULE:"qe/tests/schedule",LOAD_TEST:"qe/tests/load",URL_VALIDATE:"qe/security/url-validate",BROWSER_WORKFLOW:"qe/workflows/browser-load"},zm=[new On,new Nn,new Ln,new qn,new $n,new Gn,new zn,new Un,new Et,new Hn,new Vn,new Qn,new Wn,new Kn,new Xn,new Yn,new wt,new Rt,new Jn,new At,new kt,new Mt,...oc,new nt,new rt,new it,new st,new at,...cc,new qt,new ma,new pa,new ga,new fa];function uc(){for(let o of zm)o.resetInstanceCache()}k();var Um=mr.filter(o=>o!=="coordination"),R={fleetId:null,kernel:null,queen:null,router:null,workflowOrchestrator:null,initialized:!1,initTime:null,topology:"hierarchical",agentLevels:new Map};function Ct(){return R}function Qe(){return R.initialized&&R.kernel!==null&&R.queen!==null}function oM(o){return Qe()||(R.fleetId=`fleet-${G().slice(0,8)}`,R.kernel=o.kernel,R.queen=o.queen,R.router=o.router??null,R.workflowOrchestrator=o.workflowOrchestrator??null,R.initialized=!0,R.initTime=new Date,R.topology=o.topology??"hierarchical",R.agentLevels.clear()),R.fleetId}function cM(){return R.topology}function lM(o,e){if(R.topology!=="hierarchical"){let i={agentId:o,domain:e,level:"worker",spawnedAt:new Date};return R.agentLevels.set(o,i),"worker"}let n=Array.from(R.agentLevels.values()).find(i=>i.domain===e&&i.level==="lead")?"worker":"lead",r={agentId:o,domain:e,level:n,spawnedAt:new Date};return R.agentLevels.set(o,r),n}function uM(o){return R.agentLevels.get(o)}function dM(){return R.agentLevels}async function mM(o){try{if(R.initialized&&R.kernel&&R.queen){let l=R.kernel.getConfig();return{success:!0,data:{fleetId:R.fleetId,topology:R.topology,maxAgents:l.maxConcurrentAgents,enabledDomains:l.enabledDomains.filter(u=>u!=="coordination"),status:"ready"}}}R.fleetId=`fleet-${G().slice(0,8)}`;let e=o.enabledDomains||[...mr],t=e.filter(l=>l!=="coordination"),n=process.env.AQE_MEMORY_BACKEND==="memory"?"memory":o.memoryBackend||"hybrid";R.kernel=new Hs({maxConcurrentAgents:o.maxAgents||15,memoryBackend:n,hnswEnabled:!0,lazyLoading:o.lazyLoading!==!1,enabledDomains:e}),await R.kernel.initialize(),R.router=new Qs(R.kernel.eventBus),await R.router.initialize();let r=l=>R.kernel.getDomainAPI(l),i=new ha(R.kernel.eventBus,R.kernel.memory,r),s=R.kernel.plugins;await s.loadAll();let a=new Map;for(let l of s.getLoaded()){let u=s.getPlugin(l);u&&a.set(l,u)}try{let{getDaemon:l}=await import("./daemon-3DQCKRYO.js"),u=l().getWorkerManager();u.setKernel(R.kernel),u.setMemory(R.kernel.memory)}catch(l){console.warn(`[fleet_init] Daemon worker manager wiring skipped: ${E(l)}`)}R.queen=Vs(R.kernel,R.router,i,void 0,a),await R.queen.initialize(),R.workflowOrchestrator=new Bs(R.kernel.eventBus,R.kernel.memory,R.kernel.coordinator),await R.workflowOrchestrator.initialize(),Bm(R.kernel,R.workflowOrchestrator);let{subscribeTrajectoryEvents:c}=await import("./task-handlers-6CRDEELN.js");return c(R.router),R.initialized=!0,R.initTime=new Date,R.topology=o.topology||"hierarchical",R.agentLevels.clear(),{success:!0,data:{fleetId:R.fleetId,topology:R.topology,maxAgents:o.maxAgents||15,enabledDomains:t,status:"initialized"}}}catch(e){return{success:!1,error:`Failed to initialize fleet: ${E(e)}`}}}async function pM(o){if(!Qe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{let e=R.queen.getHealth(),t=R.queen.getMetrics(),n={status:e.status,uptime:t.uptime,agents:{total:e.totalAgents,active:e.activeAgents,idle:e.totalAgents-e.activeAgents},tasks:{pending:e.pendingTasks,running:e.runningTasks,completed:t.tasksCompleted,failed:t.tasksFailed}};if(o.includeDomains){let i=[];for(let[s,a]of e.domainHealth)i.push({domain:s,status:a.status,agents:a.agents.total,load:R.queen.getDomainLoad(s)});n.domains=i}let r=R.queen.getDomainTeamManager?.();if(r){let i=r.listDomainTeams(),s=0,a=0;for(let c of i)s+=1+c.teammateIds.length,r.getTeamHealth(c.domain)?.healthy&&a++;n.teams={active:i.length,totalAgentsInTeams:s,healthyCount:a}}o.includeMetrics&&(n.metrics={tasksReceived:t.tasksReceived,tasksCompleted:t.tasksCompleted,tasksFailed:t.tasksFailed,agentUtilization:t.agentUtilization,averageTaskDuration:t.averageTaskDuration});try{let{getUnifiedMemory:i}=await import("./unified-memory-2Z2F446J.js"),s=i();if(s.isInitialized()){let a=l=>{try{return s.queryCount(l)}catch{return 0}},c=await s.vectorCount();n.learning={totalPatterns:a("qe_patterns"),totalExperiences:a("captured_experiences"),totalTrajectories:a("qe_trajectories"),vectorCount:c,experienceApplications:a("experience_applications"),dreamCycles:a("dream_cycles"),embeddingDimension:384}}}catch{}return{success:!0,data:n}}catch(e){return{success:!1,error:`Failed to get fleet status: ${E(e)}`}}}async function gM(o){if(!Qe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{if(o.domain){let n=R.queen.getDomainHealth(o.domain);return n?{success:!0,data:{domain:o.domain,status:n.status,agents:n.agents,errors:n.errors,lastActivity:n.lastActivity?.toISOString()}}:{success:!1,error:`Domain not found: ${o.domain}`}}let e=R.queen.getHealth(),t={status:e.status,totalAgents:e.totalAgents,activeAgents:e.activeAgents,pendingTasks:e.pendingTasks,runningTasks:e.runningTasks,workStealingActive:e.workStealingActive,lastHealthCheck:e.lastHealthCheck.toISOString()};if(o.detailed){let n={};for(let[r,i]of e.domainHealth)n[r]={status:i.status,agents:i.agents,errors:i.errors.length,lastActivity:i.lastActivity?.toISOString()};t.domains=n,t.issues=e.issues.map(r=>({severity:r.severity,message:r.message,domain:r.domain,timestamp:r.timestamp.toISOString()}))}try{let{StructuralHealthMonitor:n}=await import("./structural-health-PQ7NZAJ4.js"),r=new n,i=[];for(let[c]of e.domainHealth){let l=R.queen.getAgentsByDomain(c);for(let u of l)i.push({id:u.id,name:u.name,domain:u.domain})}let s=i.map(c=>({id:c.id,name:c.name,domain:c.domain,capabilities:[c.domain],dependsOn:[],weight:1})),a=r.computeFleetHealth(s);t.structuralHealth={lambda:a.lambda,healthy:a.healthy,normalizedLambda:a.normalizedLambda,riskScore:a.riskScore,status:a.status,weakPoints:a.weakPoints,suggestions:a.suggestions}}catch{}return{success:!0,data:t}}catch(e){return{success:!1,error:`Failed to get fleet health: ${E(e)}`}}}async function fM(){if(Ja(),Io(),uc(),R.workflowOrchestrator&&(await R.workflowOrchestrator.dispose(),R.workflowOrchestrator=null),R.queen&&(await R.queen.dispose(),R.queen=null),R.router){try{let{unsubscribeTrajectoryEvents:o}=await import("./task-handlers-6CRDEELN.js");o(R.router)}catch{}await R.router.dispose(),R.router=null}R.kernel&&(await R.kernel.dispose(),R.kernel=null),R.initialized=!1,R.fleetId=null,R.initTime=null,R.topology="hierarchical",R.agentLevels.clear()}async function hM(){let o=performance.now();try{let e=Qe(),t=R.initTime?Date.now()-R.initTime.getTime():0,n={connected:!1,totalEntries:0,namespaces:0},r={enabled:!1,vectorCount:0},i=0;if(e&&R.kernel){let u=R.kernel.memory;try{n.connected=!0;let d=await u.count("default"),m=await u.count("learning"),p=await u.count("patterns");n.totalEntries=d+m+p;let g=0;for(let f of["default","learning","patterns","mcp-tools","coordination"])await u.count(f)>0&&g++;n.namespaces=g}catch{}try{let d=process.env.AQE_V3_HNSW_ENABLED==="true";r.enabled=d;let m=u;d&&typeof m.vectorCount=="function"&&(r.vectorCount=await m.vectorCount())}catch{}try{i=(await u.search("pattern:*",1e3)).length}catch{}}let s=e&&R.kernel?(R.kernel.getLoadedDomains?.()??Um).length:0,a=null;try{let{getSharedRvfDualWriterSync:u}=await import("./shared-rvf-dual-writer-4BGDVPQ7.js"),d=u();if(d){let m=d.status(),p=d.getDivergenceReport();a={mode:m.mode,vectorCount:m.rvf?.totalVectors??0,divergences:p.divergences,promotionSafe:d.isPromotionSafe()}}}catch{}let c=null;try{let{SQLitePatternStore:u}=await import("./sqlite-persistence-ZX5QFDMR.js"),d=new u;await d.initialize(),c=d.getGhostPatternCount(),d.close()}catch{}return{success:!0,data:{status:e?"healthy":"unhealthy",version:"3.15.7",loadedDomains:s,memory:n,hnsw:r,rvf:a??void 0,ghostPatterns:c??void 0,loadedPatterns:i,uptimeMs:t,timestamp:new Date().toISOString()},metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:G(),toolName:"aqe_health"}}}catch(e){return{success:!1,error:E(e),metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:G(),toolName:"aqe_health"}}}}function Bm(o,e){let t=o.getDomainAPI("requirements-validation");t?.registerWorkflowActions&&(t.registerWorkflowActions(e),console.log("[Fleet] Registered requirements-validation workflow actions (includes QCSD Ideation)"));let n=o.getDomainAPI("visual-accessibility");n?.registerWorkflowActions&&(n.registerWorkflowActions(e),console.log("[Fleet] Registered visual-accessibility workflow actions"))}export{Fp as a,Tn as b,Ct as c,Qe as d,oM as e,cM as f,lM as g,uM as h,dM as i,mM as j,pM as k,gM as l,fM as m,hM as n};
742
+ `).run(t.status==="completed"?"completed":t.status==="cancelled"?"cancelled":"failed",new Date(Date.now()-t.totalDurationMs).toISOString(),new Date().toISOString(),t.planId)}catch(r){console.warn("[PlanExecutor] Failed to update goap_plans status (non-fatal):",r)}}async updateActionStats(e,t,n){try{"updateActionStats"in this.planner&&await this.planner.updateActionStats(e,t,n)}catch(r){console.warn("[PlanExecutor] Failed to update action stats:",r)}}meetsConditions(e,t){for(let[n,r]of Object.entries(t))if(!this.checkCondition(e,n,r))return!1;return!0}checkCondition(e,t,n){let r=this.getStateValue(e,t);return typeof n=="string"||typeof n=="number"||typeof n=="boolean"?r===n:!(typeof n=="object"&&n!==null&&("min"in n&&n.min!==void 0&&(typeof r!="number"||r<n.min)||"max"in n&&n.max!==void 0&&(typeof r!="number"||r>n.max)||"eq"in n&&n.eq!==void 0&&r!==n.eq))}applyEffects(e,t){let n=this.cloneState(e);for(let[r,i]of Object.entries(t))this.applyEffect(n,r,i);return n}applyEffect(e,t,n){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean"){this.setStateValue(e,t,n);return}if(typeof n=="object"&&n!==null){let r=this.getStateValue(e,t);if("set"in n&&n.set!==void 0&&this.setStateValue(e,t,n.set),"delta"in n&&n.delta!==void 0&&typeof r=="number"){let i=Math.max(0,Math.min(100,r+n.delta));this.setStateValue(e,t,i)}}}getStateValue(e,t){let n=t.split("."),r=e;for(let i of n){if(r==null)return;r=r[i]}return r}setStateValue(e,t,n){let r=t.split("."),i=new Set(["__proto__","constructor","prototype"]);for(let c of r)if(i.has(c)){console.warn(`[PlanExecutor] Blocked prototype pollution attempt: ${t}`);return}let s=e;for(let c=0;c<r.length-1;c++){let l=r[c];Object.hasOwn(s,l)||Object.defineProperty(s,l,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0});let u=Object.getOwnPropertyDescriptor(s,l);if(!u)return;s=u.value}let a=r[r.length-1];Object.defineProperty(s,a,{value:n,writable:!0,enumerable:!0,configurable:!0})}cloneState(e){return{coverage:{...e.coverage},quality:{...e.quality},fleet:{...e.fleet,availableAgents:[...e.fleet.availableAgents]},resources:{...e.resources},context:{...e.context},patterns:{...e.patterns}}}delay(e){return new Promise(t=>setTimeout(t,e))}async close(){this.currentExecution&&await this.cancel(),this.db&&(this.unifiedMemory?console.log("[PlanExecutor] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[PlanExecutor] Database closed"))),this.unifiedMemory=null,this.initialized=!1}},et=class{successRate;executionDelay;constructor(e){this.successRate=e?.successRate??1,this.executionDelay=e?.executionDelay??100}async spawn(e,t){await new Promise(i=>setTimeout(i,this.executionDelay));let n=oe()<this.successRate,r=`mock-agent-${Mi().slice(0,8)}`;return n?{agentId:r,output:`Successfully executed task for ${e}: ${t.slice(0,50)}...`,success:!0}:{agentId:r,output:"",success:!1,error:`Simulated failure for ${e}`}}};function Ii(o,e){let t=new et({successRate:e?.successRate??1});return new Ze(o,t,e?.dbPath,e?.config)}import*as nr from"fs";import*as Ni from"path";Bt();var lm=["coverage.line","coverage.branch","coverage.function","coverage.target","coverage.measured","quality.testsPassing","quality.totalTests","quality.securityScore","quality.performanceScore","fleet.activeAgents","fleet.availableAgents","fleet.maxAgents","resources.timeRemaining","resources.memoryAvailable","resources.parallelSlots","context.environment","context.riskLevel","patterns.available","patterns.reusable"],Zo=Ni.join("coverage","coverage-summary.json"),um=32*1024*1024;async function dm(){try{let{getFleetState:o,isFleetInitialized:e}=await import("./core-handlers-ZC7QB432.js");if(!e())return null;let{queen:t,kernel:n}=o();if(!t||!n)return null;let r=t.listAllAgents(),i=[...new Set(r.filter(s=>s.status==="running"||s.status==="idle").map(s=>s.type))].sort();return{activeAgents:r.filter(s=>s.status==="running").length,maxAgents:n.getConfig().maxConcurrentAgents,availableAgents:i}}catch{return null}}function Di(o){return typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=100}function mm(o=Ut()){let e=Ni.join(o,Zo);try{let t=nr.statSync(e);if(!t.isFile()||t.size>um)return null;let n=JSON.parse(nr.readFileSync(e,"utf-8")),r=n.total?.lines?.pct,i=n.total?.branches?.pct,s=n.total?.functions?.pct;return!Di(r)||!Di(i)||!Di(s)?null:{line:r,branch:i,function:s,source:Zo,measuredAt:t.mtime.toISOString()}}catch{return null}}function pm(){let o=Pi;return{coverage:{...o.coverage},quality:{...o.quality},fleet:{...o.fleet,availableAgents:[...o.fleet.availableAgents]},resources:{...o.resources},context:{...o.context},patterns:{...o.patterns}}}async function xt(o={}){let e=pm(),t={};for(let s of lm)t[s]="default";let n=await(o.readFleet??dm)();n&&(e.fleet.activeAgents=n.activeAgents,e.fleet.maxAgents=n.maxAgents,e.fleet.availableAgents=[...n.availableAgents],t["fleet.activeAgents"]="live",t["fleet.maxAgents"]="live",t["fleet.availableAgents"]="live");let r=(o.readCoverage??(()=>mm()))(),i;if(r){e.coverage.line=r.line,e.coverage.branch=r.branch,e.coverage.function=r.function,e.coverage.measured=!0;for(let s of["coverage.line","coverage.branch","coverage.function","coverage.measured"])t[s]="measured";i={source:r.source,measuredAt:r.measuredAt}}return{state:e,provenance:t,fleetInitialized:n!==null,coverageReport:i}}var De=o=>typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=100?null:"a number between 0 and 100",tt=o=>typeof o=="number"&&Number.isInteger(o)&&o>=0?null:"a non-negative integer",ec=o=>typeof o=="number"&&Number.isFinite(o)&&o>=0?null:"a non-negative number",gm=o=>typeof o=="boolean"?null:"a boolean",fm=o=>Array.isArray(o)&&o.every(e=>typeof e=="string")?null:"an array of strings",tc=(...o)=>e=>typeof e=="string"&&o.includes(e)?null:`one of ${o.join(", ")}`,hm={"coverage.line":De,"coverage.branch":De,"coverage.function":De,"coverage.target":De,"coverage.measured":gm,"quality.testsPassing":De,"quality.totalTests":tt,"quality.securityScore":De,"quality.performanceScore":De,"fleet.activeAgents":tt,"fleet.availableAgents":fm,"fleet.maxAgents":tt,"resources.timeRemaining":ec,"resources.memoryAvailable":ec,"resources.parallelSlots":tt,"context.environment":tc("development","staging","production"),"context.riskLevel":tc("low","medium","high"),"patterns.available":tt,"patterns.reusable":tt},Oi=["coverage","quality","fleet","resources","context","patterns"],_i=null;function ym(){if(!_i){let o=new Set;for(let e of me()){for(let t of Object.keys(e.preconditions))o.add(t);for(let t of Object.keys(e.effects))o.add(t)}for(let e of Je)for(let t of Object.keys(e.conditions))o.add(t);_i=o}return _i}function nc(o,e=[]){if(typeof o!="object"||o===null||Array.isArray(o))return"currentState must be an object";let t=new Set([...ym(),...e]);for(let[n,r]of Object.entries(o)){if(!Oi.includes(n))return`currentState.${n} is not a world-state section (expected one of ${Oi.join(", ")})`;if(typeof r!="object"||r===null||Array.isArray(r))return`currentState.${n} must be an object`;for(let[i,s]of Object.entries(r)){let a=`${n}.${i}`,c=hm[a];if(c){let l=c(s);if(l)return`currentState.${a} must be ${l}, got ${JSON.stringify(s)}`;continue}if(!t.has(a))return`currentState.${a} is not a known world-state field`;if(typeof s!="boolean"&&typeof s!="string"&&!(typeof s=="number"&&Number.isFinite(s)))return`currentState.${a} must be a boolean, string or finite number, got ${JSON.stringify(s)}`}}return null}function rc(o,e){let t=o.state,n={...o.provenance};for(let r of Oi){let i=e[r];if(!(typeof i!="object"||i===null||Array.isArray(i)))for(let[s,a]of Object.entries(i))s==="__proto__"||s==="constructor"||s==="prototype"||(t[r][s]=Array.isArray(a)?[...a]:a,n[`${r}.${s}`]="caller")}return{...o,provenance:n}}function rr(o){return Object.entries(o).filter(([,e])=>e==="default").map(([e])=>e).sort()}var ic=["maxCost","maxDurationMs","maxSteps","requiredAgentTypes","excludedActions"],At=class extends A{constructor(t={}){super();this.worldStateSources=t}worldStateSources;planner=null;config={name:"qe/planning/goap_plan",description:'Find optimal action plan to achieve a QE goal using A* search. Supports named goals (e.g., "achieve-90-percent-coverage") or custom goal conditions.',domain:"coordination",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{goal:{type:"string",description:'Goal name (e.g., "achieve-90-percent-coverage") or custom goal conditions as JSON object'},currentState:{type:"object",description:"Current world state (auto-detected if not provided). Contains coverage, quality, fleet, resources, context, and patterns."},constraints:{type:"object",description:"Plan constraints",properties:{maxCost:{type:"number",description:"Maximum total cost allowed"},maxDurationMs:{type:"number",description:"Maximum total duration in milliseconds"},maxSteps:{type:"number",description:"Maximum number of steps (actions) in the plan; positive integer",minimum:1},requiredAgentTypes:{type:"array",description:"Only use actions that these agent types can execute",items:{type:"string",description:"Agent type"}},excludedActions:{type:"array",description:"Exclude these specific action IDs",items:{type:"string",description:"Action ID"}}}}},required:["goal"]}}async getPlanner(){return this.planner||(this.planner=Ie(),await this.planner.initialize()),this.planner}resetInstanceCache(){this.planner=null}async execute(t,n){try{let r=this.validateConstraints(t.constraints);if(r)return{success:!1,error:r};let i=await this.getPlanner(),s;if(typeof t.goal=="string"){let m=await i.getGoals(),p=m.find(g=>g.name===t.goal);if(!p){let g=m.map(f=>f.name).join(", ");return{success:!1,error:`Unknown goal: ${t.goal}. Available goals: ${g||"none (seed actions first)"}`}}s=p.conditions}else s=t.goal;if(t.currentState!==void 0){let m=nc(t.currentState,[...i.getReferencedStateKeys(),...Object.keys(s)]);if(m)return{success:!1,error:`Invalid currentState: ${m}`}}let a=t.currentState?rc(await xt(this.worldStateSources),t.currentState):await xt(this.worldStateSources),c=a.state,l=rr(a.provenance),u=t.constraints?{maxCost:t.constraints.maxCost,maxDurationMs:t.constraints.maxDurationMs,maxSteps:t.constraints.maxSteps,requiredAgentTypes:t.constraints.requiredAgentTypes,excludedActions:t.constraints.excludedActions}:void 0,d=await i.findPlan(c,s,u);return d?(l.length===0?this.markAsRealData():this.markAsEstimatedData(),{success:!0,data:{planId:d.id,goal:t.goal,actions:d.actions.map(m=>({name:m.name,agentType:m.agentType,cost:m.cost,category:m.category,description:m.description})),totalCost:d.totalCost,estimatedDurationMs:d.estimatedDurationMs,stepCount:d.actions.length,reusedFrom:d.reusedFrom,similarityScore:d.similarityScore,stateProvenance:a.provenance,defaultedFields:l}}):{success:!1,error:`No valid plan found for the given goal and constraints${u?.maxSteps!==void 0?` (maxSteps: ${u.maxSteps} \u2014 the goal may need more steps)`:""}. Try relaxing constraints or seeding more actions.`}}catch(r){return{success:!1,error:E(r)}}}validateConstraints(t){if(t==null)return null;if(typeof t!="object"||Array.isArray(t))return"constraints must be an object";let n=t,r=Object.keys(n).filter(s=>!ic.includes(s));if(r.length>0)return`Unknown constraint(s): ${r.join(", ")}. Supported constraints: ${ic.join(", ")}`;for(let s of["maxCost","maxDurationMs"]){let a=n[s];if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||a<0))return`constraints.${s} must be a non-negative number, got ${String(a)}`}let i=Pt(n.maxSteps);if(i)return i;for(let s of["requiredAgentTypes","excludedActions"]){let a=n[s];if(a!==void 0&&(!Array.isArray(a)||!a.every(c=>typeof c=="string")))return`constraints.${s} must be an array of strings`}return null}};k();var kt=class extends A{planner=null;executor=null;config={name:"qe/planning/goap_execute",description:"Execute a GOAP plan. Each action dispatches to a real domain API method when the action is marked implemented and a kernel is available (run fleet_init first); actions with no real implementation, or with no domain/kernel available, fail with a specific reason rather than reporting a fabricated success. Supports dry-run mode to preview the plan without executing anything.",domain:"coordination",schema:this.buildSchema(),timeout:3e5};buildSchema(){return{type:"object",properties:{planId:{type:"string",description:"ID of plan to execute (from goap_plan result)"},dryRun:{type:"boolean",description:"Simulate execution without spawning agents (default: false)",default:!1},stepByStep:{type:"boolean",description:"Execute one step at a time (default: false)",default:!1},maxRetries:{type:"number",description:"Max retries per failed step (default: 2)",default:2,minimum:0,maximum:5}},required:["planId"]}}async getPlanner(){return this.planner||(this.planner=Ie(),await this.planner.initialize()),this.planner}async getExecutor(e){if(!this.executor){let t=await this.getPlanner(),n=r=>e?.getDomainAPI(r);this.executor=new Ze(t,new et,void 0,{maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,parallelExecution:!1,recordWorldState:!0},n),await this.executor.initialize()}return this.executor}resetInstanceCache(){this.planner=null,this.executor=null}async execute(e,t){try{let r=await(await this.getPlanner()).getPlan(e.planId);if(!r)return{success:!1,error:`Plan not found: ${e.planId}. Create a plan first using goap_plan.`};if(e.dryRun)return this.markAsRealData(),{success:!0,data:{planId:r.id,mode:"dry-run",status:"completed",stepsCompleted:r.actions.length,stepsFailed:0,totalDurationMs:r.estimatedDurationMs,steps:r.actions.map(c=>({action:c.name,status:"would-execute",retries:0,durationMs:c.estimatedDurationMs}))}};let i=await sn(t),s=await this.getExecutor(i);if(s.isExecuting())return{success:!1,error:"Another plan is currently executing. Wait for completion or cancel it."};let a=await s.execute(r,r.initialState);return this.markAsRealData(),{success:a.status==="completed",data:{planId:a.planId,mode:"execution",status:a.status,stepsCompleted:a.stepsCompleted,stepsFailed:a.stepsFailed,totalDurationMs:a.totalDurationMs,steps:a.steps.map(c=>({action:c.action.name,status:c.status,retries:c.retries,durationMs:c.durationMs,error:c.error})),error:a.error},error:a.status!=="completed"?a.error:void 0}}catch(n){return{success:!1,error:E(n)}}}};k();var Fi=["pending","executing","completed","failed","cancelled"],Mt=class extends A{constructor(t={}){super();this.worldStateSources=t}worldStateSources;planner=null;executor=null;config={name:"qe/planning/goap_status",description:"Get GOAP system status: world state, available goals, actions, or plans. Use to understand current state and available planning options.",domain:"coordination",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{type:{type:"string",description:"What to get status of",enum:["world","goals","actions","plans","execution"]},filter:{type:"object",description:"Optional filters",properties:{category:{type:"string",description:"Filter actions by category (test, security, coverage, etc.)"},status:{type:"string",description:"Filter plans by status (pending, executing, completed, failed, cancelled)",enum:[...Fi]},limit:{type:"number",description:"Maximum number of results (default: 20)",default:20,minimum:1,maximum:100}}}},required:["type"]}}async getPlanner(){return this.planner||(this.planner=Ie(),await this.planner.initialize()),this.planner}async getExecutor(){if(!this.executor){let t=await this.getPlanner();this.executor=Ii(t),await this.executor.initialize()}return this.executor}resetInstanceCache(){this.planner=null,this.executor=null}async execute(t,n){try{switch(t.type){case"world":return this.getWorldState();case"goals":return this.getGoals();case"actions":return this.getActions(t.filter?.category,t.filter?.limit);case"plans":return this.getPlans(t.filter?.status,t.filter?.limit);case"execution":return this.getExecutionStatus();default:return{success:!1,error:`Unknown status type: ${t.type}`}}}catch(r){return{success:!1,error:E(r)}}}async getWorldState(){let t=await xt(this.worldStateSources),{state:n,provenance:r}=t,i=l=>r[l]!=="default",s=(l,u)=>i(l)?u:null,a=rr(r);return["coverage.line","coverage.branch","coverage.function","quality.testsPassing","quality.securityScore","quality.performanceScore","fleet.activeAgents","fleet.maxAgents","resources.timeRemaining","resources.parallelSlots"].every(i)?this.markAsRealData():this.markAsEstimatedData(),{success:!0,data:{type:"world",data:{coverage:{line:s("coverage.line",n.coverage.line),branch:s("coverage.branch",n.coverage.branch),function:s("coverage.function",n.coverage.function),measured:n.coverage.measured,...t.coverageReport?{report:t.coverageReport}:{}},quality:{testsPassing:s("quality.testsPassing",n.quality.testsPassing),securityScore:s("quality.securityScore",n.quality.securityScore),performanceScore:s("quality.performanceScore",n.quality.performanceScore)},fleet:{initialized:t.fleetInitialized,activeAgents:n.fleet.activeAgents,maxAgents:s("fleet.maxAgents",n.fleet.maxAgents),availableAgents:[...n.fleet.availableAgents]},resources:{timeRemaining:s("resources.timeRemaining",n.resources.timeRemaining),parallelSlots:s("resources.parallelSlots",n.resources.parallelSlots)},provenance:r,defaultedFields:a}}}}async getGoals(){let n=await(await this.getPlanner()).getGoals();return this.markAsRealData(),{success:!0,data:{type:"goals",data:{goals:n.map(r=>({id:r.id,name:r.name,description:r.description,priority:r.priority,conditionCount:Object.keys(r.conditions).length})),count:n.length}}}}async getActions(t,n=50){let r=[],i=me(),s=t?i.filter(c=>c.category===t):i;r=s.slice(0,n).map((c,l)=>({id:`action-${l}`,name:c.name,category:c.category,agentType:c.agentType,cost:c.cost,successRate:c.successRate}));let a={};for(let c of i)a[c.category]=(a[c.category]||0)+1;return this.markAsRealData(),{success:!0,data:{type:"actions",data:{actions:r,count:s.length,byCategory:a}}}}async getPlans(t,n=20){if(t!==void 0&&!Fi.includes(t))return{success:!1,error:`filter.status must be one of: ${Fi.join(", ")}`};let r=await this.getPlanner(),[{plans:i,count:s,invalidPlanIds:a},c]=await Promise.all([r.listPlanSummaries(t,n),r.getPlanReuseStats()]);return this.markAsRealData(),{success:!0,data:{type:"plans",data:{plans:i,count:s,...a?{invalidPlanIds:a}:{},reuseStats:{totalPlans:c.totalPlans,reusedPlans:c.reusedPlans,reuseRate:c.reuseRate,avgSuccessRate:c.avgSuccessRate}}}}}async getExecutionStatus(){let n=(await this.getExecutor()).isExecuting();return this.markAsRealData(),{success:!0,data:{type:"execution",data:{isExecuting:n,message:n?"Plan execution in progress":"No active execution"}}}}};k();mt();ue();k();k();mt();var It={HEALTH:"qe/mincut/health",ANALYZE:"qe/mincut/analyze",STRENGTHEN:"qe/mincut/strengthen"};function Gi(){return gr()}function wm(){return fr()}var Li=class extends A{config={name:It.HEALTH,description:"Analyze swarm topology health using MinCut algorithms. Reports connectivity, weak points, and health trends.",domain:"coordination",schema:{type:"object",properties:{agents:{type:"array",description:"Agent vertices to add to the graph before analysis"},edges:{type:"array",description:"Edges to add between agents"},includeWeakVertices:{type:"boolean",description:"Include detailed weak vertex analysis",default:!0},includeHistory:{type:"boolean",description:"Include historical health data",default:!1}},additionalProperties:!0}};async execute(e,t){let n=Gi(),r=wm(),i=ve();if(e.agents)for(let l of e.agents)n.hasVertex(l.id)||n.addVertex({id:l.id,type:"agent",domain:l.domain,weight:l.weight??1,createdAt:new Date});if(e.edges)for(let l of e.edges)n.hasVertex(l.source)&&n.hasVertex(l.target)&&(n.hasEdge(l.source,l.target)||n.addEdge({source:l.source,target:l.target,weight:l.weight??1,type:"coordination",bidirectional:!0}));let s=r.checkHealth(),a=e.includeWeakVertices!==!1?i.findWeakVertices(n):[],c={health:{status:s.status,minCutValue:s.minCutValue,healthyThreshold:s.healthyThreshold,warningThreshold:s.warningThreshold,weakVertexCount:s.weakVertexCount,trend:s.trend},topology:{vertexCount:n.vertexCount,edgeCount:n.edgeCount,isConnected:n.isConnected()}};return e.includeWeakVertices!==!1&&a.length>0&&(c.weakVertices=a.map(l=>({id:l.vertexId,domain:l.vertex?.domain,weightedDegree:l.weightedDegree,riskScore:l.riskScore,reason:l.reason}))),e.includeHistory&&(c.history=s.history.map(l=>({timestamp:l.timestamp,value:l.value}))),this.markAsRealData(),{success:!0,data:c,metadata:this.createMetadata(t.startTime,t.requestId)}}},qi=class extends A{config={name:It.ANALYZE,description:"Deep analysis of swarm topology using MinCut algorithms. Identifies weak points, suggests improvements.",domain:"coordination",schema:{type:"object",properties:{weaknessThreshold:{type:"number",description:"Threshold for weak vertex detection"},includePartitioningPoints:{type:"boolean",description:"Include analysis of potential partitioning points",default:!1}},additionalProperties:!0}};async execute(e,t){let n=Gi(),r=ve(),i=r.getMinCutValue(n),s=r.getMinDegreeVertex(n),a=r.findWeakVertices(n,e.weaknessThreshold),c=r.suggestEdgeAdditions(n,2),l={minCutValue:i,minDegreeVertex:s,weakVertices:a.map(u=>({id:u.vertexId,weightedDegree:u.weightedDegree,riskScore:u.riskScore,reason:u.reason,suggestions:u.suggestions.map(d=>({type:d.type,priority:d.priority,estimatedImprovement:d.estimatedImprovement}))})),suggestedEdges:c.map(u=>({source:u.source,target:u.target,weight:u.weight}))};return e.includePartitioningPoints&&(l.partitioningPoints=r.findPartitioningPoints(n)),this.markAsRealData(),{success:!0,data:l,metadata:this.createMetadata(t.startTime,t.requestId)}}},$i=class extends A{config={name:It.STRENGTHEN,description:"Strengthen swarm topology by adding edges between weak and strong vertices.",domain:"coordination",schema:{type:"object",properties:{targetImprovement:{type:"number",description:"Target improvement in MinCut value",default:1},targetVertices:{type:"array",description:"Specific vertices to strengthen"},apply:{type:"boolean",description:"Apply changes (true) or simulate (false)",default:!1}},additionalProperties:!0}};async execute(e,t){let n=Gi(),r=ve(),i=r.getMinCutValue(n),s=e.targetImprovement??1,a=r.suggestEdgeAdditions(n,s),c=[];if(e.apply)for(let u of a)n.addEdge({source:u.source,target:u.target,weight:u.weight,type:"coordination",bidirectional:!0}),c.push({type:"add_edge",source:u.source,target:u.target,weight:u.weight});else for(let u of a)c.push({type:"add_edge",source:u.source,target:u.target,weight:u.weight});let l=r.getMinCutValue(n);return this.markAsRealData(),{success:!0,data:{beforeMinCut:i,afterMinCut:e.apply?l:i+s,improvement:e.apply?l-i:s,actionsApplied:c,applied:e.apply??!1},metadata:this.createMetadata(t.startTime,t.requestId)}}},oc=[new Li,new qi,new $i];k();var ji=null,ir=null;async function Dt(){return ji||ir||(ir=(async()=>{let o=gn({embedding:{model:"all-MiniLM-L6-v2",cacheSize:1e3,normalize:!0,hyperbolic:!1,curvature:-1},autoInitialize:!1});return await o.initialize(),ji=o,console.error("[EmbeddingTool] ONNX adapter initialized"),o})(),ir)}var nt=class extends A{config={name:"qe/embeddings/generate",description:"Generate a vector embedding for text using local ONNX model",domain:"learning-optimization",schema:{type:"object",properties:{text:{type:"string",description:"Text to generate embedding for",minLength:1,maxLength:1e4},hyperbolic:{type:"boolean",description:"Use hyperbolic space for hierarchical data",default:!1}},required:["text"]}};async execute(e,t){let n=performance.now();try{let r=await Dt(),i=await r.generateEmbedding(e.text);e.hyperbolic&&(i=r.toHyperbolic(i));let s=performance.now()-n;return this.markAsRealData(),{success:!0,data:{embedding:Array.from(i.vector),dimension:i.dimensions,isHyperbolic:i.isHyperbolic,latencyMs:s,model:i.model}}}catch(r){return{success:!1,error:`Embedding generation failed: ${E(r)}`}}}},rt=class extends A{config={name:"qe/embeddings/compare",description:"Compare semantic similarity between two texts",domain:"learning-optimization",schema:{type:"object",properties:{text1:{type:"string",description:"First text to compare",minLength:1},text2:{type:"string",description:"Second text to compare",minLength:1},metric:{type:"string",description:"Similarity metric",enum:["cosine","euclidean","poincare"],default:"cosine"}},required:["text1","text2"]}};async execute(e,t){let n=performance.now();try{let r=await Dt(),i=e.metric||"cosine",s=i==="cosine"?"cosine":i==="euclidean"?"euclidean":"poincare",a=await r.compareSimilarity(e.text1,e.text2,s),c=performance.now()-n;return this.markAsRealData(),{success:!0,data:{similarity:a,metric:i,isSimilar:a>.7,latencyMs:c}}}catch(r){return{success:!1,error:`Similarity comparison failed: ${E(r)}`}}}},it=class extends A{config={name:"qe/embeddings/search",description:"Search for semantically similar texts using vector search",domain:"learning-optimization",schema:{type:"object",properties:{query:{type:"string",description:"Query text to search for",minLength:1},namespace:{type:"string",description:"Namespace to search in",default:"default"},topK:{type:"number",description:"Number of results to return",minimum:1,maximum:100,default:10},threshold:{type:"number",description:"Minimum similarity threshold (0-1)",minimum:0,maximum:1,default:.5}},required:["query"]}};async execute(e,t){let n=performance.now();try{let i=await(await Dt()).searchByText(e.query,{metric:"cosine",topK:e.topK??10,threshold:e.threshold??.5,namespace:e.namespace}),s=performance.now()-n;return this.markAsRealData(),{success:!0,data:{results:i.map(a=>({text:a.text,score:a.score,metadata:a.metadata})),totalFound:i.length,latencyMs:s}}}catch(r){return{success:!1,error:`Search failed: ${E(r)}`}}}},st=class extends A{config={name:"qe/embeddings/store",description:"Store text with its embedding for later retrieval",domain:"learning-optimization",schema:{type:"object",properties:{text:{type:"string",description:"Text to store",minLength:1},id:{type:"string",description:"Optional ID for the stored embedding"},namespace:{type:"string",description:"Namespace for organization",default:"default"},metadata:{type:"object",description:"Additional metadata to store"}},required:["text"]}};async execute(e,t){let n=performance.now();try{let r=await Dt(),i=e.namespace||"default",s=await r.generateAndStore(e.text,{id:e.id,namespace:i,customData:e.metadata}),a=performance.now()-n;return this.markAsRealData(),{success:!0,data:{id:s.id,namespace:s.namespace||i,latencyMs:a}}}catch(r){return{success:!1,error:`Store failed: ${E(r)}`}}}},at=class extends A{config={name:"qe/embeddings/stats",description:"Get ONNX embedding system statistics",domain:"learning-optimization",schema:{type:"object",properties:{}}};async execute(e,t){try{let n=await Dt(),r=n.getStats(),i=await n.getHealth(),s=r.cacheHits+r.cacheMisses,a=s>0?r.cacheHits/s:0;return this.markAsRealData(),{success:!0,data:{totalGenerated:r.totalGenerated,vectorsStored:r.vectorsStored,cache:{hits:r.cacheHits,misses:r.cacheMisses,hitRate:a},model:{name:r.currentModel,dimension:r.currentModel==="all-MiniLM-L6-v2"?384:768},healthy:i.available}}}catch(n){return{success:!1,error:`Stats failed: ${E(n)}`}}}},Rm=new nt,Pm=new rt,xm=new it,Am=new st,km=new at;k();var Mm={type:"object",properties:{nodes:{type:"array",description:"Array of nodes to check for coherence. Each node must have an id and embedding vector."},energyThreshold:{type:"number",description:"Custom energy threshold for contradiction detection (default: 0.4)",minimum:0,maximum:1}},required:["nodes"]},_t=class extends A{config={name:"qe/coherence/check",description:"Check mathematical coherence of beliefs/facts using Prime Radiant sheaf cohomology. Detects contradictions and computes coherence energy for multi-agent coordination.",domain:"learning-optimization",schema:Mm,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await be(Ce)),this.coherenceService}resetInstanceCache(){this.coherenceService&&(this.coherenceService.dispose(),this.coherenceService=null)}async execute(e,t){let n=Date.now(),{nodes:r,energyThreshold:i=.4}=e;if(!r||r.length===0)return{success:!1,error:"At least one node is required for coherence check"};for(let s of r)if(!s.embedding||!Array.isArray(s.embedding))return{success:!1,error:`Node ${s.id} has invalid embedding - must be an array of numbers`};try{let s=await this.getService(),a=r.map(m=>({id:m.id,embedding:m.embedding,weight:m.weight??1,metadata:m.metadata})),c=await s.checkCoherence(a),l=[...c.recommendations,...this.generateAdditionalRecommendations(c,i)],u=c.contradictions.map(m=>({nodeIds:m.nodeIds,severity:String(m.severity),description:m.description||`Contradiction between nodes ${m.nodeIds[0]} and ${m.nodeIds[1]}`})),d=Date.now()-n;return this.markAsRealData(),{success:!0,data:{isCoherent:c.isCoherent,energy:c.energy,lane:c.lane,contradictions:u,recommendations:l,nodeCount:r.length,executionTimeMs:d,usedFallback:c.usedFallback}}}catch(s){return s instanceof Error&&s.message.includes("WASM")?(this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{isCoherent:!0,energy:.1,lane:"reflex",contradictions:[],recommendations:["WASM module unavailable - coherence check running in fallback mode","Install prime-radiant-advanced-wasm for full coherence verification"],nodeCount:r.length,executionTimeMs:Date.now()-n,usedFallback:!0}}):{success:!1,error:E(s)}}}generateAdditionalRecommendations(e,t){let n=[];switch(e.energy>t&&n.push(`High coherence energy (${e.energy.toFixed(3)}) detected - review contradicting beliefs`),e.lane){case"reflex":n.push("Low energy - safe for immediate execution");break;case"retrieval":n.push("Moderate energy - consider fetching additional context");break;case"heavy":n.push("High energy - deep analysis recommended");break;case"human":n.push("Critical energy - escalate to Queen coordinator");break}return n}};var Im=["rename","framework-transfer","reordered-steps","distractor-terminology","cross-domain-transfer"],RR=[["async-race","observe completion before assertion","await the operation","increase the timeout","completion probe","unit","vitest"],["stale-cache","invalidate on every state mutation","invalidate the cache","retry the read","freshness assertion","integration","redis"],["transaction-leak","rollback isolates each test","rollback the transaction","truncate a shared table","row-count check","database","postgres"],["clock-skew","compare times in one clock domain","inject a monotonic clock","widen the time window","clock boundary check","unit","node"],["event-loss","subscribe before publishing","register the listener first","publish twice","delivery assertion","events","eventemitter"],["resource-leak","release resources on every exit","close in a finally block","raise the pool limit","handle-count check","integration","playwright"],["eventual-consistency","poll the observable state","poll with a bounded deadline","sleep for a fixed delay","state convergence","distributed","kubernetes"],["identity-confusion","compare canonical identities","normalize the identifier","use display names","identity equality","security","oauth"],["partial-write","publish only complete state","commit through an atomic swap","ignore missing fields","atomicity check","filesystem","node"],["order-dependence","tests start from isolated state","reset state in setup","force alphabetical order","shuffle repeat","unit","jest"],["schema-drift","validate at the boundary","reject the incompatible schema","cast the payload","schema validator","api","zod"],["backpressure-loss","producer respects consumer capacity","await the drain signal","increase buffer memory","loss counter","performance","streams"],["retry-duplication","retries preserve idempotency","attach an idempotency key","disable all retries","duplicate detector","api","fetch"],["permission-bypass","authorization precedes mutation","check permission before write","hide the user interface","denial assertion","security","express"],["encoding-mismatch","encode and decode with one charset","set UTF-8 explicitly","strip non-ASCII text","round-trip equality","api","json"],["pagination-gap","cursor advances from the last item","use the returned cursor","increase page size","set equality","api","graphql"],["cancellation-leak","cancellation propagates to children","forward the abort signal","wait for natural completion","abort observation","integration","abortcontroller"],["floating-point-boundary","compare numeric results by tolerance","use an error bound","round every input","relative-error check","unit","vitest"],["locale-dependence","format under an explicit locale","pass the locale explicitly","update the snapshot locally","multi-locale check","ui","intl"],["lock-starvation","lock acquisition remains fair","queue lock waiters","raise retry count","bounded-wait check","concurrency","mutex"]].map(([o,e,t,n,r,i,s])=>({mechanism:o,invariant:e,action:t,wrongAction:n,oracle:r,domain:i,framework:s}));var Dm=Object.freeze([...Im]);Wi();k();var GR=Gt.create("qe-unified-memory");var Om={"test-suites":{dimensions:Se.DIMENSIONS,M:8,efConstruction:100,efSearch:50,metric:"cosine",namespace:"test-suites-hnsw",maxElements:1e5},coverage:{dimensions:Se.DIMENSIONS,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},defects:{dimensions:Se.DIMENSIONS,M:32,efConstruction:400,efSearch:200,metric:"cosine",namespace:"defects-hnsw",maxElements:1e5},quality:{dimensions:Se.DIMENSIONS,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"quality-hnsw",maxElements:1e5},learning:{dimensions:Se.DIMENSIONS,M:24,efConstruction:300,efSearch:150,metric:"cosine",namespace:"learning-hnsw",maxElements:1e5},coordination:{dimensions:Se.DIMENSIONS,M:8,efConstruction:100,efSearch:50,metric:"cosine",namespace:"coordination-hnsw",maxElements:5e4}},Nm={enableHNSW:{"test-suites":!0,coverage:!0,defects:!0,quality:!0,learning:!0,coordination:!0},defaultNamespace:"qe-unified",enableCrossDomainSearch:!0,embeddingDimension:Se.DIMENSIONS};Wi();k();import{randomUUID as Fm}from"crypto";var zi=Gt.create("MemoryAuditor"),Ui={batchSize:50,energyThreshold:.4,hotspotThreshold:.6,maxRecommendations:10},sr=class{constructor(e,t,n=Ui){this.coherenceService=e;this.eventBus=t;this.config=n}coherenceService;eventBus;config;isAuditing=!1;async auditPatterns(e){let t=Date.now();await this.emitEvent("memory:audit_started",{totalPatterns:e.length,timestamp:new Date});try{let n=this.groupByDomain(e),r=[],i=0,s=0;for(let[p,g]of Object.entries(n)){if(g.length<2)continue;let f=this.patternsToNodes(g),h=await this.coherenceService.checkCoherence(f);s+=h.energy,i+=h.contradictions.length,h.energy>this.config.hotspotThreshold&&r.push({domain:p,patternIds:g.map(v=>v.id),energy:h.energy,description:this.describeHotspot(h,p)})}let a=Object.keys(n).length,c=a>0?s/a:0,l=await this.identifyHotspots(e),u=await this.generateRecommendations(l,e),d=Date.now()-t,m={totalPatterns:e.length,scannedPatterns:e.length,contradictionCount:i,globalEnergy:c,hotspots:l,recommendations:u,duration:d,timestamp:new Date};return await this.emitEvent("memory:audit_completed",{result:m,timestamp:new Date}),m}catch(n){try{await this.emitEvent("memory:audit_failed",{error:E(n),timestamp:new Date})}catch(r){zi.warn("Failed to emit audit_failed event",{error:E(r)})}throw n}}async identifyHotspots(e){let t=[],n=this.groupByDomain(e);for(let[r,i]of Object.entries(n)){if(i.length<2)continue;let s=this.patternsToNodes(i),a=await this.coherenceService.checkCoherence(s);a.energy>this.config.hotspotThreshold&&t.push({domain:r,patternIds:i.map(c=>c.id),energy:a.energy,description:this.describeHotspot(a,r)})}return t}async generateRecommendations(e,t){let n=[],r=new Map(t.map(i=>[i.id,i]));for(let i of e){let s=i.patternIds.map(u=>r.get(u)).filter(u=>u!==void 0),a=this.findDuplicates(s);a.length>0&&n.push({type:"merge",patternIds:a,reason:`Detected ${a.length} similar patterns in ${i.domain} domain`,priority:"high"});let c=this.findOutdated(s);c.length>0&&n.push({type:"remove",patternIds:c,reason:`Found ${c.length} outdated patterns with low usage/success`,priority:"medium"}),i.energy>.7&&n.push({type:"review",patternIds:i.patternIds,reason:`Critical coherence energy (${i.energy.toFixed(2)}) in ${i.domain}`,priority:"high"});let l=this.findBroadPatterns(s);l.length>0&&n.push({type:"split",patternIds:l,reason:`Found ${l.length} overly generic patterns that should be specialized`,priority:"low"})}return n.sort((i,s)=>this.priorityValue(s.priority)-this.priorityValue(i.priority)).slice(0,this.config.maxRecommendations)}async runBackgroundAudit(e){if(this.isAuditing){zi.warn("Audit already in progress, skipping");return}this.isAuditing=!0;try{await this.emitEvent("memory:audit_progress",{status:"fetching_patterns",timestamp:new Date});let t=await e();await this.emitEvent("memory:audit_progress",{status:"analyzing_coherence",totalPatterns:t.length,timestamp:new Date});let n=await this.auditPatterns(t);await this.emitEvent("memory:audit_progress",{status:"completed",result:n,timestamp:new Date})}catch(t){await this.emitEvent("memory:audit_progress",{status:"failed",error:E(t),timestamp:new Date})}finally{this.isAuditing=!1}}groupByDomain(e){let t={};for(let n of e){let r=n.qeDomain;t[r]||(t[r]=[]),t[r].push(n)}return t}patternsToNodes(e){return e.map(t=>({id:t.id,embedding:t.embedding||this.createFallbackEmbedding(t),weight:t.qualityScore,metadata:{name:t.name,description:t.description,domain:t.qeDomain,confidence:t.confidence,usageCount:t.usageCount,successRate:t.successRate}}))}createFallbackEmbedding(e){let t=`${e.name} ${e.description}`,n=[];for(let r=0;r<64;r++){let i=t.charCodeAt(r%t.length);n.push(i/255*2-1)}return n}describeHotspot(e,t){let n=e.energy.toFixed(2),r=e.contradictions.length;return r>0?`${t} has ${r} contradiction(s) with energy ${n}`:`${t} has high coherence energy (${n}) indicating potential inconsistencies`}findDuplicates(e){let t=[],n=new Map;for(let r of e){let i=this.normalizeText(`${r.name} ${r.description}`);n.has(i)||n.set(i,[]),n.get(i).push(r.id)}for(let[r,i]of n)i.length>1&&t.push(...i.slice(1));return t}findOutdated(e){return e.filter(t=>t.usageCount<5&&t.successRate<.5).map(t=>t.id)}findBroadPatterns(e){return e.filter(t=>{let n=/generic|general|common|basic/i.test(t.name),r=t.context?.tags,i=!r||r.length<2;return n||i}).map(t=>t.id)}normalizeText(e){return e.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim()}priorityValue(e){switch(e){case"high":return 3;case"medium":return 2;case"low":return 1;default:return 0}}async emitEvent(e,t){if(this.eventBus)try{await this.eventBus.publish({id:`memory-audit-${Date.now()}-${Fm().split("-")[0]}`,type:e,source:"learning-optimization",timestamp:new Date,payload:t})}catch(n){zi.warn("Failed to emit event",{eventType:e,error:E(n)})}}};function Bi(o,e,t){return new sr(o,e,{...Ui,...t})}k();var Lm={type:"object",properties:{namespace:{type:"string",description:"Namespace to audit (default: qe-patterns)",default:"qe-patterns"},maxPatterns:{type:"number",description:"Maximum patterns to scan (default: 1000)",default:1e3,minimum:1,maximum:1e4},energyThreshold:{type:"number",description:"Energy threshold for flagging issues (default: 0.4)",default:.4,minimum:0,maximum:1},includeDetails:{type:"boolean",description:"Include detailed pattern information in results",default:!1}},required:[]},Ot=class extends A{config={name:"qe/coherence/audit",description:"Audit QE memory for contradictions and coherence issues. Scans patterns, detects hotspots, and generates remediation recommendations.",domain:"learning-optimization",schema:Lm,streaming:!1,timeout:6e4};coherenceService=null;auditor=null;async getService(){return this.coherenceService||(this.coherenceService=await be(Ce)),this.coherenceService}resetInstanceCache(){this.coherenceService&&(this.coherenceService.dispose(),this.coherenceService=null),this.auditor=null}async execute(e,t){let{namespace:n="qe-patterns",maxPatterns:r=1e3,energyThreshold:i=.4}=e;try{let s=await this.getService();this.auditor||(this.auditor=Bi(s,void 0,{energyThreshold:i,hotspotThreshold:i+.2,maxRecommendations:10}));let a=await O(),c=pr(a,{namespace:n,embeddingDimension:384});await c.initialize();let l=await c.search("",{limit:r,useVectorSearch:!1}),u=l.success?l.value.map(p=>p.pattern):[],d;u.length>0?d=await this.auditor.auditPatterns(u):d={totalPatterns:0,scannedPatterns:0,contradictionCount:0,globalEnergy:0,hotspots:[],recommendations:[],duration:0,timestamp:new Date};let m=this.calculateHealthScore(d);return this.markAsRealData(),{success:!0,data:{totalPatterns:d.totalPatterns,scannedPatterns:d.scannedPatterns,contradictionCount:d.contradictionCount,globalEnergy:d.globalEnergy,hotspots:d.hotspots.map(p=>({domain:p.domain,patternIds:p.patternIds,energy:p.energy,description:p.description})),recommendations:d.recommendations.map(p=>({type:p.type,patternIds:p.patternIds,reason:p.reason,priority:p.priority})),durationMs:d.duration,timestamp:d.timestamp.toISOString(),healthScore:m}}}catch(s){return s instanceof Error&&s.message.includes("WASM")?(this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{totalPatterns:0,scannedPatterns:0,contradictionCount:0,globalEnergy:0,hotspots:[],recommendations:[{type:"review",patternIds:[],reason:"WASM module unavailable - install prime-radiant-advanced-wasm for full audit",priority:"medium"}],durationMs:0,timestamp:new Date().toISOString(),healthScore:100}}):{success:!1,error:E(s)}}}calculateHealthScore(e){let t=100;t-=Math.min(30,e.contradictionCount*5),t-=Math.min(30,e.globalEnergy*50),t-=Math.min(20,e.hotspots.length*5);let n=e.recommendations.filter(r=>r.priority==="high").length;return t-=Math.min(20,n*5),Math.max(0,Math.round(t))}};k();function qm(o){let e="Each vote must be { agentId: string, verdict: string | number | boolean, confidence: number 0-1 }.";for(let t=0;t<o.length;t++){let n=o[t];if(typeof n!="object"||n===null||Array.isArray(n))return`votes[${t}] must be an object. ${e}`;let{agentId:r,verdict:i,confidence:s}=n;if(typeof r!="string"||r.trim()==="")return`votes[${t}].agentId must be a non-empty string. ${e}`;let a=typeof i;if(a!=="string"&&a!=="number"&&a!=="boolean")return`votes[${t}].verdict is required (string, number, or boolean), got ${i===null?"null":a}. ${e}`;if(typeof s!="number"||!Number.isFinite(s)||s<0||s>1)return`votes[${t}].confidence must be a number between 0 and 1, got ${JSON.stringify(s)??"undefined"}. ${e}`}return null}var $m={type:"object",properties:{votes:{type:"array",description:"Array of agent votes to verify for consensus (at least 2). Each vote is an object { agentId: string, verdict: string | number | boolean, confidence: number 0-1, agentType?: string, reasoning?: string }.",items:{type:"object",description:"One agent vote",properties:{agentId:{type:"string",description:"Agent identifier",minLength:1},agentType:{type:"string",description:"Agent type (default: worker)"},confidence:{type:"number",description:"Confidence in the verdict",minimum:0,maximum:1},reasoning:{type:"string",description:"Optional reasoning text"}},required:["agentId","verdict","confidence"]}},confidenceThreshold:{type:"number",description:"Minimum confidence threshold (0-1, default: 0.5)",default:.5,minimum:0,maximum:1}},required:["votes"]},Nt=class extends A{config={name:"qe/coherence/consensus",description:"Verify multi-agent consensus mathematically using spectral analysis. Detects false consensus where agents appear to agree but have divergent beliefs.",domain:"learning-optimization",schema:$m,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await be(Ce)),this.coherenceService}resetInstanceCache(){this.coherenceService&&(this.coherenceService.dispose(),this.coherenceService=null)}async execute(e,t){let n=Date.now(),{votes:r,confidenceThreshold:i=.5}=e;if(!r||r.length===0)return{success:!1,error:"At least one vote is required for consensus verification"};if(r.length<2)return{success:!1,error:"At least two votes are required to verify consensus"};let s=qm(r);if(s)return{success:!1,error:s};try{let a=await this.getService(),c=r.map(p=>({agentId:p.agentId,agentType:p.agentType||"worker",verdict:p.verdict,confidence:p.confidence,reasoning:p.reasoning,timestamp:new Date})),l=await a.verifyConsensus(c),u=l.recommendation,d=r.reduce((p,g)=>p+g.confidence,0)/r.length;d<i&&(u=`Low average confidence (${(d*100).toFixed(1)}%) - consider gathering more evidence. `+u);let m=Date.now()-n;return this.markAsRealData(),{success:!0,data:{isValid:l.isValid,isFalseConsensus:l.isFalseConsensus,confidence:l.confidence,fiedlerValue:l.fiedlerValue,collapseRisk:l.collapseRisk,recommendation:u,usedFallback:l.usedFallback,executionTimeMs:m}}}catch(a){if(a instanceof Error&&a.message.includes("WASM")){let c=this.simpleMajorityAnalysis(r);return this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{...c,recommendation:`Running in fallback mode (simple analysis): ${ts(es(r))} across ${r.length} votes. Install prime-radiant-advanced-wasm for spectral consensus analysis.`,usedFallback:!0,executionTimeMs:Date.now()-n}}}return{success:!1,error:E(a)}}}simpleMajorityAnalysis(e){let t=new Map;for(let s of e){let a=String(s.verdict);t.set(a,(t.get(a)||0)+1)}let n=0;for(let s of t.values())s>n&&(n=s);let r=n/e.length,i=e.reduce((s,a)=>s+a.confidence,0)/e.length;return{isValid:r>=.5&&i>=.5,isFalseConsensus:!1,confidence:i,fiedlerValue:0,collapseRisk:1-r}}};k();var Gm={type:"object",properties:{swarmState:{type:"object",description:"Current state of the swarm including agents and task info"},riskThreshold:{type:"number",description:"Risk threshold for warning (0-1, default: 0.5)",default:.5,minimum:0,maximum:1}},required:["swarmState"]},Ft=class extends A{config={name:"qe/coherence/collapse",description:"Predict swarm collapse risk using spectral analysis. Identifies vulnerable vertices and provides mitigation recommendations.",domain:"learning-optimization",schema:Gm,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await be(Ce)),this.coherenceService}resetInstanceCache(){this.coherenceService&&(this.coherenceService.dispose(),this.coherenceService=null)}async execute(e,t){let n=Date.now(),{swarmState:r,riskThreshold:i=.5}=e;if(!r)return{success:!1,error:"swarmState is required"};if(!r.agents||r.agents.length<1)return{success:!1,error:"At least one agent is required in swarmState"};try{let s=await this.getService(),a={agents:r.agents.map(g=>({agentId:g.agentId,agentType:g.agentType||"worker",health:Number.isFinite(g.health)?g.health:1,beliefs:[],lastActivity:new Date,errorCount:g.errorCount??0,successRate:Number.isFinite(g.successRate)?g.successRate:1})),activeTasks:Number.isFinite(r.activeTasks)?r.activeTasks:0,pendingTasks:Number.isFinite(r.pendingTasks)?r.pendingTasks:0,errorRate:Number.isFinite(r.errorRate)?r.errorRate:0,utilization:Number.isFinite(r.utilization)?r.utilization:0,timestamp:new Date},c=await s.predictCollapse(a),l=Number.isFinite(c.risk)?c.risk:0,u=this.categorizeRisk(l),d=[...c.recommendations,...this.generateAdditionalRecommendations(c,r)],m=Date.now()-n;this.markAsRealData();let p=u==="high"||u==="critical"||u==="medium"&&l>=i;return{success:!0,data:{risk:l,isAtRisk:p,riskLevel:u,fiedlerValue:c.fiedlerValue,collapseImminent:c.collapseImminent,weakVertices:c.weakVertices,recommendations:d,executionTimeMs:m,usedFallback:c.usedFallback}}}catch(s){if(s instanceof Error&&s.message.includes("WASM")){let a=this.heuristicAnalysis(r,i);return this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{...a,recommendations:["Running in fallback mode (heuristic analysis)","Install prime-radiant-advanced-wasm for spectral collapse prediction",...a.recommendations],usedFallback:!0,executionTimeMs:Date.now()-n}}}return{success:!1,error:E(s)}}}categorizeRisk(e){return!Number.isFinite(e)||e<.25?"low":e<.5?"medium":e<.75?"high":"critical"}generateAdditionalRecommendations(e,t){let n=[];t.errorRate>.1&&n.push(`High system error rate (${(t.errorRate*100).toFixed(1)}%) - investigate root causes`),t.utilization>.85&&n.push(`High resource utilization (${(t.utilization*100).toFixed(1)}%) - consider scaling`),t.pendingTasks>t.activeTasks*2&&n.push(`Large task backlog (${t.pendingTasks} pending) - may need more agents`);let r=t.agents.filter(i=>i.health<.5);return r.length>0&&n.push(`${r.length} agent(s) with low health - consider replacement`),e.risk>=.75&&n.unshift("\u26A0\uFE0F CRITICAL: Immediate action required to prevent collapse"),n}heuristicAnalysis(e,t){let n=0,r=[],i=[],s=Number.isFinite(e.errorRate)?e.errorRate:0,a=Number.isFinite(e.utilization)?e.utilization:0,c=Number.isFinite(e.pendingTasks)?e.pendingTasks:0,l=Number.isFinite(e.activeTasks)?e.activeTasks:0,u=e.agents.map(f=>Number.isFinite(f.health)?f.health:1),d=u.length>0?u.reduce((f,h)=>f+h,0)/u.length:1;n+=(1-d)*.3,n+=Math.min(.25,s*2.5),a>.7&&(n+=(a-.7)*.5);let m=c/Math.max(1,l);m>1&&(n+=Math.min(.2,(m-1)*.1)),e.agents.forEach((f,h)=>{(u[h]<.5||(f.errorCount??0)>5)&&i.push(f.agentId)}),n=Math.min(1,n),n>=t&&(r.push("Consider reducing task load"),r.push("Monitor agent health closely")),i.length>0&&r.push(`Reinforce weak agents: ${i.join(", ")}`),n<.25&&r.push("Swarm appears stable - continue normal operations");let p=this.categorizeRisk(n),g=p==="high"||p==="critical"||p==="medium"&&n>=t;return{risk:n,isAtRisk:g,riskLevel:p,fiedlerValue:0,collapseImminent:n>=.75,weakVertices:i,recommendations:r}}};var cc=[new _t,new Ot,new Nt,new Ft],lc={COHERENCE_CHECK:"qe/coherence/check",COHERENCE_AUDIT:"qe/coherence/audit",COHERENCE_CONSENSUS:"qe/coherence/consensus",COHERENCE_COLLAPSE:"qe/coherence/collapse"};var Lt=(S=>(S.PROBLEM_UNDERSTANDING="H1.1-problem-understanding",S.RULE_OF_THREE="H1.2-rule-of-three",S.PROBLEM_COMPLEXITY="H1.3-problem-complexity",S.USER_NEEDS_IDENTIFICATION="H2.1-user-needs-identification",S.USER_NEEDS_SUITABILITY="H2.2-user-needs-suitability",S.USER_NEEDS_VALIDATION="H2.3-user-needs-validation",S.BUSINESS_NEEDS_IDENTIFICATION="H3.1-business-needs-identification",S.USER_VS_BUSINESS_BALANCE="H3.2-user-vs-business-balance",S.KPI_IMPACT_ANALYSIS="H3.3-kpi-impact-analysis",S.ORACLE_PROBLEM_DETECTION="H4.1-oracle-problem-detection",S.WHAT_MUST_NOT_CHANGE="H4.2-what-must-not-change",S.SUPPORTING_DATA_ANALYSIS="H4.3-supporting-data-analysis",S.GUI_FLOW_IMPACT="H5.1-gui-flow-impact",S.USER_FEELINGS_IMPACT="H5.2-user-feelings-impact",S.CROSS_FUNCTIONAL_IMPACT="H5.3-cross-functional-impact",S.DATA_DEPENDENT_IMPACT="H5.4-data-dependent-impact",S.COMPETITIVE_ANALYSIS="H6.1-competitive-analysis",S.DOMAIN_INSPIRATION="H6.2-domain-inspiration",S.INNOVATIVE_SOLUTIONS="H6.3-innovative-solutions",S.EXACTNESS_AND_CLARITY="H7.1-exactness-and-clarity",S.INTUITIVE_DESIGN="H7.2-intuitive-design",S.COUNTER_INTUITIVE_DESIGN="H7.3-counter-intuitive-design",S.CONSISTENCY_ANALYSIS="H7.4-consistency-analysis",S))(Lt||{});var ar=class{enabledHeuristics;minConfidence;constructor(e={}){this.enabledHeuristics=e.enabledHeuristics||Object.values(Lt),this.minConfidence=e.minConfidence||.7}async applyAll(e,t,n,r){let i=[];for(let s of this.enabledHeuristics){let a=await this.apply(s,e,t,n,r);i.push(a)}return i}async apply(e,t,n,r,i){let s=this.getHeuristicCategory(e),a=[],c=[],l=[],u=75;switch(e){case"H7.4-consistency-analysis":t.domMetrics?.semanticStructure?.hasHeader&&t.domMetrics?.semanticStructure?.hasFooter?(u=85,a.push("Consistent page structure with header and footer")):(u=60,l.push("Add consistent header/footer structure"));break;case"H7.2-intuitive-design":{let d=t.domMetrics?.semanticStructure?.hasNav,m=t.accessibility?.focusableElementsCount||0;d&&m>10?(u=82,a.push("Intuitive navigation and interaction design")):(u=55,c.push({description:"Navigation or interaction patterns unclear",severity:"medium"}));break}case"H7.1-exactness-and-clarity":{u=70;let d=t.domMetrics?.semanticStructure,m=[d?.hasHeader,d?.hasMain,d?.hasNav,d?.hasFooter].filter(Boolean).length;u=50+m*10,m>=3?a.push("Strong visual hierarchy with semantic HTML elements"):m>=2?(a.push("Moderate visual hierarchy - some semantic elements present"),l.push("Add more semantic HTML5 elements for clarity")):(c.push({description:"Weak visual hierarchy - missing semantic structure",severity:"high"}),l.push("Implement semantic HTML5: header, nav, main, footer")),t.metadata?.description&&t.metadata.description.length>20&&(u+=10,a.push("Page has descriptive metadata"));break}case"H7.3-counter-intuitive-design":{u=85;let d=!t.domMetrics?.semanticStructure?.hasNav&&(t.domMetrics?.interactiveElements||0)>10,m=!t.domMetrics?.semanticStructure?.hasHeader&&!t.domMetrics?.semanticStructure?.hasFooter;d&&(u=45,c.push({description:"Navigation structure may be counter-intuitive",severity:"high"}),l.push("Add semantic navigation elements")),m&&(u-=15,c.push({description:"Page structure lacks expected header/footer",severity:"medium"})),u>75&&a.push("No counter-intuitive design patterns detected");break}case"H5.2-user-feelings-impact":{let d=t.accessibility?.altTextsCoverage||0,m=t.performance?.loadTime||0,p=t.accessibility?.ariaLabelsCount||0,g=t.accessibility?.focusableElementsCount||0;u=60,d>=90?(u+=20,a.push("Excellent accessibility (90%+ alt coverage) creates inclusive, positive experience")):d>=70?(u+=12,a.push("Good accessibility creates generally positive user feelings")):d<50&&(u-=15,c.push({description:"Poor accessibility (<50% alt coverage) frustrates users with disabilities",severity:"high"}),l.push("Improve alt text coverage to at least 80% for better accessibility")),p>5&&(u+=8,a.push("Strong ARIA labeling enhances screen reader experience")),m<1500?(u+=15,a.push("Very fast load time (<1.5s) delights users")):m<2500?(u+=8,a.push("Fast load time enhances user satisfaction")):m>4e3?(u-=20,c.push({description:"Very slow load time (>4s) causes significant frustration",severity:"critical"}),l.push("Optimize page load time - target under 2.5 seconds")):m>3e3&&(u-=12,c.push({description:"Slow load time causes user frustration",severity:"high"})),t.errorIndicators?.hasErrorMessages&&(u-=12,c.push({description:"Visible errors reduce user confidence and satisfaction",severity:"high"}),l.push("Review and fix visible error messages")),g>20?(u+=5,a.push("Rich interactive elements provide user control and engagement")):g<5&&(u-=8,c.push({description:"Limited interactivity may feel restrictive",severity:"medium"})),u=Math.max(20,Math.min(100,u));break}case"H5.1-gui-flow-impact":{let d=t.domMetrics?.interactiveElements||0,m=t.domMetrics?.forms||0;d>20&&(u=75,a.push(`${d} interactive elements provide user control`)),m>0&&(a.push(`${m} forms impact user input flows`),u=Math.min(100,u+10)),d===0&&(u=30,c.push({description:"Limited user interaction capability",severity:"high"}));break}case"H5.3-cross-functional-impact":u=70,t.accessibility&&(t.accessibility.altTextsCoverage||0)<100&&a.push("Content team needed for alt text creation"),t.performance&&(t.performance.loadTime||0)>2e3&&a.push("Engineering team needed for performance optimization"),n.complexity==="complex"&&a.push("QA team needed for comprehensive testing"),u=70+a.length*5;break;case"H5.4-data-dependent-impact":t.domMetrics?.forms&&t.domMetrics.forms>0?(u=75,a.push(`${t.domMetrics.forms} forms depend on backend data processing`)):(u=50,a.push("Limited data-dependent features"));break;case"H1.1-problem-understanding":u=n.clarityScore,n.clarityScore>80?a.push("Problem is well-defined"):c.push({description:"Problem clarity needs improvement",severity:"medium"}),a.push(...n.breakdown);break;case"H1.2-rule-of-three":u=n.potentialFailures.length>=3?85:60,a.push(`${n.potentialFailures.length} potential failure modes identified`),n.potentialFailures.length<3&&l.push("Identify at least 3 potential failure modes (Rule of Three)");break;case"H1.3-problem-complexity":u=n.complexity==="simple"?90:n.complexity==="moderate"?75:60,a.push(`Problem complexity: ${n.complexity}`);break;case"H2.1-user-needs-identification":{u=r.alignmentScore,a.push(`${r.needs.length} user needs identified`);let d=r.needs.filter(m=>m.priority==="must-have").length;a.push(`${d} must-have features`),r.challenges.length>0&&c.push({description:`${r.challenges.length} user need challenges found`,severity:"medium"});break}case"H2.2-user-needs-suitability":u=r.suitability==="excellent"?95:r.suitability==="good"?80:r.suitability==="adequate"?65:45,a.push(`User needs suitability: ${r.suitability}`);break;case"H2.3-user-needs-validation":{let d=r.needs.filter(m=>m.addressed).length;u=r.needs.length>0?d/r.needs.length*100:50,a.push(`${d}/${r.needs.length} needs validated and addressed`);break}case"H3.1-business-needs-identification":u=i.alignmentScore,a.push(`Primary goal: ${i.primaryGoal}`),a.push(`${i.kpisAffected.length} KPIs affected`),a.push(`${i.crossTeamImpact.length} cross-team impacts`);break;case"H3.2-user-vs-business-balance":{let d=100-Math.abs(r.alignmentScore-i.alignmentScore);u=d,d>80?a.push("Good balance between user and business needs"):(c.push({description:"Imbalance between user and business priorities",severity:"medium"}),l.push("Align user and business objectives more closely"));break}case"H3.3-kpi-impact-analysis":u=i.impactsKPIs?85:50,a.push(`KPIs impacted: ${i.kpisAffected.join(", ")}`),i.compromisesUX&&(c.push({description:"Business ease compromises user experience",severity:"high"}),u-=20);break;case"H4.1-oracle-problem-detection":u=75,a.push("Oracle problem detection capability active");break;case"H4.2-what-must-not-change":u=80,t.domMetrics?.semanticStructure?.hasMain&&a.push("Main content structure is immutable"),t.accessibility&&(t.accessibility.focusableElementsCount||0)>0&&a.push("Keyboard navigation support must be maintained");break;case"H4.3-supporting-data-analysis":{u=75,(t.domMetrics?.forms||0)>0||(t.domMetrics?.interactiveElements||0)>20?(u=82,a.push("Sufficient data points for informed decision-making")):(u=60,c.push({description:"Limited data for comprehensive analysis",severity:"medium"}),l.push("Collect more user interaction data"));break}case"H6.1-competitive-analysis":u=70,a.push("Competitive analysis capability available"),t.domMetrics?.semanticStructure?.hasNav&&t.domMetrics?.interactiveElements&&t.domMetrics.interactiveElements>15?(u=78,a.push("Navigation and interaction patterns follow industry standards")):l.push("Compare interaction patterns with leading competitors");break;case"H6.2-domain-inspiration":{u=72,t.accessibility&&(t.accessibility.ariaLabelsCount||0)>0?(u=80,a.push("Modern accessibility patterns show domain inspiration")):l.push("Research domain-specific design patterns and best practices");break}case"H6.3-innovative-solutions":{u=65,(t.accessibility?.landmarkRoles||0)>3?(u=75,a.push("Advanced accessibility features show innovative thinking")):l.push("Explore innovative UX patterns to differentiate experience");break}default:s==="user-needs"?u=r.alignmentScore:s==="business-needs"?u=i.alignmentScore:s==="problem"&&(u=n.clarityScore);break}return{id:e,name:this.getHeuristicName(e),category:s,applied:!0,score:Math.min(100,Math.max(0,u)),findings:a,issues:c,recommendations:l}}getHeuristicCategory(e){return e.includes("problem")?"problem":e.includes("user-needs")||e.includes("user-vs")?"user-needs":e.includes("business")?"business-needs":e.includes("oracle")||e.includes("balance")||e.includes("what-must")||e.includes("supporting-data")?"balance":e.includes("impact")||e.includes("gui-flow")||e.includes("feelings")||e.includes("cross-functional")||e.includes("data-dependent")?"impact":e.includes("competitive")||e.includes("inspiration")||e.includes("innovative")?"creativity":"design"}getHeuristicName(e){return{"H1.1-problem-understanding":"Problem Understanding","H1.2-rule-of-three":"Rule of Three","H1.3-problem-complexity":"Problem Complexity","H2.1-user-needs-identification":"User Needs Identification","H2.2-user-needs-suitability":"User Needs Suitability","H2.3-user-needs-validation":"User Needs Validation","H3.1-business-needs-identification":"Business Needs Identification","H3.2-user-vs-business-balance":"User vs Business Balance","H3.3-kpi-impact-analysis":"KPI Impact Analysis","H4.1-oracle-problem-detection":"Oracle Problem Detection","H4.2-what-must-not-change":"What Must Not Change","H4.3-supporting-data-analysis":"Supporting Data Analysis","H5.1-gui-flow-impact":"GUI Flow Impact","H5.2-user-feelings-impact":"User Feelings Impact","H5.3-cross-functional-impact":"Cross-Functional Impact","H5.4-data-dependent-impact":"Data-Dependent Impact","H6.1-competitive-analysis":"Competitive Analysis","H6.2-domain-inspiration":"Domain Inspiration","H6.3-innovative-solutions":"Innovative Solutions","H7.1-exactness-and-clarity":"Exactness & Clarity","H7.2-intuitive-design":"Intuitive Design","H7.3-counter-intuitive-design":"Counter-Intuitive Design","H7.4-consistency-analysis":"Consistency Analysis"}[e]||e}};var or=class{minSeverity;constructor(e="medium"){this.minSeverity=e}detect(e,t,n){let r=[];Math.abs(t.alignmentScore-n.alignmentScore)>20&&r.push({type:"user-vs-business",description:"Significant gap between user needs and business objectives",severity:"high",stakeholders:["Users","Business"],resolutionApproach:["Gather supporting data from both perspectives","Facilitate discussion between stakeholders","Find compromise solutions that address both needs"]}),(t.challenges.length>0||n.compromisesUX)&&r.push({type:"unclear-criteria",description:"Quality criteria unclear due to conflicting information",severity:"medium",missingInfo:t.challenges,resolutionApproach:["Collect missing information from stakeholders","Define clear acceptance criteria"]});let i=(e.title||"").toLowerCase(),s=(e.metadata?.description||"").toLowerCase();return(i.includes("hotel")||i.includes("booking")||i.includes("travel")||i.includes("shop")||i.includes("store")||s.includes("book"))&&(n.kpisAffected.some(a=>a.toLowerCase().includes("conversion")||a.toLowerCase().includes("engagement"))&&r.push({type:"user-vs-business",description:"Potential conflict between conversion optimization (business) and user experience quality (user trust)",severity:"medium",stakeholders:["Marketing","Product","Users"],resolutionApproach:["A/B test aggressive vs. subtle conversion tactics","Measure both conversion rate and user satisfaction metrics","Balance urgency messaging with transparent communication"]}),r.push({type:"unclear-criteria",description:"Unclear criteria for price display timing - when to show fees, taxes, and final price",severity:"medium",stakeholders:["Users","Legal","Business"],resolutionApproach:["Define regulatory compliance requirements for price display","Balance business desire for competitive base pricing vs user need for full price transparency","Establish clear standards for fee disclosure timing"]})),(i.includes("blog")||i.includes("article")||i.includes("news")||i.includes("magazine")||i.includes("testing"))&&r.push({type:"user-vs-business",description:"Content depth (user need) vs. publication frequency (business engagement goals) trade-off",severity:"low",stakeholders:["Readers","Content Team","Editorial"],resolutionApproach:["Define content quality standards and acceptance criteria","Balance editorial calendar with quality thresholds","Consider mix of in-depth and quick-read content formats"]}),(i.includes("health")||i.includes("medical")||i.includes("patient")||i.includes("care")||i.includes("nhs"))&&(r.push({type:"stakeholder-conflict",description:"Healthcare compliance requirements may conflict with streamlined user experience",severity:"medium",stakeholders:["Patients","Healthcare Providers","Compliance","Legal"],resolutionApproach:["Map regulatory requirements to UX touchpoints","Identify where compliance can be achieved without friction","Engage compliance team early in UX design reviews","Document consent and data handling requirements clearly"]}),e.accessibility&&(e.accessibility.altTextsCoverage||0)<80&&r.push({type:"technical-constraint",description:"Healthcare accessibility requirements not fully met - critical for patient inclusivity",severity:"high",stakeholders:["Patients","Accessibility Team","Legal"],resolutionApproach:["Prioritize WCAG 2.1 AA compliance for healthcare content","Ensure screen reader compatibility for medical information","Test with assistive technology users"]})),(i.includes("bank")||i.includes("finance")||i.includes("payment")||i.includes("money"))&&r.push({type:"stakeholder-conflict",description:"Security requirements vs user convenience - authentication friction vs fraud prevention",severity:"high",stakeholders:["Users","Security Team","Product","Compliance"],resolutionApproach:["Implement risk-based authentication to reduce friction for trusted sessions","Use biometrics where available for convenient yet secure access","A/B test authentication flows for security effectiveness and user completion rates"]}),((e.domMetrics?.totalElements||0)>500||(e.domMetrics?.interactiveElements||0)>50)&&r.push({type:"technical-constraint",description:"Platform technical limitations may restrict advanced UX features or accessibility enhancements",severity:"low",stakeholders:["Development","Product","Users"],resolutionApproach:["Evaluate platform capabilities and constraints","Prioritize features based on user impact vs. implementation complexity","Consider gradual enhancement approach"]}),e.performance&&(e.performance.loadTime||0)>3e3&&r.push({type:"technical-constraint",description:"Performance optimization needed but may require trade-offs with visual richness",severity:"medium",stakeholders:["Users","Development","Design"],resolutionApproach:["Profile and identify performance bottlenecks","Consider progressive loading for visual elements","Balance image quality with load time"]}),r.filter(a=>this.meetsMinimumSeverity(a.severity))}meetsMinimumSeverity(e){let t=["low","medium","high","critical"],n=t.indexOf(this.minSeverity);return t.indexOf(e)>=n}};var cr=class o{static LOAD_TIME_FEELINGS=[[4001,1/0,"Impatient - Very slow load time causes significant frustration"],[3001,4e3,"Impatient - Slow load time causes frustration"],[2001,3e3,"Mildly Annoyed - Noticeable load time"],[0,1499,"Delighted - Fast load time enhances experience"],[1500,1999,"Satisfied - Good load time meets expectations"]];static DOMAIN_REQUIREMENTS=[[["health","medical","care"],["Must comply with healthcare accessibility standards","Must protect patient data privacy"]],[["bank","finance","payment"],["Must maintain PCI DSS compliance for payment data","Must support secure authentication flows"]]];static VISIBLE_SCORE_ADJUSTMENTS=[[["Positive","Satisfied","Delighted"],20],[["Oriented"],10],[["Frustrated","Confused","Impatient"],-15],[["Disoriented"],-10]];analyze(e,t){let n=this.analyzeEndUserFlow(e),r=this.analyzeInternalFlow(e),i=this.analyzeUserFeelings(e),s=this.analyzePerformance(e),a=this.analyzeSecurity(e),c=this.analyzeImmutableRequirements(e,t),l=this.calculateVisibleScore(n,i),u=this.calculateInvisibleScore(s,a),d=Math.round((l+u)/2);return{visible:{guiFlow:{forEndUser:n,forInternalUser:r},userFeelings:i,score:l},invisible:{performance:s,security:a,score:u},immutableRequirements:c,overallImpactScore:d}}analyzeEndUserFlow(e){let t=[],n=e.domMetrics?.interactiveElements||0,r=e.domMetrics?.forms||0;return n>0&&t.push(`${n} interactive elements affect user journey`),r>0&&t.push(`${r} forms impact user input flows`),e.domMetrics?.semanticStructure?.hasNav&&t.push("Navigation structure enables exploration flow"),e.domMetrics?.semanticStructure?.hasMain&&t.push("Clear main content area guides user focus"),t}analyzeInternalFlow(e){let t=[];return(e.domMetrics?.forms||0)>0&&t.push("Form submissions create data processing workflows"),e.domMetrics?.semanticStructure?.hasAside&&t.push("Sidebar content may require separate management"),t}analyzeUserFeelings(e){let t=[],n=e.accessibility?.altTextsCoverage||0;n>80?t.push("Positive - Good accessibility creates inclusive experience"):n>=50?t.push("Neutral - Moderate accessibility; some users may struggle"):n<50&&t.push("Frustrated - Poor accessibility excludes some users");let r=e.performance?.loadTime||0;for(let[i,s,a]of o.LOAD_TIME_FEELINGS)if(r>=i&&r<=s){t.push(a);break}return e.errorIndicators?.hasErrorMessages&&t.push("Confused - Visible errors reduce confidence"),this.analyzeStructureFeelings(e,t),t}analyzeStructureFeelings(e,t){let n=e.domMetrics?.semanticStructure;if(!n)return;let r=[n.hasHeader,n.hasNav,n.hasMain,n.hasFooter].filter(Boolean).length;r>=3?t.push("Oriented - Clear page structure helps navigation"):r<2&&t.push("Disoriented - Unclear page structure may confuse users")}analyzePerformance(e){let t=[],n=e.performance?.loadTime||0;return n>2e3&&t.push(`Load time ${n}ms impacts user retention`),e.metadata?.viewport||t.push("Missing viewport tag affects mobile performance"),e.performance?.firstContentfulPaint&&e.performance.firstContentfulPaint>2500&&t.push(`First Contentful Paint ${e.performance.firstContentfulPaint}ms delays perceived readiness`),t}analyzeSecurity(e){let t=[];return(e.domMetrics?.forms||0)>0&&t.push("Form data handling requires secure transmission"),e.accessibility&&(e.accessibility.ariaLabelsCount||0)>0&&t.push("ARIA labels may expose internal element names - review for sensitive info"),t}analyzeImmutableRequirements(e,t){let n=[];e.domMetrics?.semanticStructure?.hasMain&&n.push("Must maintain main content accessibility"),e.accessibility&&(e.accessibility.focusableElementsCount||0)>0&&n.push("Must support keyboard navigation"),t.complexity==="complex"&&n.push("Must maintain system stability with complex interactions");let r=(e.title||"").toLowerCase();for(let[i,s]of o.DOMAIN_REQUIREMENTS)i.some(a=>r.includes(a))&&n.push(...s);return n}calculateVisibleScore(e,t){let n=50;e.length>0&&(n+=15);for(let[r,i]of o.VISIBLE_SCORE_ADJUSTMENTS)t.some(s=>r.some(a=>s.includes(a)))&&(n+=i);return Math.max(0,Math.min(100,n))}calculateInvisibleScore(e,t){let n=50;return e.length===0&&(n+=20),t.length===0&&(n+=10),e.length>2&&(n-=15),Math.max(0,Math.min(100,n))}};k();var jm={type:"object",properties:{target:{type:"string",description:"Target URL or identifier to analyze"},context:{type:"object",description:"Pre-collected QX context (optional)"},mode:{type:"string",description:"Analysis mode: full, quick, or targeted",enum:["full","quick","targeted"],default:"full"},heuristics:{type:"array",description:"Specific heuristics to apply (default: all)"},minOracleSeverity:{type:"string",description:"Minimum oracle problem severity to report",enum:["low","medium","high","critical"],default:"medium"},includeCreativity:{type:"boolean",description:"Include creativity analysis from diverse domains",default:!0},includeDesign:{type:"boolean",description:"Include design quality analysis",default:!0}},required:["target"]},qt=class extends A{config={name:"qe/qx/analyze",description:"Comprehensive Quality Experience (QX) analysis combining QA and UX perspectives. Applies 23+ programmatic heuristics, detects oracle problems, and analyzes impacts. QX = Marriage between QA (Quality Advocacy) and UX (User Experience).",domain:"quality-assessment",schema:jm,streaming:!0,timeout:18e4};async execute(e,t){let{target:n,context:r=this.createMinimalContext(n),mode:i="full",heuristics:s,minOracleSeverity:a="medium",includeCreativity:c=!0,includeDesign:l=!0}=e;try{this.emitStream(t,{status:"starting",message:`Starting QX analysis for: ${n}`,phase:"initialization"}),this.emitStream(t,{status:"analyzing",phase:"problem-analysis"});let u=this.analyzeProblem(r);if(this.isAborted(t))return{success:!1,error:"Operation aborted"};this.emitStream(t,{status:"analyzing",phase:"user-needs"});let d=this.analyzeUserNeeds(r,u);this.emitStream(t,{status:"analyzing",phase:"business-needs"});let m=this.analyzeBusinessNeeds(r,u);this.emitStream(t,{status:"analyzing",phase:"creativity"});let p=c?this.analyzeCreativity(r,u):this.createMinimalCreativityAnalysis();this.emitStream(t,{status:"analyzing",phase:"design"});let g=l?this.analyzeDesign(r):this.createMinimalDesignAnalysis();this.emitStream(t,{status:"analyzing",phase:"oracle-detection"});let h=new or(a).detect(r,d,m);this.emitStream(t,{status:"analyzing",phase:"impact-analysis"});let y=new cr().analyze(r,u);this.emitStream(t,{status:"analyzing",phase:"heuristics",count:23});let b=await new ar({enabledHeuristics:s||Object.values(Lt)}).applyAll(r,u,d,m);this.emitStream(t,{status:"analyzing",phase:"recommendations"});let w=this.generateRecommendations(u,d,m,h,y,b),T=this.calculateOverallScore(u,d,m,p,g,y,b),S=this.scoreToGrade(T),x={overallScore:T,grade:S,timestamp:new Date().toISOString(),target:n,problemAnalysis:u,userNeeds:d,businessNeeds:m,creativityAnalysis:p,designAnalysis:g,oracleProblems:h,impactAnalysis:y,heuristics:b,recommendations:w,context:r};return this.emitStream(t,{status:"complete",score:T,grade:S,heuristicsApplied:b.length,oracleProblemsFound:h.length}),{success:!0,data:x,metadata:this.createMetadata(t.startTime,t.requestId)}}catch(u){return{success:!1,error:`QX analysis failed: ${E(u)}`}}}analyzeProblem(e){let t=e.title||"Untitled page",n=e.metadata?.description||"",r=e.errorIndicators?.hasErrorMessages||!1,i=`Evaluate quality experience of "${t}"`;n&&(i+=` - ${n.substring(0,100)}`);let s=e.domMetrics?.totalElements||0,a=e.domMetrics?.interactiveElements||0,c=e.domMetrics?.forms||0,l;s>500||a>50||c>3?l="complex":s>200||a>20||c>1?l="moderate":l="simple";let u=[];e.domMetrics?.semanticStructure?.hasNav&&u.push("Navigation structure"),c>0&&u.push(`Form interactions (${c} forms)`),a>0&&u.push(`User interactions (${a} elements)`),e.accessibility&&u.push("Accessibility compliance"),e.performance&&u.push("Performance metrics");let d=[],m=t.toLowerCase();for((m.includes("health")||m.includes("care")||m.includes("nhs"))&&(d.push({description:"Healthcare information may not be accessible to users with visual impairments",severity:"high",likelihood:"likely"}),d.push({description:"Patient journey complexity may cause confusion during registration or booking",severity:"medium",likelihood:"possible"}),d.push({description:"Emergency contact information may not be prominently visible",severity:"high",likelihood:"possible"})),e.domMetrics?.semanticStructure?.hasMain||d.push({description:"Missing main content landmark - users may struggle to find primary content",severity:"medium",likelihood:"likely"}),e.accessibility&&(e.accessibility.altTextsCoverage||0)<80&&d.push({description:"Poor image alt text coverage - screen reader users affected",severity:"high",likelihood:"very-likely"}),r&&d.push({description:"Visible error messages detected - potential usability issues",severity:"medium",likelihood:"likely"}),e.performance&&(e.performance.loadTime||0)>3e3&&d.push({description:"Slow load time - user frustration and abandonment risk",severity:"high",likelihood:"very-likely"});d.length<3;)l==="complex"?d.push({description:"Complex interaction flows may confuse first-time users",severity:"medium",likelihood:"possible"}):l==="moderate"?d.push({description:"Multiple interactive elements increase cognitive load",severity:"low",likelihood:"possible"}):d.push({description:"Limited interactivity may not meet user expectations",severity:"low",likelihood:"possible"});let p=50;return t&&t!=="Untitled page"&&(p+=15),n&&(p+=15),u.length>=3&&(p+=10),e.domMetrics?.semanticStructure?.hasMain&&(p+=10),p=Math.min(100,p),{problemStatement:i,complexity:l,breakdown:u,potentialFailures:d.slice(0,5),clarityScore:p}}analyzeUserNeeds(e,t){let n=[],r=[],i=e.domMetrics?.semanticStructure,s=e.accessibility,a=e.domMetrics?.interactiveElements||0,c=e.domMetrics?.forms||0;i?.hasNav?n.push({description:"Clear navigation to find content",priority:"must-have",addressed:!0}):(r.push("Missing navigation structure - users cannot easily explore site"),n.push({description:"Clear navigation to find content",priority:"must-have",addressed:!1})),a>0&&n.push({description:"Interactive elements for engagement",priority:"must-have",addressed:!0}),s&&(s.focusableElementsCount||0)>0?n.push({description:"Keyboard navigation support",priority:"must-have",addressed:!0}):(r.push("Limited keyboard navigation - inaccessible to some users"),n.push({description:"Keyboard navigation support",priority:"must-have",addressed:!1})),i?.hasHeader&&n.push({description:"Consistent page header for orientation",priority:"should-have",addressed:!0}),i?.hasFooter&&n.push({description:"Footer with supporting information",priority:"should-have",addressed:!0}),s&&(s.altTextsCoverage||0)>50?n.push({description:"Image descriptions for screen readers",priority:"should-have",addressed:!0}):s&&(s.altTextsCoverage||0)<50&&(r.push("Poor alt text coverage - images not accessible"),n.push({description:"Image descriptions for screen readers",priority:"should-have",addressed:!1})),e.performance&&(e.performance.loadTime||0)<3e3?n.push({description:"Fast page load time",priority:"should-have",addressed:!0}):e.performance&&(e.performance.loadTime||0)>=3e3&&(r.push("Slow load time - user frustration risk"),n.push({description:"Fast page load time",priority:"should-have",addressed:!1})),i?.hasAside&&n.push({description:"Supplementary content sections",priority:"nice-to-have",addressed:!0}),s&&(s.landmarkRoles||0)>3&&n.push({description:"Rich ARIA landmarks for navigation",priority:"nice-to-have",addressed:!0}),c>0&&n.push({description:"Form interactions for user input",priority:"nice-to-have",addressed:!0});let l=n.filter(m=>m.priority==="must-have"&&m.addressed).length,u;r.length===0&&l>=3?u="excellent":r.length<=1&&l>=2?u="good":r.length<=2&&l>=2?u="adequate":u="poor";let d=40;return d+=l*10,d+=n.filter(m=>m.priority==="should-have"&&m.addressed).length*5,d+=n.filter(m=>m.priority==="nice-to-have"&&m.addressed).length*2,d-=r.length*8,d=Math.max(0,Math.min(100,d)),{needs:n,suitability:u,challenges:r,alignmentScore:d}}analyzeBusinessNeeds(e,t){let n=e.domMetrics?.forms||0,r=e.domMetrics?.interactiveElements||0,i=e.performance,s=e.errorIndicators?.hasErrorMessages||!1,a,c=[];n>2?(a="business-ease",c=["Form completion rate","Lead generation","User sign-ups"]):r>30?(a="user-experience",c=["Time on site","Click-through rate","User engagement"]):(a="balanced",c=["Content consumption","Bounce rate","Page views"]);let l=(e.title||"").toLowerCase();(l.includes("health")||l.includes("care"))&&c.push("Patient satisfaction","Appointment completion rate","Information accessibility");let u=[];n>0&&(u.push({team:"Marketing",impactType:"positive",description:"Form conversion optimization needed"}),u.push({team:"Development",impactType:"neutral",description:"Form validation and submission handling"})),e.accessibility&&(e.accessibility.altTextsCoverage||0)<100&&u.push({team:"Content",impactType:"negative",description:"Image alt text creation required"}),i&&(i.loadTime||0)>2e3&&u.push({team:"Engineering",impactType:"negative",description:"Performance optimization needed"}),t.complexity==="complex"&&u.push({team:"QA",impactType:"neutral",description:"Comprehensive testing strategy required"});let d=!1;s&&(d=!0),e.accessibility&&(e.accessibility.altTextsCoverage||0)<50&&(d=!0),i&&(i.loadTime||0)>4e3&&(d=!0);let m=50;return c.length>0&&(m+=15),u.length>0&&(m+=10),d||(m+=20),m=Math.min(100,m),{primaryGoal:a,kpisAffected:c,crossTeamImpact:u,compromisesUX:d,impactsKPIs:c.length>0,alignmentScore:m}}analyzeCreativity(e,t){let n=[];(t.complexity==="complex"||t.complexity==="moderate")&&(n.push({description:"Question fundamental assumptions about user mental models and expected workflows",inspirationSource:"philosophy",applicability:"high",novelty:"moderately-novel"}),e.errorIndicators?.hasErrorMessages&&n.push({description:"Apply diagnostic testing - systematically isolate error sources through controlled scenarios",inspirationSource:"medicine",applicability:"high",novelty:"moderately-novel"})),e.domMetrics?.forms&&e.domMetrics.forms>0&&n.push({description:"Test checkout/form flows like fashion retail - focus on friction points, abandonment triggers",inspirationSource:"e-commerce",applicability:"high",novelty:"incremental"}),n.push({description:"Analyze through diverse demographic lenses (age, gender, culture, ability) for inclusive testing",inspirationSource:"social science",applicability:"high",novelty:"moderately-novel"}),e.domMetrics?.interactiveElements&&e.domMetrics.interactiveElements>20&&n.push({description:'Test for "game-breaking" exploits - unexpected interaction sequences, boundary conditions',inspirationSource:"gaming",applicability:"medium",novelty:"highly-novel"});let r=[...new Set(n.map(a=>a.inspirationSource))],i=["Unexperienced user perspective (fresh eyes)","Power user perspective (efficiency focus)","Accessibility perspective (assistive tech users)","International perspective (cultural differences)"],s=50;return s+=n.length*8,s+=r.length*5,s=Math.min(100,s),{innovativeApproaches:n,domainsExplored:r,perspectives:i,creativityScore:s,notes:["Creativity draws from diverse domains to uncover unconventional testing approaches","Higher complexity problems benefit from cross-disciplinary inspiration",`Applied ${n.length} creative approaches from ${r.length} domains`]}}analyzeDesign(e){let t=[],n=[];e.domMetrics?.semanticStructure?.hasNav&&t.push("Navigation structure clearly defined with semantic <nav> element"),e.domMetrics?.semanticStructure?.hasMain&&t.push("Main content area clearly identified"),e.domMetrics?.semanticStructure?.hasHeader&&e.domMetrics?.semanticStructure?.hasFooter&&t.push("Header and footer provide clear page structure");let r=e.accessibility?.ariaLabelsCount||0,i=e.domMetrics?.interactiveElements||0;i>0&&r<i*.5&&n.push("Many interactive elements lack ARIA labels for clarity");let s=50+t.length*15-n.length*10;s=Math.max(0,Math.min(100,s));let a=s>=80?"excellent":s>=60?"good":s>=40?"adequate":"poor",c=[],l=[],u=!0;e.domMetrics?.semanticStructure?.hasNav&&c.push("Standard navigation placement"),e.domMetrics?.semanticStructure?.hasHeader&&c.push("Header follows common layout conventions"),!e.domMetrics?.semanticStructure?.hasNav&&i>10&&(u=!1,l.push("Non-standard navigation pattern may confuse users from different regions"));let d=50+c.length*15;u||(d-=20),d=Math.max(0,Math.min(100,d));let m=Math.round((s+d)/2);return{exactness:{clarity:a,clearElements:t,unclearElements:n,score:s},intuitive:{followsConventions:u,intuitivePatterns:c,culturalIssues:l,score:d},counterIntuitive:{deviations:[],innovativeJustification:!1,freshEyesPerspective:!0,issuesCount:0},overallDesignScore:m}}generateRecommendations(e,t,n,r,i,s){let a=[],c=1;for(let l of s){for(let u of l.issues)(u.severity==="critical"||u.severity==="high")&&a.push({principle:l.name,recommendation:u.description,severity:u.severity,impact:u.severity==="critical"?90:75,effort:"medium",priority:c++,category:"qx"});for(let u of l.recommendations)a.push({principle:l.name,recommendation:u,severity:"medium",impact:60,effort:"medium",priority:c++,category:"qx"})}for(let l of r)a.push({principle:`Oracle: ${l.type}`,recommendation:l.description,severity:l.severity,impact:l.severity==="critical"?95:l.severity==="high"?80:60,effort:"high",priority:c++,category:"process",evidence:l.resolutionApproach});for(let l of t.challenges)a.push({principle:"User Needs",recommendation:l,severity:"medium",impact:65,effort:"medium",priority:c++,category:"ux"});return a.sort((l,u)=>{let d={critical:0,high:1,medium:2,low:3},m=d[l.severity]-d[u.severity];return m!==0?m:u.impact-l.impact}).slice(0,15)}calculateOverallScore(e,t,n,r,i,s,a){let c=a.reduce((u,d)=>u+d.score,0)/a.length||0,l=e.clarityScore*.1+t.alignmentScore*.2+n.alignmentScore*.15+r.creativityScore*.1+i.overallDesignScore*.15+(100-s.overallImpactScore)*.1+c*.2;return Math.round(Math.max(0,Math.min(100,l)))}scoreToGrade(e){return e>=90?"A":e>=80?"B":e>=70?"C":e>=60?"D":"F"}createMinimalContext(e){return{url:e,title:e}}createMinimalCreativityAnalysis(){return{innovativeApproaches:[],domainsExplored:[],perspectives:[],creativityScore:50,notes:["Creativity analysis skipped"]}}createMinimalDesignAnalysis(){return{exactness:{clarity:"adequate",clearElements:[],unclearElements:[],score:50},intuitive:{followsConventions:!0,intuitivePatterns:[],culturalIssues:[],score:50},counterIntuitive:{deviations:[],innovativeJustification:!1,freshEyesPerspective:!1,issuesCount:0},overallDesignScore:50}}emitStream(e,t){e.streaming&&e.onStream&&e.onStream(t)}isAborted(e){return e.abortSignal?.aborted||!1}createMetadata(e,t){return{executionTime:Date.now()-e,timestamp:new Date().toISOString(),requestId:t}}},bk=new qt;var Vk={TEST_GENERATE:"qe/tests/generate",TEST_EXECUTE:"qe/tests/execute",COVERAGE_ANALYZE:"qe/coverage/analyze",COVERAGE_GAPS:"qe/coverage/gaps",QUALITY_EVALUATE:"qe/quality/evaluate",QUALITY_GATE:"qe/quality/gate",DEFECT_PREDICT:"qe/defects/predict",REQUIREMENTS_VALIDATE:"qe/requirements/validate",QUALITY_CRITERIA:"qe/requirements/quality-criteria",CODE_ANALYZE:"qe/code/analyze",CODE_C4:"qe/code/c4",SECURITY_SCAN:"qe/security/scan",CONTRACT_VALIDATE:"qe/contracts/validate",VISUAL_COMPARE:"qe/visual/compare",A11Y_AUDIT:"qe/a11y/audit",CHAOS_INJECT:"qe/chaos/inject",LEARNING_OPTIMIZE:"qe/learning/optimize",LEARNING_DREAM:"qe/learning/dream",TOKEN_USAGE:"qe/analysis/token_usage",GOAP_PLAN:"qe/planning/goap_plan",GOAP_EXECUTE:"qe/planning/goap_execute",GOAP_STATUS:"qe/planning/goap_status",...It,EMBEDDING_GENERATE:"qe/embeddings/generate",EMBEDDING_COMPARE:"qe/embeddings/compare",EMBEDDING_SEARCH:"qe/embeddings/search",EMBEDDING_STORE:"qe/embeddings/store",EMBEDDING_STATS:"qe/embeddings/stats",...lc,QX_ANALYZE:"qe/qx/analyze",TEST_SCHEDULE:"qe/tests/schedule",LOAD_TEST:"qe/tests/load",URL_VALIDATE:"qe/security/url-validate",BROWSER_WORKFLOW:"qe/workflows/browser-load"},zm=[new On,new Nn,new Ln,new qn,new $n,new Gn,new zn,new Un,new Et,new Hn,new Vn,new Qn,new Wn,new Kn,new Xn,new Yn,new wt,new Rt,new Jn,new At,new kt,new Mt,...oc,new nt,new rt,new it,new st,new at,...cc,new qt,new ma,new pa,new ga,new fa];function uc(){for(let o of zm)o.resetInstanceCache()}k();var Um=mr.filter(o=>o!=="coordination"),R={fleetId:null,kernel:null,queen:null,router:null,workflowOrchestrator:null,initialized:!1,initTime:null,topology:"hierarchical",agentLevels:new Map};function Ct(){return R}function Qe(){return R.initialized&&R.kernel!==null&&R.queen!==null}function oM(o){return Qe()||(R.fleetId=`fleet-${G().slice(0,8)}`,R.kernel=o.kernel,R.queen=o.queen,R.router=o.router??null,R.workflowOrchestrator=o.workflowOrchestrator??null,R.initialized=!0,R.initTime=new Date,R.topology=o.topology??"hierarchical",R.agentLevels.clear()),R.fleetId}function cM(){return R.topology}function lM(o,e){if(R.topology!=="hierarchical"){let i={agentId:o,domain:e,level:"worker",spawnedAt:new Date};return R.agentLevels.set(o,i),"worker"}let n=Array.from(R.agentLevels.values()).find(i=>i.domain===e&&i.level==="lead")?"worker":"lead",r={agentId:o,domain:e,level:n,spawnedAt:new Date};return R.agentLevels.set(o,r),n}function uM(o){return R.agentLevels.get(o)}function dM(){return R.agentLevels}async function mM(o){try{if(R.initialized&&R.kernel&&R.queen){let l=R.kernel.getConfig();return{success:!0,data:{fleetId:R.fleetId,topology:R.topology,maxAgents:l.maxConcurrentAgents,enabledDomains:l.enabledDomains.filter(u=>u!=="coordination"),status:"ready"}}}R.fleetId=`fleet-${G().slice(0,8)}`;let e=o.enabledDomains||[...mr],t=e.filter(l=>l!=="coordination"),n=process.env.AQE_MEMORY_BACKEND==="memory"?"memory":o.memoryBackend||"hybrid";R.kernel=new Hs({maxConcurrentAgents:o.maxAgents||15,memoryBackend:n,hnswEnabled:!0,lazyLoading:o.lazyLoading!==!1,enabledDomains:e}),await R.kernel.initialize(),R.router=new Qs(R.kernel.eventBus),await R.router.initialize();let r=l=>R.kernel.getDomainAPI(l),i=new ha(R.kernel.eventBus,R.kernel.memory,r),s=R.kernel.plugins;await s.loadAll();let a=new Map;for(let l of s.getLoaded()){let u=s.getPlugin(l);u&&a.set(l,u)}try{let{getDaemon:l}=await import("./daemon-JER6HE2J.js"),u=l().getWorkerManager();u.setKernel(R.kernel),u.setMemory(R.kernel.memory)}catch(l){console.warn(`[fleet_init] Daemon worker manager wiring skipped: ${E(l)}`)}R.queen=Vs(R.kernel,R.router,i,void 0,a),await R.queen.initialize(),R.workflowOrchestrator=new Bs(R.kernel.eventBus,R.kernel.memory,R.kernel.coordinator),await R.workflowOrchestrator.initialize(),Bm(R.kernel,R.workflowOrchestrator);let{subscribeTrajectoryEvents:c}=await import("./task-handlers-FH6DNTHW.js");return c(R.router),R.initialized=!0,R.initTime=new Date,R.topology=o.topology||"hierarchical",R.agentLevels.clear(),{success:!0,data:{fleetId:R.fleetId,topology:R.topology,maxAgents:o.maxAgents||15,enabledDomains:t,status:"initialized"}}}catch(e){return{success:!1,error:`Failed to initialize fleet: ${E(e)}`}}}async function pM(o){if(!Qe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{let e=R.queen.getHealth(),t=R.queen.getMetrics(),n={status:e.status,uptime:t.uptime,agents:{total:e.totalAgents,active:e.activeAgents,idle:e.totalAgents-e.activeAgents},tasks:{pending:e.pendingTasks,running:e.runningTasks,completed:t.tasksCompleted,failed:t.tasksFailed}};if(o.includeDomains){let i=[];for(let[s,a]of e.domainHealth)i.push({domain:s,status:a.status,agents:a.agents.total,load:R.queen.getDomainLoad(s)});n.domains=i}let r=R.queen.getDomainTeamManager?.();if(r){let i=r.listDomainTeams(),s=0,a=0;for(let c of i)s+=1+c.teammateIds.length,r.getTeamHealth(c.domain)?.healthy&&a++;n.teams={active:i.length,totalAgentsInTeams:s,healthyCount:a}}o.includeMetrics&&(n.metrics={tasksReceived:t.tasksReceived,tasksCompleted:t.tasksCompleted,tasksFailed:t.tasksFailed,agentUtilization:t.agentUtilization,averageTaskDuration:t.averageTaskDuration});try{let{getUnifiedMemory:i}=await import("./unified-memory-RQ3Q4CU3.js"),s=i();if(s.isInitialized()){let a=l=>{try{return s.queryCount(l)}catch{return 0}},c=await s.vectorCount();n.learning={totalPatterns:a("qe_patterns"),totalExperiences:a("captured_experiences"),totalTrajectories:a("qe_trajectories"),vectorCount:c,experienceApplications:a("experience_applications"),dreamCycles:a("dream_cycles"),embeddingDimension:384}}}catch{}return{success:!0,data:n}}catch(e){return{success:!1,error:`Failed to get fleet status: ${E(e)}`}}}async function gM(o){if(!Qe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{if(o.domain){let n=R.queen.getDomainHealth(o.domain);return n?{success:!0,data:{domain:o.domain,status:n.status,agents:n.agents,errors:n.errors,lastActivity:n.lastActivity?.toISOString()}}:{success:!1,error:`Domain not found: ${o.domain}`}}let e=R.queen.getHealth(),t={status:e.status,totalAgents:e.totalAgents,activeAgents:e.activeAgents,pendingTasks:e.pendingTasks,runningTasks:e.runningTasks,workStealingActive:e.workStealingActive,lastHealthCheck:e.lastHealthCheck.toISOString()};if(o.detailed){let n={};for(let[r,i]of e.domainHealth)n[r]={status:i.status,agents:i.agents,errors:i.errors.length,lastActivity:i.lastActivity?.toISOString()};t.domains=n,t.issues=e.issues.map(r=>({severity:r.severity,message:r.message,domain:r.domain,timestamp:r.timestamp.toISOString()}))}try{let{StructuralHealthMonitor:n}=await import("./structural-health-3LPG6MQN.js"),r=new n,i=[];for(let[c]of e.domainHealth){let l=R.queen.getAgentsByDomain(c);for(let u of l)i.push({id:u.id,name:u.name,domain:u.domain})}let s=i.map(c=>({id:c.id,name:c.name,domain:c.domain,capabilities:[c.domain],dependsOn:[],weight:1})),a=r.computeFleetHealth(s);t.structuralHealth={lambda:a.lambda,healthy:a.healthy,normalizedLambda:a.normalizedLambda,riskScore:a.riskScore,status:a.status,weakPoints:a.weakPoints,suggestions:a.suggestions}}catch{}return{success:!0,data:t}}catch(e){return{success:!1,error:`Failed to get fleet health: ${E(e)}`}}}async function fM(){if(Ja(),Io(),uc(),R.workflowOrchestrator&&(await R.workflowOrchestrator.dispose(),R.workflowOrchestrator=null),R.queen&&(await R.queen.dispose(),R.queen=null),R.router){try{let{unsubscribeTrajectoryEvents:o}=await import("./task-handlers-FH6DNTHW.js");o(R.router)}catch{}await R.router.dispose(),R.router=null}R.kernel&&(await R.kernel.dispose(),R.kernel=null),R.initialized=!1,R.fleetId=null,R.initTime=null,R.topology="hierarchical",R.agentLevels.clear()}async function hM(){let o=performance.now();try{let e=Qe(),t=R.initTime?Date.now()-R.initTime.getTime():0,n={connected:!1,totalEntries:0,namespaces:0},r={enabled:!1,vectorCount:0},i=0;if(e&&R.kernel){let u=R.kernel.memory;try{n.connected=!0;let d=await u.count("default"),m=await u.count("learning"),p=await u.count("patterns");n.totalEntries=d+m+p;let g=0;for(let f of["default","learning","patterns","mcp-tools","coordination"])await u.count(f)>0&&g++;n.namespaces=g}catch{}try{let d=process.env.AQE_V3_HNSW_ENABLED==="true";r.enabled=d;let m=u;d&&typeof m.vectorCount=="function"&&(r.vectorCount=await m.vectorCount())}catch{}try{i=(await u.search("pattern:*",1e3)).length}catch{}}let s=e&&R.kernel?(R.kernel.getLoadedDomains?.()??Um).length:0,a=null;try{let{getSharedRvfDualWriterSync:u}=await import("./shared-rvf-dual-writer-WML274E7.js"),d=u();if(d){let m=d.status(),p=d.getDivergenceReport();a={mode:m.mode,vectorCount:m.rvf?.totalVectors??0,divergences:p.divergences,promotionSafe:d.isPromotionSafe()}}}catch{}let c=null;try{let{SQLitePatternStore:u}=await import("./sqlite-persistence-N5T7DWMR.js"),d=new u;await d.initialize(),c=d.getGhostPatternCount(),d.close()}catch{}return{success:!0,data:{status:e?"healthy":"unhealthy",version:"3.15.8",loadedDomains:s,memory:n,hnsw:r,rvf:a??void 0,ghostPatterns:c??void 0,loadedPatterns:i,uptimeMs:t,timestamp:new Date().toISOString()},metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:G(),toolName:"aqe_health"}}}catch(e){return{success:!1,error:E(e),metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:G(),toolName:"aqe_health"}}}}function Bm(o,e){let t=o.getDomainAPI("requirements-validation");t?.registerWorkflowActions&&(t.registerWorkflowActions(e),console.log("[Fleet] Registered requirements-validation workflow actions (includes QCSD Ideation)"));let n=o.getDomainAPI("visual-accessibility");n?.registerWorkflowActions&&(n.registerWorkflowActions(e),console.log("[Fleet] Registered visual-accessibility workflow actions"))}export{Fp as a,Tn as b,Ct as c,Qe as d,oM as e,cM as f,lM as g,uM as h,dM as i,mM as j,pM as k,gM as l,fM as m,hM as n};