agentic-qe 3.11.1 → 3.11.2

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 (334) hide show
  1. package/.claude/skills/qe-code-intelligence/SKILL.md +3 -0
  2. package/.claude/skills/skills-manifest.json +1 -1
  3. package/CHANGELOG.md +35 -0
  4. package/README.md +1 -0
  5. package/assets/skills/qe-code-intelligence/SKILL.md +3 -0
  6. package/dist/cli/bundle.js +5 -5
  7. package/dist/cli/chunks/adapter-LDNYC4GH.js +2 -0
  8. package/dist/cli/chunks/{agent-booster-wasm-3OJAT664.js → agent-booster-wasm-FNCVODUJ.js} +2 -2
  9. package/dist/cli/chunks/{agent-handler-6TCTI5AT.js → agent-handler-JK7VK37B.js} +2 -2
  10. package/dist/cli/chunks/{agent-memory-branch-FAWCYEGJ.js → agent-memory-branch-EPVVJNNA.js} +2 -2
  11. package/dist/cli/chunks/aqe-learning-engine-CA4CT5Q7.js +2 -0
  12. package/dist/cli/chunks/{arena-O2TCUQBF.js → arena-EH2IMSRW.js} +4 -4
  13. package/dist/cli/chunks/{arena-UVYIGYUF.js → arena-NTHVDZTJ.js} +2 -2
  14. package/dist/cli/chunks/{audit-AYESKHAJ.js → audit-ODZV2T2B.js} +2 -2
  15. package/dist/cli/chunks/base-TSDAEMT4.js +2 -0
  16. package/dist/cli/chunks/{hnswlib-node-FUWQTM2D.js → better-sqlite3-5JTP47LA.js} +2 -2
  17. package/dist/cli/chunks/{brain-handler-KSJBVTHZ.js → brain-handler-NVB6OJ25.js} +3 -3
  18. package/dist/cli/chunks/{branch-enumerator-4O3S42EG.js → branch-enumerator-BIXSELMY.js} +2 -2
  19. package/dist/cli/chunks/{browser-5VXK323P.js → browser-S2Y2W33Z.js} +2 -2
  20. package/dist/cli/chunks/browser-workflow-3HCTJBLR.js +2 -0
  21. package/dist/cli/chunks/{chunk-XEVUW4QL.js → chunk-26ZMIYSK.js} +2 -2
  22. package/dist/cli/chunks/{chunk-7GP7ZG3K.js → chunk-27KNLVOY.js} +2 -2
  23. package/dist/cli/chunks/{chunk-5Y7GXQOM.js → chunk-2Q65LTJN.js} +2 -2
  24. package/dist/cli/chunks/{chunk-QOR4YAZY.js → chunk-3ATEYGVD.js} +2 -2
  25. package/dist/cli/chunks/{chunk-NVJIOCS5.js → chunk-3J3QXLWP.js} +2 -2
  26. package/dist/cli/chunks/{chunk-OUBYADPD.js → chunk-3KTOM7NN.js} +2 -2
  27. package/dist/cli/chunks/{chunk-EZBXCEBV.js → chunk-3NCVUFAL.js} +2 -2
  28. package/dist/cli/chunks/{chunk-2RE32VOF.js → chunk-42DCMEUM.js} +1 -1
  29. package/dist/cli/chunks/{chunk-ZRWAFMM7.js → chunk-4FTVTAMN.js} +2 -2
  30. package/dist/cli/chunks/{chunk-437XL5VZ.js → chunk-4PYJCIRO.js} +2 -2
  31. package/dist/cli/chunks/{chunk-4RUS5E3Q.js → chunk-527U4AHC.js} +2 -2
  32. package/dist/cli/chunks/{chunk-OX2PGDUM.js → chunk-5AFO7ZZG.js} +3 -3
  33. package/dist/cli/chunks/{chunk-S7IHSELP.js → chunk-5BDVFFYF.js} +2 -2
  34. package/dist/cli/chunks/{chunk-IAHJ62JS.js → chunk-5KMGG3QW.js} +4 -4
  35. package/dist/cli/chunks/{chunk-LNV76GGB.js → chunk-6LQIVIZB.js} +2 -2
  36. package/dist/cli/chunks/{chunk-FOD6JEEU.js → chunk-6SOGYNJG.js} +2 -2
  37. package/dist/cli/chunks/{chunk-5PSIKJL5.js → chunk-6VAFRS5N.js} +2 -2
  38. package/dist/cli/chunks/chunk-72VVTMEL.js +2 -0
  39. package/dist/cli/chunks/{chunk-SU4YXUVK.js → chunk-75C5GX7D.js} +2 -2
  40. package/dist/cli/chunks/{chunk-B6U56VWG.js → chunk-76RO2RHG.js} +1 -1
  41. package/dist/cli/chunks/{chunk-OUSD2RWO.js → chunk-7HYO76F2.js} +2 -2
  42. package/dist/cli/chunks/{chunk-PY4YQDBM.js → chunk-7KHZZVF2.js} +4 -4
  43. package/dist/cli/chunks/{chunk-NKCL6RAF.js → chunk-7MKF52GT.js} +2 -2
  44. package/dist/cli/chunks/{chunk-FK3XYV3A.js → chunk-7VM4ZUHT.js} +2 -2
  45. package/dist/cli/chunks/{chunk-VS2G6LX5.js → chunk-7XIQR6VU.js} +2 -2
  46. package/dist/cli/chunks/{chunk-OHBZON7T.js → chunk-A4ZDKF5F.js} +1 -1
  47. package/dist/cli/chunks/{chunk-K7XPKGOL.js → chunk-AAVUZVM6.js} +2 -2
  48. package/dist/cli/chunks/{chunk-44HXRFOP.js → chunk-AINAWVGD.js} +2 -2
  49. package/dist/cli/chunks/{chunk-P7CMWL7Y.js → chunk-AK5Q2WCJ.js} +2 -2
  50. package/dist/cli/chunks/{chunk-Z6ADE3KJ.js → chunk-AKZK46TQ.js} +2 -2
  51. package/dist/cli/chunks/{chunk-4UHWZ47M.js → chunk-ARUXFZDY.js} +1 -1
  52. package/dist/cli/chunks/{chunk-7DQLYWLR.js → chunk-AYXRT2ND.js} +1 -1
  53. package/dist/cli/chunks/{chunk-X2OVUBF6.js → chunk-AZQ6HDPM.js} +2 -2
  54. package/dist/cli/chunks/{chunk-CN2HMHIY.js → chunk-BGVEBYV4.js} +2 -2
  55. package/dist/cli/chunks/{chunk-LOPM3YIO.js → chunk-C6UTRG66.js} +2 -2
  56. package/dist/cli/chunks/{chunk-4OYC5TIZ.js → chunk-CAUTOCLZ.js} +2 -2
  57. package/dist/cli/chunks/{chunk-6WNYBIPS.js → chunk-CAVBEZV4.js} +2 -2
  58. package/dist/cli/chunks/{chunk-BOQNPFO5.js → chunk-CEMROADY.js} +1 -1
  59. package/dist/cli/chunks/{chunk-ATQTTGSE.js → chunk-CMVNYVKL.js} +2 -2
  60. package/dist/cli/chunks/{chunk-N52WQO3G.js → chunk-CUDGKSFX.js} +2 -2
  61. package/dist/cli/chunks/{chunk-X4GKYSOH.js → chunk-CZYSCUJ4.js} +2 -2
  62. package/dist/cli/chunks/{chunk-72UPBNVF.js → chunk-DMUQV2YU.js} +2 -2
  63. package/dist/cli/chunks/{chunk-BXLWERBR.js → chunk-DPFLJMEI.js} +3 -3
  64. package/dist/cli/chunks/{chunk-H5GCRC2D.js → chunk-DU4GQKTH.js} +2 -2
  65. package/dist/cli/chunks/{chunk-S7ZHD6VN.js → chunk-EDH4H55B.js} +2 -2
  66. package/dist/cli/chunks/{chunk-MILWEZSZ.js → chunk-EIWZDVMT.js} +3 -3
  67. package/dist/cli/chunks/{chunk-O5NF6BBD.js → chunk-FPZLOVEF.js} +1 -1
  68. package/dist/cli/chunks/{chunk-6CH7476R.js → chunk-FV53RMVB.js} +1 -1
  69. package/dist/cli/chunks/{chunk-QEDS3MOJ.js → chunk-FYY7OJ6Y.js} +2 -2
  70. package/dist/cli/chunks/{chunk-CXIFCN6G.js → chunk-G4CQBQBV.js} +1 -1
  71. package/dist/cli/chunks/{chunk-CZU5G6J4.js → chunk-G6LIQFT2.js} +1 -1
  72. package/dist/cli/chunks/{chunk-TUEDIQHY.js → chunk-H3LGBH4Y.js} +1 -1
  73. package/dist/cli/chunks/{chunk-BR4ERWVD.js → chunk-H4ZPPHOI.js} +2 -2
  74. package/dist/cli/chunks/{chunk-N6RSJGTW.js → chunk-H5TM4KIB.js} +2 -2
  75. package/dist/cli/chunks/{chunk-K3BBLIWW.js → chunk-H6MBRYA7.js} +2 -2
  76. package/dist/cli/chunks/{chunk-YFY35CSD.js → chunk-HDBJORV7.js} +2 -2
  77. package/dist/cli/chunks/{chunk-QXDZN2WX.js → chunk-I3AD523O.js} +1 -1
  78. package/dist/cli/chunks/{chunk-HOFEAA4R.js → chunk-I7UWFV6N.js} +1 -1
  79. package/dist/cli/chunks/{chunk-4BMPFEEG.js → chunk-IMPSB5WW.js} +2 -2
  80. package/dist/cli/chunks/{chunk-ILZHECWZ.js → chunk-IO7ZUP2G.js} +3 -3
  81. package/dist/cli/chunks/{chunk-QUTKELAS.js → chunk-IQOCTGA2.js} +2 -2
  82. package/dist/cli/chunks/{chunk-S456W64P.js → chunk-IXYF5BZY.js} +2 -2
  83. package/dist/cli/chunks/{chunk-B5EE63VE.js → chunk-JC4Z2ADP.js} +2 -2
  84. package/dist/cli/chunks/{chunk-IUVAWWQG.js → chunk-JCH2FHJ7.js} +2 -2
  85. package/dist/cli/chunks/{chunk-MX6M2VPB.js → chunk-JDFF2QMZ.js} +1 -1
  86. package/dist/cli/chunks/{chunk-EFRIMR74.js → chunk-JELN5XTK.js} +1 -1
  87. package/dist/cli/chunks/{chunk-3G25ZBQ6.js → chunk-JSZNI3AO.js} +1 -1
  88. package/dist/cli/chunks/{chunk-AEZMNFXM.js → chunk-K3YM2Z3E.js} +1 -1
  89. package/dist/cli/chunks/{chunk-QMN563LV.js → chunk-K426HTEQ.js} +44 -44
  90. package/dist/cli/chunks/{chunk-7OAKIXNM.js → chunk-K6IQBVD7.js} +2 -2
  91. package/dist/cli/chunks/{chunk-C7FYDE5F.js → chunk-KEJEZY2R.js} +125 -150
  92. package/dist/cli/chunks/{chunk-SZPTUV3B.js → chunk-KFE6LB4I.js} +2 -2
  93. package/dist/cli/chunks/{chunk-TOQJWLJV.js → chunk-KO3WB4SU.js} +2 -2
  94. package/dist/cli/chunks/{chunk-3IMEDZIS.js → chunk-LAY35POY.js} +3 -3
  95. package/dist/cli/chunks/{chunk-NYWK7ZSX.js → chunk-LFXXA325.js} +1 -1
  96. package/dist/cli/chunks/{chunk-IVZVVZZ3.js → chunk-LI3T5YNC.js} +3 -3
  97. package/dist/cli/chunks/{chunk-7SRSOZMP.js → chunk-LIEA5EON.js} +1 -1
  98. package/dist/cli/chunks/{chunk-76UVJLPM.js → chunk-LRJWKFGY.js} +2 -2
  99. package/dist/cli/chunks/{chunk-N6NSZG7Z.js → chunk-LY6PTRVL.js} +2 -2
  100. package/dist/cli/chunks/{chunk-L2QHZFC3.js → chunk-MAXOIEUG.js} +1 -1
  101. package/dist/cli/chunks/{chunk-7WQKKYYG.js → chunk-MN6W7ZNL.js} +1 -1
  102. package/dist/cli/chunks/{chunk-DZT4A7R3.js → chunk-NGE5YNKC.js} +2 -2
  103. package/dist/cli/chunks/{chunk-O75SVMMB.js → chunk-NIW4CLN2.js} +2 -2
  104. package/dist/cli/chunks/{chunk-BVFNF3RW.js → chunk-NPT7BYGF.js} +1 -1
  105. package/dist/cli/chunks/{chunk-CII57TME.js → chunk-NZNXEEZR.js} +1 -1
  106. package/dist/cli/chunks/{chunk-J2LAYCYZ.js → chunk-O3IIAIXB.js} +1 -1
  107. package/dist/cli/chunks/{chunk-3D4HNUZM.js → chunk-OC2W7KIW.js} +2 -2
  108. package/dist/cli/chunks/{chunk-ZKPOKMJZ.js → chunk-OFUF3APC.js} +2 -2
  109. package/dist/cli/chunks/{chunk-4G4GTF36.js → chunk-OU52V67H.js} +4 -4
  110. package/dist/cli/chunks/{chunk-5QFZEEJ2.js → chunk-P2RR4SW5.js} +3 -3
  111. package/dist/cli/chunks/{chunk-JGHEGMLD.js → chunk-P3VRXQ3H.js} +3 -3
  112. package/dist/cli/chunks/{chunk-KIBP3LGY.js → chunk-P5SGBQLY.js} +1 -1
  113. package/dist/cli/chunks/{chunk-5LDUW2FD.js → chunk-P7MIOTVP.js} +1 -1
  114. package/dist/cli/chunks/{chunk-VGR65B4Y.js → chunk-PFDILSVO.js} +1 -1
  115. package/dist/cli/chunks/{chunk-WIC5UZCQ.js → chunk-PPD5ZLNA.js} +2 -2
  116. package/dist/cli/chunks/{chunk-4565IIF6.js → chunk-QFJDR4HC.js} +2 -2
  117. package/dist/cli/chunks/{chunk-7QICU44H.js → chunk-QZ2GQGJX.js} +2 -2
  118. package/dist/cli/chunks/{chunk-EQYDPF52.js → chunk-QZLTIGLB.js} +1 -1
  119. package/dist/cli/chunks/{chunk-3V5DAM37.js → chunk-RHSUXQNF.js} +2 -2
  120. package/dist/cli/chunks/{chunk-HMVL55QX.js → chunk-S6BWEZKK.js} +2 -2
  121. package/dist/cli/chunks/{chunk-IIX5Y7BO.js → chunk-SE4S23C7.js} +1 -1
  122. package/dist/cli/chunks/{chunk-6ZAUNPAI.js → chunk-TOGZ37RL.js} +2 -2
  123. package/dist/cli/chunks/{chunk-D6MPGK7R.js → chunk-UCXW24HY.js} +2 -2
  124. package/dist/cli/chunks/{chunk-D4DAZ3P2.js → chunk-UQ6WB4N2.js} +2 -2
  125. package/dist/cli/chunks/{chunk-22FHOXEE.js → chunk-UQBGA4UA.js} +1 -1
  126. package/dist/cli/chunks/{chunk-UDLN2THT.js → chunk-VNFL2TPU.js} +1 -1
  127. package/dist/cli/chunks/{chunk-U5GCSSYX.js → chunk-WARFZ626.js} +1 -1
  128. package/dist/cli/chunks/{chunk-XMDZRULK.js → chunk-WEBHFIWS.js} +2 -2
  129. package/dist/cli/chunks/{chunk-N4OWZLH5.js → chunk-WKIYYF3G.js} +2 -2
  130. package/dist/cli/chunks/{chunk-3DS7ZHA7.js → chunk-WZC4HKGZ.js} +2 -2
  131. package/dist/cli/chunks/{chunk-T7PUM6OY.js → chunk-X36TZXDK.js} +1 -1
  132. package/dist/cli/chunks/{chunk-4S3UIY3G.js → chunk-XN4G3SRU.js} +2 -2
  133. package/dist/cli/chunks/{chunk-V6YDM37M.js → chunk-XNREA3FG.js} +1 -1
  134. package/dist/cli/chunks/{chunk-EJSDQQZH.js → chunk-XRDPGJNW.js} +2 -2
  135. package/dist/cli/chunks/{chunk-GUSW3OGX.js → chunk-XXCSJMSR.js} +1 -1
  136. package/dist/cli/chunks/{chunk-VRHLHGKR.js → chunk-XY2B2BEJ.js} +2 -2
  137. package/dist/cli/chunks/{chunk-CIDTFU3C.js → chunk-XY4JS3IZ.js} +2 -2
  138. package/dist/cli/chunks/{chunk-W6RS5S4Q.js → chunk-Y4M2HMPR.js} +2 -2
  139. package/dist/cli/chunks/{chunk-AG4BYKUV.js → chunk-YDPBCN7H.js} +2 -2
  140. package/dist/cli/chunks/{chunk-56PICCZN.js → chunk-YGR54EAA.js} +2 -2
  141. package/dist/cli/chunks/{chunk-6YNXH6H4.js → chunk-YGRY2TVI.js} +2 -2
  142. package/dist/cli/chunks/{chunk-H4V6WCF7.js → chunk-YJUJCLXV.js} +2 -2
  143. package/dist/cli/chunks/{chunk-KRUKMGPF.js → chunk-YWG4LHFU.js} +2 -2
  144. package/dist/cli/chunks/{chunk-FBOPSWF6.js → chunk-Z2QNTRUX.js} +2 -2
  145. package/dist/cli/chunks/{chunk-3XCEFSUK.js → chunk-ZBJMVWQR.js} +2 -2
  146. package/dist/cli/chunks/{chunk-C27UV6DO.js → chunk-ZH6HYT7C.js} +1 -1
  147. package/dist/cli/chunks/{chunk-WEPZOCN7.js → chunk-ZP2GE6DM.js} +1 -1
  148. package/dist/cli/chunks/{chunk-LSZLXLZA.js → chunk-ZQYEBLTL.js} +2 -2
  149. package/dist/cli/chunks/{chunk-AL54LED5.js → chunk-ZRU3OZEU.js} +2 -2
  150. package/dist/cli/chunks/{chunk-HYT5EMES.js → chunk-ZU3V4CJ4.js} +2 -2
  151. package/dist/cli/chunks/{chunk-TCKBICJ3.js → chunk-ZWMXF6AX.js} +2 -2
  152. package/dist/cli/chunks/{ci-KTWY7BZT.js → ci-SM3EVLZ4.js} +2 -2
  153. package/dist/cli/chunks/{ci-output-WOX6QBMS.js → ci-output-YYXICZBC.js} +2 -2
  154. package/dist/cli/chunks/{circuit-breaker-6XKOSFIF.js → circuit-breaker-CV5UGKXT.js} +2 -2
  155. package/dist/cli/chunks/{claude-flow-setup-5JA4MNE4.js → claude-flow-setup-BSBUZ4B7.js} +2 -2
  156. package/dist/cli/chunks/client-WRDYZGM2.js +2 -0
  157. package/dist/cli/chunks/{cline-installer-Z2ANHEKW.js → cline-installer-P2O6STIC.js} +2 -2
  158. package/dist/cli/chunks/code-M7DDLBGS.js +58 -0
  159. package/dist/cli/chunks/{code-index-extractor-VV4OEPG7.js → code-index-extractor-3QZIUYOG.js} +2 -2
  160. package/dist/cli/chunks/{codex-installer-BP7Y2NYR.js → codex-installer-5JVZCCTC.js} +2 -2
  161. package/dist/cli/chunks/{completions-YULJQUF4.js → completions-EM7IL2BJ.js} +8 -5
  162. package/dist/cli/chunks/{complexity-analyzer-D7XYPQ76.js → complexity-analyzer-VJXVB2CV.js} +2 -2
  163. package/dist/cli/chunks/{continuedev-installer-E3L7UF72.js → continuedev-installer-RCKJIAEC.js} +2 -2
  164. package/dist/cli/chunks/{copilot-installer-5TRUMJC5.js → copilot-installer-DZ7LTDOZ.js} +2 -2
  165. package/dist/cli/chunks/core-handlers-O6E5DNHT.js +2 -0
  166. package/dist/cli/chunks/{cost-tracker-QTYSJMSV.js → cost-tracker-QLOLXVAM.js} +2 -2
  167. package/dist/cli/chunks/{coverage-D5DKZ3XT.js → coverage-LYHTLWRV.js} +3 -3
  168. package/dist/cli/chunks/cross-domain-router-EV7LQMDO.js +2 -0
  169. package/dist/cli/chunks/{cursor-installer-UDBHGUIG.js → cursor-installer-PSIZ3Y53.js} +2 -2
  170. package/dist/cli/chunks/{daemon-IVWUMQKL.js → daemon-IYDTMA5M.js} +4 -4
  171. package/dist/cli/chunks/{daemon-2GXYN7F7.js → daemon-YLOAXM4X.js} +3 -3
  172. package/dist/cli/chunks/{dag-attention-scheduler-PWXR4QTU.js → dag-attention-scheduler-I2UIO3Z7.js} +2 -2
  173. package/dist/cli/chunks/{detect-C6P7ONFB.js → detect-ZXQ7X7GZ.js} +2 -2
  174. package/dist/cli/chunks/{dist-node-2BUFM2JK.js → dist-node-GK6OZX4H.js} +2 -2
  175. package/dist/cli/chunks/{domain-handler-Q2GWZLDM.js → domain-handler-NS3IBLRQ.js} +2 -2
  176. package/dist/cli/chunks/{domain-transfer-GMUBAM3J.js → domain-transfer-5G4RZEWF.js} +2 -2
  177. package/dist/cli/chunks/dream-E4C236UL.js +2 -0
  178. package/dist/cli/chunks/{embed-and-insert-pattern-EFUERRM2.js → embed-and-insert-pattern-V4JJUFR6.js} +2 -2
  179. package/dist/cli/chunks/{eval-24FIC43F.js → eval-7Q6PPYKR.js} +2 -2
  180. package/dist/cli/chunks/{experience-capture-middleware-R4UP2Q2M.js → experience-capture-middleware-DUBKSYFM.js} +3 -3
  181. package/dist/cli/chunks/{fast-paths-RQCGGTXB.js → fast-paths-IDPPMBUW.js} +2 -2
  182. package/dist/cli/chunks/{feature-flags-SOXVYIBN.js → feature-flags-EPTMAAKA.js} +2 -2
  183. package/dist/cli/chunks/{feature-flags-APTWWVNQ.js → feature-flags-KXI6FDY7.js} +2 -2
  184. package/dist/cli/chunks/{file-discovery-66KRMXVF.js → file-discovery-EDX2OJO7.js} +2 -2
  185. package/dist/cli/chunks/{fleet-EMBNKO5Q.js → fleet-67BO3LJ4.js} +3 -3
  186. package/dist/cli/chunks/{gnn-wrapper-6TKDWFJF.js → gnn-wrapper-YARORYT7.js} +2 -2
  187. package/dist/cli/chunks/{heartbeat-handler-4ODKJ75H.js → heartbeat-handler-K3JGPBYR.js} +4 -4
  188. package/dist/cli/chunks/heartbeat-scheduler-WMADLDKT.js +2 -0
  189. package/dist/cli/chunks/hnsw-adapter-STRDGJ65.js +2 -0
  190. package/dist/cli/chunks/hnsw-index-DBHX3TSC.js +2 -0
  191. package/dist/cli/chunks/{hnsw-legacy-bridge-25KFCLUC.js → hnsw-legacy-bridge-CDDRSV5E.js} +2 -2
  192. package/dist/cli/chunks/{better-sqlite3-MJNUEPYB.js → hnswlib-node-2KL54YUA.js} +2 -2
  193. package/dist/cli/chunks/{hooks-JIDA2COE.js → hooks-6SCAE6LC.js} +10 -10
  194. package/dist/cli/chunks/hybrid-router-L2K55I4T.js +2 -0
  195. package/dist/cli/chunks/{hypergraph-engine-3YDFDPE3.js → hypergraph-engine-I3LUMO7I.js} +2 -2
  196. package/dist/cli/chunks/{hypergraph-handler-VWZX2OJX.js → hypergraph-handler-YAKAIVCN.js} +3 -3
  197. package/dist/cli/chunks/impact-analyzer-WMO7ZGS7.js +2 -0
  198. package/dist/cli/chunks/{init-handler-DH7VQAMF.js → init-handler-NBKCZD7Q.js} +6 -6
  199. package/dist/cli/chunks/init-wizard-ZAB7UZZS.js +2 -0
  200. package/dist/cli/chunks/kernel-4MUFDEQI.js +2 -0
  201. package/dist/cli/chunks/{kilocode-installer-2W2KZCGH.js → kilocode-installer-YGPJCPU3.js} +2 -2
  202. package/dist/cli/chunks/{kiro-installer-E5KP7OMD.js → kiro-installer-JV3ONVMN.js} +2 -2
  203. package/dist/cli/chunks/knowledge-graph-GZRFGXLX.js +2 -0
  204. package/dist/cli/chunks/{learning-XJRUVPLF.js → learning-2FEZJ5CX.js} +3 -3
  205. package/dist/cli/chunks/{llm-router-AEEKEMF5.js → llm-router-SILI4KLU.js} +4 -4
  206. package/dist/cli/chunks/llm-router-service-5ODLU5U5.js +2 -0
  207. package/dist/cli/chunks/{load-PZ4YOTBJ.js → load-EGXLQVR3.js} +2 -2
  208. package/dist/cli/chunks/load-test-ZDQFS5XS.js +2 -0
  209. package/dist/cli/chunks/{mcp-IVA6LC2S.js → mcp-OJH775TL.js} +2 -2
  210. package/dist/cli/chunks/{memory-Y3DHXFQE.js → memory-FNEOK4FW.js} +5 -5
  211. package/dist/cli/chunks/memory-backend-UK7SQ6ZM.js +2 -0
  212. package/dist/cli/chunks/{memory-handlers-V5PXEJWL.js → memory-handlers-6LDUH3JZ.js} +2 -2
  213. package/dist/cli/chunks/{multi-model-executor-646G4S4Y.js → multi-model-executor-ORTFWLLE.js} +2 -2
  214. package/dist/cli/chunks/{opencode-installer-P6KOOTUS.js → opencode-installer-UAQLW6XX.js} +2 -2
  215. package/dist/cli/chunks/{orchestrator-T2GVKYMX.js → orchestrator-VE5KJ2V4.js} +5 -5
  216. package/dist/cli/chunks/pattern-null-store-LO2QTIBU.js +2 -0
  217. package/dist/cli/chunks/{pipeline-CK2ON45P.js → pipeline-FNMDRWTU.js} +2 -2
  218. package/dist/cli/chunks/{platform-OQNSD3A3.js → platform-MGAKRUQN.js} +2 -2
  219. package/dist/cli/chunks/{plugin-UOG6RNRM.js → plugin-YX7THX3I.js} +2 -2
  220. package/dist/cli/chunks/{prime-radiant-advanced-wasm-37UE6TG5.js → prime-radiant-advanced-wasm-XJV4RLMK.js} +2 -2
  221. package/dist/cli/chunks/protocol-executor-JWMYQEOI.js +2 -0
  222. package/dist/cli/chunks/{protocol-handler-V722S6YH.js → protocol-handler-QFET442Y.js} +2 -2
  223. package/dist/cli/chunks/{prove-ANGY6W3W.js → prove-QBAESCOC.js} +2 -2
  224. package/dist/cli/chunks/provider-manager-PEXOHGNB.js +2 -0
  225. package/dist/cli/chunks/qe-reasoning-bank-7B2G4UGQ.js +2 -0
  226. package/dist/cli/chunks/{quality-KG4ALI2L.js → quality-ZTNRL6EG.js} +2 -2
  227. package/dist/cli/chunks/queen-coordinator-6OF4HT3S.js +2 -0
  228. package/dist/cli/chunks/{real-embeddings-GUZDO5UN.js → real-embeddings-ZFFDV6HC.js} +2 -2
  229. package/dist/cli/chunks/{roocode-installer-WROAR6MJ.js → roocode-installer-J4LFL4AE.js} +2 -2
  230. package/dist/cli/chunks/router-GMWRF6DU.js +2 -0
  231. package/dist/cli/chunks/routing-feedback-XKJSQK3I.js +2 -0
  232. package/dist/cli/chunks/{routing-handler-UFPSSS5D.js → routing-handler-A5QG2TP2.js} +2 -2
  233. package/dist/cli/chunks/{ruvector-commands-XJQMKDRM.js → ruvector-commands-J5JL5WX5.js} +2 -2
  234. package/dist/cli/chunks/{rvf-dual-writer-QPRMDKYX.js → rvf-dual-writer-H7442GMO.js} +2 -2
  235. package/dist/cli/chunks/{rvf-migration-adapter-SOHBK23K.js → rvf-migration-adapter-PTFQUYKC.js} +2 -2
  236. package/dist/cli/chunks/{rvf-migration-coordinator-MTWUSPEJ.js → rvf-migration-coordinator-RSNROYRX.js} +2 -2
  237. package/dist/cli/chunks/rvf-native-adapter-YEA6TMXB.js +2 -0
  238. package/dist/cli/chunks/safe-db-5DOP2J3V.js +2 -0
  239. package/dist/cli/chunks/schedule-SUWTOBHP.js +2 -0
  240. package/dist/cli/chunks/scheduler-P4VTC5SQ.js +2 -0
  241. package/dist/cli/chunks/{security-5MAMQKP6.js → security-LHHLMCBA.js} +3 -3
  242. package/dist/cli/chunks/{shared-rvf-adapter-YEUBSRNN.js → shared-rvf-adapter-NPSHVUTM.js} +2 -2
  243. package/dist/cli/chunks/{shared-rvf-dual-writer-DBQJHG42.js → shared-rvf-dual-writer-INQDY5WE.js} +2 -2
  244. package/dist/cli/chunks/sqlite-persistence-5Z2RAXH7.js +2 -0
  245. package/dist/cli/chunks/{status-handler-ZUB2UKQZ.js → status-handler-R2KIAMAE.js} +2 -2
  246. package/dist/cli/chunks/{structural-health-B2GHENWX.js → structural-health-2VPPIOZX.js} +2 -2
  247. package/dist/cli/chunks/{sync-7VMXJTR2.js → sync-ASZ3T5GT.js} +2 -2
  248. package/dist/cli/chunks/{sync-YCUUW3IP.js → sync-NLASP7AK.js} +2 -2
  249. package/dist/cli/chunks/{task-handler-N7LJTXZM.js → task-handler-UV5R6LJG.js} +2 -2
  250. package/dist/cli/chunks/{task-handlers-GDHNJV2E.js → task-handlers-I6YJXPYP.js} +3 -3
  251. package/dist/cli/chunks/{test-6COGC5KI.js → test-TE43TNTI.js} +4 -4
  252. package/dist/cli/chunks/{test-scheduling-CUERHJMF.js → test-scheduling-WWWWF2TZ.js} +3 -3
  253. package/dist/cli/chunks/{token-bootstrap-JTGSL6PP.js → token-bootstrap-HEWP7KKS.js} +2 -2
  254. package/dist/cli/chunks/{token-usage-LSG3JYGX.js → token-usage-3FVHUAW6.js} +2 -2
  255. package/dist/cli/chunks/{transformers-ODIITRCT.js → transformers-O5OFM4XM.js} +2 -2
  256. package/dist/cli/chunks/{tree-sitter-wasm-parser-KSP7ZZ5H.js → tree-sitter-wasm-parser-YOYWFW63.js} +2 -2
  257. package/dist/cli/chunks/{types-6N6SUU2O.js → types-42GR6PLO.js} +2 -2
  258. package/dist/cli/chunks/unified-memory-HCKOPFAY.js +2 -0
  259. package/dist/cli/chunks/unified-memory-hnsw-6NQPYA5C.js +2 -0
  260. package/dist/cli/chunks/unified-persistence-NIMKNAFR.js +2 -0
  261. package/dist/cli/chunks/{upgrade-7SCVOCPS.js → upgrade-BU6DJ4LT.js} +2 -2
  262. package/dist/cli/chunks/{validate-762ISH2Y.js → validate-MPTBARGN.js} +2 -2
  263. package/dist/cli/chunks/{validate-swarm-R6WYYXGO.js → validate-swarm-5LUQYHPP.js} +2 -2
  264. package/dist/cli/chunks/{vibium-5GZYSUDQ.js → vibium-MJJDANDL.js} +2 -2
  265. package/dist/cli/chunks/visual-security-HFGHA57Z.js +2 -0
  266. package/dist/cli/chunks/{web-tree-sitter-VYYVAJTY.js → web-tree-sitter-5TF4UGB3.js} +2 -2
  267. package/dist/cli/chunks/{windsurf-installer-RRIOR3B6.js → windsurf-installer-NQAOSVCN.js} +2 -2
  268. package/dist/cli/chunks/{witness-chain-SRVBEKDB.js → witness-chain-23UWK2JT.js} +2 -2
  269. package/dist/cli/chunks/witness-chain-VZGGJ7TJ.js +2 -0
  270. package/dist/cli/chunks/{workflow-XNUDHGEC.js → workflow-3QOLXRJC.js} +4 -4
  271. package/dist/cli/chunks/workflow-orchestrator-45L7D4SN.js +2 -0
  272. package/dist/cli/chunks/{wrappers-3STST7QW.js → wrappers-S6EUZBCX.js} +2 -2
  273. package/dist/cli/commands/code.js +78 -2
  274. package/dist/cli/completions/index.js +4 -1
  275. package/dist/domains/code-intelligence/coordinator.js +8 -4
  276. package/dist/domains/code-intelligence/services/c4-model/from-detected.d.ts +41 -0
  277. package/dist/domains/code-intelligence/services/c4-model/from-detected.js +152 -0
  278. package/dist/domains/code-intelligence/services/c4-model/kg-relationships.d.ts +71 -0
  279. package/dist/domains/code-intelligence/services/c4-model/kg-relationships.js +87 -0
  280. package/dist/domains/code-intelligence/services/knowledge-graph.d.ts +6 -0
  281. package/dist/domains/code-intelligence/services/knowledge-graph.js +3 -3
  282. package/dist/domains/code-intelligence/services/product-factors-bridge.d.ts +26 -5
  283. package/dist/domains/code-intelligence/services/product-factors-bridge.js +72 -65
  284. package/dist/mcp/bundle.js +429 -454
  285. package/dist/mcp/tools/code-intelligence/c4.d.ts +56 -0
  286. package/dist/mcp/tools/code-intelligence/c4.js +145 -0
  287. package/dist/mcp/tools/index.d.ts +1 -0
  288. package/dist/mcp/tools/index.js +1 -0
  289. package/dist/mcp/tools/registry.d.ts +1 -0
  290. package/dist/mcp/tools/registry.js +3 -0
  291. package/dist/shared/c4-model/confidence.d.ts +38 -0
  292. package/dist/shared/c4-model/confidence.js +69 -0
  293. package/dist/shared/c4-model/index.d.ts +4 -0
  294. package/dist/shared/c4-model/index.js +1 -0
  295. package/package.json +1 -1
  296. package/dist/cli/chunks/adapter-A6GCBONS.js +0 -2
  297. package/dist/cli/chunks/aqe-learning-engine-FRCSXNMG.js +0 -2
  298. package/dist/cli/chunks/base-CZ3EHBU5.js +0 -2
  299. package/dist/cli/chunks/browser-workflow-EKTGQQBQ.js +0 -2
  300. package/dist/cli/chunks/chunk-57WGS6BI.js +0 -2
  301. package/dist/cli/chunks/client-X3KUJ6R5.js +0 -2
  302. package/dist/cli/chunks/code-NO4ZKNDU.js +0 -39
  303. package/dist/cli/chunks/core-handlers-A2EQB3UH.js +0 -2
  304. package/dist/cli/chunks/cross-domain-router-OKZ2PDHT.js +0 -2
  305. package/dist/cli/chunks/dream-ZBP4Z5C3.js +0 -2
  306. package/dist/cli/chunks/heartbeat-scheduler-6JUWQXWG.js +0 -2
  307. package/dist/cli/chunks/hnsw-adapter-JT4BU7XJ.js +0 -2
  308. package/dist/cli/chunks/hnsw-index-JC5YELJX.js +0 -2
  309. package/dist/cli/chunks/hybrid-router-SLTXHUFG.js +0 -2
  310. package/dist/cli/chunks/impact-analyzer-JXHCMZXY.js +0 -2
  311. package/dist/cli/chunks/init-wizard-EX37TYOG.js +0 -2
  312. package/dist/cli/chunks/kernel-JPHAG27D.js +0 -2
  313. package/dist/cli/chunks/knowledge-graph-5QJZIRYB.js +0 -2
  314. package/dist/cli/chunks/llm-router-service-SE2RO4P5.js +0 -2
  315. package/dist/cli/chunks/load-test-LOTBWIIS.js +0 -2
  316. package/dist/cli/chunks/memory-backend-BSDKTFAN.js +0 -2
  317. package/dist/cli/chunks/pattern-null-store-LRSXCZWM.js +0 -2
  318. package/dist/cli/chunks/protocol-executor-WPUVJEL7.js +0 -2
  319. package/dist/cli/chunks/provider-manager-EVPWSH3E.js +0 -2
  320. package/dist/cli/chunks/qe-reasoning-bank-IH63FG33.js +0 -2
  321. package/dist/cli/chunks/queen-coordinator-TTCAGYQO.js +0 -2
  322. package/dist/cli/chunks/router-64Q4ILOQ.js +0 -2
  323. package/dist/cli/chunks/routing-feedback-KCZV4XXC.js +0 -2
  324. package/dist/cli/chunks/rvf-native-adapter-GNJKMURU.js +0 -2
  325. package/dist/cli/chunks/safe-db-6VBZQIJI.js +0 -2
  326. package/dist/cli/chunks/schedule-4V7O5IPX.js +0 -2
  327. package/dist/cli/chunks/scheduler-CQDMHEHN.js +0 -2
  328. package/dist/cli/chunks/sqlite-persistence-7DHUFTHL.js +0 -2
  329. package/dist/cli/chunks/unified-memory-MQA72NLP.js +0 -2
  330. package/dist/cli/chunks/unified-memory-hnsw-K7HA3CWV.js +0 -2
  331. package/dist/cli/chunks/unified-persistence-2DXB4OE4.js +0 -2
  332. package/dist/cli/chunks/visual-security-UD6CARIJ.js +0 -2
  333. package/dist/cli/chunks/witness-chain-LWALPPMC.js +0 -2
  334. package/dist/cli/chunks/workflow-orchestrator-QU652FLH.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.11.1");process.exit(0)}
2
- import{a as Pn}from"./chunk-CIDTFU3C.js";import{b as xn}from"./chunk-TOQJWLJV.js";import{a as oi}from"./chunk-VS2G6LX5.js";import{a as li}from"./chunk-K7XPKGOL.js";import{a as ui}from"./chunk-YFY35CSD.js";import{a as di}from"./chunk-LSZLXLZA.js";import{a as si,b as ai}from"./chunk-WIC5UZCQ.js";import{b as St,c as Et}from"./chunk-LNV76GGB.js";import{a as Re}from"./chunk-3G25ZBQ6.js";import{a as ci}from"./chunk-LOPM3YIO.js";import{a as Ct,b as Ir,c as Bs,d as Or,e as Fr,f as Lr,g as Nr,h as Gr,i as zr,j as Ur,k as Hr,l as Vr,m as Qr,n as Wr,o as Kr,p as Xr,q as Yr,r as Jr,s as Zr,t as Ee,u as we,v as ti}from"./chunk-C7FYDE5F.js";import{a as Br,c as Ue,d as jr}from"./chunk-CZU5G6J4.js";import{a as ni}from"./chunk-K3BBLIWW.js";import{a as ri}from"./chunk-AG4BYKUV.js";import{d as ii}from"./chunk-IVZVVZZ3.js";import{a as be}from"./chunk-VGR65B4Y.js";import{b as Tt}from"./chunk-MILWEZSZ.js";import{s as Dr}from"./chunk-4G4GTF36.js";import{c as ei}from"./chunk-7GP7ZG3K.js";import{a as le,b as ue}from"./chunk-5Y7GXQOM.js";import{c as _r}from"./chunk-NVJIOCS5.js";import{d as Rn}from"./chunk-SU4YXUVK.js";import{a as $r}from"./chunk-6YNXH6H4.js";import{c as de,g as qr}from"./chunk-BXLWERBR.js";import{a as Mr,b as J,c as U}from"./chunk-OUBYADPD.js";import{c as L,i as B,k as x}from"./chunk-X4GKYSOH.js";import{h as bt}from"./chunk-ILZHECWZ.js";import{a as Sn}from"./chunk-PY4YQDBM.js";import{c as En,d as wn}from"./chunk-7OAKIXNM.js";import{d as ce}from"./chunk-HOFEAA4R.js";import{c as kr}from"./chunk-6WNYBIPS.js";import{b as Se}from"./chunk-JGHEGMLD.js";import{i as j,m as ie}from"./chunk-437XL5VZ.js";import{a as xr}from"./chunk-57WGS6BI.js";import{c as ft,d as Ce,e as Tn}from"./chunk-S7IHSELP.js";import{b as A,d as H}from"./chunk-N6NSZG7Z.js";import{a as Cn,b as I,c as G}from"./chunk-EQYDPF52.js";import{a as E,b as $,c as M}from"./chunk-QEDS3MOJ.js";import{i as N}from"./chunk-B6U56VWG.js";import{a as Ar,b as $s}from"./chunk-X2OVUBF6.js";import{a as te,c as ne,d as je}from"./chunk-NKCL6RAF.js";import{a as yt}from"./chunk-44HXRFOP.js";import{R as zs,S as vt,b as Te}from"./chunk-N4OWZLH5.js";import{a as Ns,c as qs,e as Gs,g as Pr}from"./chunk-7SRSOZMP.js";var Mi={};Gs(Mi,{DEFAULT_QEC_CONFIG:()=>Ai,ReasoningQEC:()=>Bt,createReasoningQEC:()=>ki,processReasoning:()=>uo});async function lo(){return xi?Pi!==null:(Pi=null,xi=!0,!1)}function ki(c){return new Bt(c)}function uo(c,e){return ki(e).process(c)}var Xn,Ai,oo,co,Pi,xi,Bt,Di=qs(()=>{"use strict";Tn();vt();Xn=Ce("ReasoningQEC"),Ai={minPaths:3,confidenceThreshold:.5,majorityThreshold:.5,useNativeBackend:!0,votingMethod:"weighted"},oo={"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"]},co=["analytical","empirical","heuristic"],Pi=null,xi=!1;Bt=class{config;nativeAvailable=!1;constructor(e={}){this.config={...Ai,...e}}async initialize(){if(this.config.useNativeBackend){let e=Te();(e.useQEFlashAttention||e.useQEGNNIndex)&&(this.nativeAvailable=await lo())}}generatePaths(e){let t=Math.max(this.config.minPaths,3),n=oo[e.type]??co,r=[];for(let i=0;i<t;i++){let s=n[i%n.length],a=this.generatePathSteps(e,i,s),o=this.deriveConclusion(a,s),u=this.calculatePathConfidence(a);r.push({id:i,steps:a,conclusion:o,confidence:u})}return Xn.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 u of e){let l=u.steps[i];if(!l)continue;let d=s.get(l.conclusion)??[];d.push(u.id),s.set(l.conclusion,d)}if(s.size<=1)continue;let a=[...s.entries()].map(([u,l])=>l.map(d=>({pathId:d,conclusion:u}))).flat(),o=this.classifySyndromeSeverity(s,e.length);t.push({stepIndex:i,disagreements:a,severity:o})}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,o])=>o.map(u=>({pathId:u,conclusion:a}))).flat(),s=this.classifySyndromeSeverity(r,e.length);t.push({stepIndex:-1,disagreements:i,severity:s})}return Xn.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(l=>l.stepIndex>=0).map(l=>l.stepIndex)),r=Math.max(...e.map(l=>l.steps.length)),i=[],s=[];for(let l=0;l<r;l++)if(n.has(l)){let{step:d,correction:m}=this.correctStep(e,l);i.push(d),m&&s.push(m)}else{let d=e[0].steps[l];d&&i.push({...d})}let a=this.correctConclusion(e),o=this.calculateCorrectedConfidence(e,t),u={steps:i,conclusion:a,confidence:o,corrections:s,syndromeCount:t.length};return Xn.debug(`Error correction applied: ${s.length} corrections, confidence: ${o.toFixed(3)}`),u}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:u=>u.length>0?`Focused on ${u[0]}`:"Primary analysis",1:u=>u.length>1?`Focused on ${u[u.length-1]}`:"Secondary analysis",2:u=>u.length>0?`Cross-referencing ${u.join(" and ")}`:"Holistic analysis"},o=(s[r%3]??s[0])(i);return`[${t}] ${e}: ${o}`}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 h=g.steps[t];if(!h)continue;let f=n.get(h.conclusion)??0,v=i?g.confidence:1;n.set(h.conclusion,f+v),r.set(h.conclusion,h)}if(n.size===0)return{step:{index:t,description:`Step ${t} (no data)`,conclusion:"",evidence:[]},correction:null};let s=[...n.entries()].sort((g,h)=>h[1]-g[1]||g[0].localeCompare(h[0])),[a,o]=s[0],u=r.get(a),l=new Set;for(let g of e){let h=g.steps[t];if(h)for(let f of h.evidence)l.add(f)}let d={index:t,description:u.description,conclusion:a,evidence:[...l]},m=e[0].steps[t]?.conclusion,p=null;if(m&&m!==a){let g=e.filter(C=>C.steps[t]).length,h=[...n.values()].reduce((C,b)=>C+b,0),v=o/h>this.config.majorityThreshold;p={stepIndex:t,original:m,corrected:a,reason:v?`${i?"Weighted vote":"Majority vote"} (${o.toFixed(2)}/${h.toFixed(2)} weight from ${g} paths)`:`Selected highest ${i?"weight":"count"} (${o.toFixed(2)}/${h.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((u,l)=>u+l.confidence,0)/e.length,r=t.filter(u=>u.severity==="critical").length,i=t.filter(u=>u.severity==="major").length,s=t.filter(u=>u.severity==="minor").length,a=r*.2+i*.1+s*.03,o=t.length===0?.1:0;return Math.max(0,Math.min(1,n-a+o))}}});M();H();import*as _ from"fs/promises";import*as D from"path";import{createHash as js}from"crypto";var Us={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"}},An=class{baseDir;resultsDir;constructor(e=".agentic-qe"){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),o=r.filenamePrefix||a;switch(t){case"generate-tests":s.push(...await this.saveTestGeneration(n,o,r));break;case"analyze-coverage":s.push(...await this.saveCoverage(n,o,r));break;case"scan-security":s.push(...await this.saveSecurityScan(n,o,r));break;case"assess-quality":s.push(...await this.saveQualityAssessment(n,o,r));break;case"index-code":s.push(...await this.saveCodeIndex(n,o,r));break;case"predict-defects":s.push(...await this.saveDefectPrediction(n,o,r));break;case"validate-contracts":s.push(...await this.saveContractValidation(n,o,r));break;case"test-accessibility":s.push(...await this.saveAccessibilityTest(n,o,r));break;case"run-chaos":s.push(...await this.saveChaosTest(n,o,r));break;default:s.push(...await this.saveGeneric(t,n,o))}let u=this.extractSummary(t,n);return await this.updateIndex(e,t,i,s,u),{taskId:e,taskType:t,timestamp:i,files:s,summary:u}}async saveTestGeneration(e,t,n){let r=[],i=e,s=D.join(this.resultsDir,"tests","generated");await _.mkdir(s,{recursive:!0});let a=D.join(this.resultsDir,"tests",`${t}_manifest.json`),o=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(await _.writeFile(a,o),r.push(await this.createFileEntry(a,"json")),i.tests){for(let d of i.tests)if(d.code){let m=this.getTestExtension(n.language||"typescript",n.framework||"vitest"),p=this.sanitizeFilename(d.name)+m,g=D.join(s,p);await _.writeFile(g,d.code),r.push(await this.createFileEntry(g,"source"))}}let u=D.join(this.resultsDir,"tests",`${t}_report.md`),l=this.generateTestReport(i,n);return await _.writeFile(u,l),r.push(await this.createFileEntry(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(await _.writeFile(a,JSON.stringify(i,null,2)),r.push(await this.createFileEntry(a,"json")),n.includeSecondary!==!1){let l=D.join(s,`${t}_coverage.lcov`),d=this.generateLcov(i);await _.writeFile(l,d),r.push(await this.createFileEntry(l,"lcov"))}let o=D.join(s,`${t}_report.md`),u=this.generateCoverageReport(i);return await _.writeFile(o,u),r.push(await this.createFileEntry(o,"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(await _.writeFile(a,JSON.stringify(i,null,2)),r.push(await this.createFileEntry(a,"json")),n.includeSecondary!==!1){let l=D.join(s,`${t}_scan.sarif`),d=this.generateSarif(i);await _.writeFile(l,d),r.push(await this.createFileEntry(l,"sarif"))}let o=D.join(s,`${t}_report.md`),u=this.generateSecurityReport(i);return await _.writeFile(o,u),r.push(await this.createFileEntry(o,"markdown")),r}async saveQualityAssessment(e,t,n){let r=[],i=e,s=D.join(this.resultsDir,"quality"),a=D.join(s,`${t}_assessment.json`);await _.writeFile(a,JSON.stringify(i,null,2)),r.push(await this.createFileEntry(a,"json"));let o=D.join(s,`${t}_report.md`),u=this.generateQualityReport(i);return await _.writeFile(o,u),r.push(await this.createFileEntry(o,"markdown")),r}async saveCodeIndex(e,t,n){let r=[],i=e,s=D.join(this.resultsDir,"code-index");await _.mkdir(s,{recursive:!0});let a=D.join(s,`${t}_index.json`);return await _.writeFile(a,JSON.stringify(i,null,2)),r.push(await this.createFileEntry(a,"json")),r}async saveDefectPrediction(e,t,n){let r=[],i=D.join(this.resultsDir,"defects");await _.mkdir(i,{recursive:!0});let s=D.join(i,`${t}_prediction.json`);return await _.writeFile(s,JSON.stringify(e,null,2)),r.push(await this.createFileEntry(s,"json")),r}async saveContractValidation(e,t,n){let r=[],i=D.join(this.resultsDir,"contracts");await _.mkdir(i,{recursive:!0});let s=D.join(i,`${t}_validation.json`);return await _.writeFile(s,JSON.stringify(e,null,2)),r.push(await this.createFileEntry(s,"json")),r}async saveAccessibilityTest(e,t,n){let r=[],i=D.join(this.resultsDir,"accessibility");await _.mkdir(i,{recursive:!0});let s=D.join(i,`${t}_test.json`);return await _.writeFile(s,JSON.stringify(e,null,2)),r.push(await this.createFileEntry(s,"json")),r}async saveChaosTest(e,t,n){let r=[],i=D.join(this.resultsDir,"chaos");await _.mkdir(i,{recursive:!0});let s=D.join(i,`${t}_chaos.json`);return await _.writeFile(s,JSON.stringify(e,null,2)),r.push(await this.createFileEntry(s,"json")),r}async saveGeneric(e,t,n){let r=[],i=D.join(this.resultsDir,"other");await _.mkdir(i,{recursive:!0});let s=D.join(i,`${n}_${e}.json`);return await _.writeFile(s,JSON.stringify(t,null,2)),r.push(await this.createFileEntry(s,"json")),r}generateLcov(e){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.11.2");process.exit(0)}
2
+ import{a as An}from"./chunk-XY4JS3IZ.js";import{b as kn}from"./chunk-KO3WB4SU.js";import{a as pi}from"./chunk-7XIQR6VU.js";import{a as hi}from"./chunk-AAVUZVM6.js";import{a as fi}from"./chunk-HDBJORV7.js";import{a as yi}from"./chunk-ZQYEBLTL.js";import{a as di,b as mi}from"./chunk-PPD5ZLNA.js";import{b as Et,c as wt}from"./chunk-6LQIVIZB.js";import{a as Re}from"./chunk-JSZNI3AO.js";import{a as gi}from"./chunk-C6UTRG66.js";import{a as Mr,b as Ct,c as Lr,d as Ws,e as Nr,f as Gr,g as $r,h as zr,i as Br,j as jr,k as Ur,l as Hr,m as Qr,n as Xr,o as Yr,p as Jr,q as Zr,r as ei,s as ti,t as ni,u as ri,v as ii,w as si,x as Ee,y as we,z as oi}from"./chunk-KEJEZY2R.js";import{a as Wr,c as Ue,d as Kr}from"./chunk-G6LIQFT2.js";import{a as ci}from"./chunk-H6MBRYA7.js";import{a as li}from"./chunk-YDPBCN7H.js";import{d as ui}from"./chunk-LI3T5YNC.js";import{a as be}from"./chunk-PFDILSVO.js";import{b as St}from"./chunk-EIWZDVMT.js";import{s as Fr}from"./chunk-OU52V67H.js";import{c as ai}from"./chunk-27KNLVOY.js";import{a as le,b as ue}from"./chunk-2Q65LTJN.js";import{c as qr}from"./chunk-3J3QXLWP.js";import{d as xn}from"./chunk-75C5GX7D.js";import{a as Vr}from"./chunk-YGRY2TVI.js";import{c as de,g as Tt}from"./chunk-DPFLJMEI.js";import{a as _r,b as J,c as U}from"./chunk-3KTOM7NN.js";import{c as F,i as B,k as P}from"./chunk-CZYSCUJ4.js";import{h as bt}from"./chunk-IO7ZUP2G.js";import{a as wn}from"./chunk-7KHZZVF2.js";import{c as Rn,d as Pn}from"./chunk-K6IQBVD7.js";import{d as ce}from"./chunk-I7UWFV6N.js";import{c as Or}from"./chunk-CAVBEZV4.js";import{b as Se}from"./chunk-P3VRXQ3H.js";import{i as j,m as ie}from"./chunk-4PYJCIRO.js";import{a as Dr}from"./chunk-72VVTMEL.js";import{c as ft,d as Ce,e as En}from"./chunk-5BDVFFYF.js";import{b as A,d as H}from"./chunk-LY6PTRVL.js";import{a as Sn,b as I,c as G}from"./chunk-QZLTIGLB.js";import{a as T,b as $,c as k}from"./chunk-FYY7OJ6Y.js";import{i as N}from"./chunk-76RO2RHG.js";import{a as Ir,b as Vs}from"./chunk-AZQ6HDPM.js";import{a as te,c as ne,d as je}from"./chunk-7MKF52GT.js";import{a as yt}from"./chunk-AINAWVGD.js";import{R as Qs,S as vt,b as Te}from"./chunk-WKIYYF3G.js";import{a as js,c as Us,e as Hs,g as kr}from"./chunk-LIEA5EON.js";var Li={};Hs(Li,{DEFAULT_QEC_CONFIG:()=>_i,ReasoningQEC:()=>jt,createReasoningQEC:()=>Fi,processReasoning:()=>yo});async function fo(){return Oi?Ii!==null:(Ii=null,Oi=!0,!1)}function Fi(c){return new jt(c)}function yo(c,e){return Fi(e).process(c)}var Jn,_i,go,ho,Ii,Oi,jt,Ni=Us(()=>{"use strict";En();vt();Jn=Ce("ReasoningQEC"),_i={minPaths:3,confidenceThreshold:.5,majorityThreshold:.5,useNativeBackend:!0,votingMethod:"weighted"},go={"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"]},ho=["analytical","empirical","heuristic"],Ii=null,Oi=!1;jt=class{config;nativeAvailable=!1;constructor(e={}){this.config={..._i,...e}}async initialize(){if(this.config.useNativeBackend){let e=Te();(e.useQEFlashAttention||e.useQEGNNIndex)&&(this.nativeAvailable=await fo())}}generatePaths(e){let t=Math.max(this.config.minPaths,3),n=go[e.type]??ho,r=[];for(let i=0;i<t;i++){let s=n[i%n.length],a=this.generatePathSteps(e,i,s),o=this.deriveConclusion(a,s),u=this.calculatePathConfidence(a);r.push({id:i,steps:a,conclusion:o,confidence:u})}return Jn.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 u of e){let l=u.steps[i];if(!l)continue;let d=s.get(l.conclusion)??[];d.push(u.id),s.set(l.conclusion,d)}if(s.size<=1)continue;let a=[...s.entries()].map(([u,l])=>l.map(d=>({pathId:d,conclusion:u}))).flat(),o=this.classifySyndromeSeverity(s,e.length);t.push({stepIndex:i,disagreements:a,severity:o})}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,o])=>o.map(u=>({pathId:u,conclusion:a}))).flat(),s=this.classifySyndromeSeverity(r,e.length);t.push({stepIndex:-1,disagreements:i,severity:s})}return Jn.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(l=>l.stepIndex>=0).map(l=>l.stepIndex)),r=Math.max(...e.map(l=>l.steps.length)),i=[],s=[];for(let l=0;l<r;l++)if(n.has(l)){let{step:d,correction:m}=this.correctStep(e,l);i.push(d),m&&s.push(m)}else{let d=e[0].steps[l];d&&i.push({...d})}let a=this.correctConclusion(e),o=this.calculateCorrectedConfidence(e,t),u={steps:i,conclusion:a,confidence:o,corrections:s,syndromeCount:t.length};return Jn.debug(`Error correction applied: ${s.length} corrections, confidence: ${o.toFixed(3)}`),u}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:u=>u.length>0?`Focused on ${u[0]}`:"Primary analysis",1:u=>u.length>1?`Focused on ${u[u.length-1]}`:"Secondary analysis",2:u=>u.length>0?`Cross-referencing ${u.join(" and ")}`:"Holistic analysis"},o=(s[r%3]??s[0])(i);return`[${t}] ${e}: ${o}`}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 h=g.steps[t];if(!h)continue;let f=n.get(h.conclusion)??0,v=i?g.confidence:1;n.set(h.conclusion,f+v),r.set(h.conclusion,h)}if(n.size===0)return{step:{index:t,description:`Step ${t} (no data)`,conclusion:"",evidence:[]},correction:null};let s=[...n.entries()].sort((g,h)=>h[1]-g[1]||g[0].localeCompare(h[0])),[a,o]=s[0],u=r.get(a),l=new Set;for(let g of e){let h=g.steps[t];if(h)for(let f of h.evidence)l.add(f)}let d={index:t,description:u.description,conclusion:a,evidence:[...l]},m=e[0].steps[t]?.conclusion,p=null;if(m&&m!==a){let g=e.filter(C=>C.steps[t]).length,h=[...n.values()].reduce((C,b)=>C+b,0),v=o/h>this.config.majorityThreshold;p={stepIndex:t,original:m,corrected:a,reason:v?`${i?"Weighted vote":"Majority vote"} (${o.toFixed(2)}/${h.toFixed(2)} weight from ${g} paths)`:`Selected highest ${i?"weight":"count"} (${o.toFixed(2)}/${h.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((u,l)=>u+l.confidence,0)/e.length,r=t.filter(u=>u.severity==="critical").length,i=t.filter(u=>u.severity==="major").length,s=t.filter(u=>u.severity==="minor").length,a=r*.2+i*.1+s*.03,o=t.length===0?.1:0;return Math.max(0,Math.min(1,n-a+o))}}});k();H();import*as _ from"fs/promises";import*as D from"path";import{createHash as Ks}from"crypto";var Xs={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"}},Mn=class{baseDir;resultsDir;constructor(e=".agentic-qe"){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),o=r.filenamePrefix||a;switch(t){case"generate-tests":s.push(...await this.saveTestGeneration(n,o,r));break;case"analyze-coverage":s.push(...await this.saveCoverage(n,o,r));break;case"scan-security":s.push(...await this.saveSecurityScan(n,o,r));break;case"assess-quality":s.push(...await this.saveQualityAssessment(n,o,r));break;case"index-code":s.push(...await this.saveCodeIndex(n,o,r));break;case"predict-defects":s.push(...await this.saveDefectPrediction(n,o,r));break;case"validate-contracts":s.push(...await this.saveContractValidation(n,o,r));break;case"test-accessibility":s.push(...await this.saveAccessibilityTest(n,o,r));break;case"run-chaos":s.push(...await this.saveChaosTest(n,o,r));break;default:s.push(...await this.saveGeneric(t,n,o))}let u=this.extractSummary(t,n);return await this.updateIndex(e,t,i,s,u),{taskId:e,taskType:t,timestamp:i,files:s,summary:u}}async saveTestGeneration(e,t,n){let r=[],i=e,s=D.join(this.resultsDir,"tests","generated");await _.mkdir(s,{recursive:!0});let a=D.join(this.resultsDir,"tests",`${t}_manifest.json`),o=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(await _.writeFile(a,o),r.push(await this.createFileEntry(a,"json")),i.tests){for(let d of i.tests)if(d.code){let m=this.getTestExtension(n.language||"typescript",n.framework||"vitest"),p=this.sanitizeFilename(d.name)+m,g=D.join(s,p);await _.writeFile(g,d.code),r.push(await this.createFileEntry(g,"source"))}}let u=D.join(this.resultsDir,"tests",`${t}_report.md`),l=this.generateTestReport(i,n);return await _.writeFile(u,l),r.push(await this.createFileEntry(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(await _.writeFile(a,JSON.stringify(i,null,2)),r.push(await this.createFileEntry(a,"json")),n.includeSecondary!==!1){let l=D.join(s,`${t}_coverage.lcov`),d=this.generateLcov(i);await _.writeFile(l,d),r.push(await this.createFileEntry(l,"lcov"))}let o=D.join(s,`${t}_report.md`),u=this.generateCoverageReport(i);return await _.writeFile(o,u),r.push(await this.createFileEntry(o,"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(await _.writeFile(a,JSON.stringify(i,null,2)),r.push(await this.createFileEntry(a,"json")),n.includeSecondary!==!1){let l=D.join(s,`${t}_scan.sarif`),d=this.generateSarif(i);await _.writeFile(l,d),r.push(await this.createFileEntry(l,"sarif"))}let o=D.join(s,`${t}_report.md`),u=this.generateSecurityReport(i);return await _.writeFile(o,u),r.push(await this.createFileEntry(o,"markdown")),r}async saveQualityAssessment(e,t,n){let r=[],i=e,s=D.join(this.resultsDir,"quality"),a=D.join(s,`${t}_assessment.json`);await _.writeFile(a,JSON.stringify(i,null,2)),r.push(await this.createFileEntry(a,"json"));let o=D.join(s,`${t}_report.md`),u=this.generateQualityReport(i);return await _.writeFile(o,u),r.push(await this.createFileEntry(o,"markdown")),r}async saveCodeIndex(e,t,n){let r=[],i=e,s=D.join(this.resultsDir,"code-index");await _.mkdir(s,{recursive:!0});let a=D.join(s,`${t}_index.json`);return await _.writeFile(a,JSON.stringify(i,null,2)),r.push(await this.createFileEntry(a,"json")),r}async saveDefectPrediction(e,t,n){let r=[],i=D.join(this.resultsDir,"defects");await _.mkdir(i,{recursive:!0});let s=D.join(i,`${t}_prediction.json`);return await _.writeFile(s,JSON.stringify(e,null,2)),r.push(await this.createFileEntry(s,"json")),r}async saveContractValidation(e,t,n){let r=[],i=D.join(this.resultsDir,"contracts");await _.mkdir(i,{recursive:!0});let s=D.join(i,`${t}_validation.json`);return await _.writeFile(s,JSON.stringify(e,null,2)),r.push(await this.createFileEntry(s,"json")),r}async saveAccessibilityTest(e,t,n){let r=[],i=D.join(this.resultsDir,"accessibility");await _.mkdir(i,{recursive:!0});let s=D.join(i,`${t}_test.json`);return await _.writeFile(s,JSON.stringify(e,null,2)),r.push(await this.createFileEntry(s,"json")),r}async saveChaosTest(e,t,n){let r=[],i=D.join(this.resultsDir,"chaos");await _.mkdir(i,{recursive:!0});let s=D.join(i,`${t}_chaos.json`);return await _.writeFile(s,JSON.stringify(e,null,2)),r.push(await this.createFileEntry(s,"json")),r}async saveGeneric(e,t,n){let r=[],i=D.join(this.resultsDir,"other");await _.mkdir(i,{recursive:!0});let s=D.join(i,`${n}_${e}.json`);return await _.writeFile(s,JSON.stringify(t,null,2)),r.push(await this.createFileEntry(s,"json")),r}generateLcov(e){return`TN:agentic-qe-coverage
3
3
  SF:summary
4
4
  DA:1,${Math.round(e.lineCoverage)}
5
5
  LF:100
@@ -101,7 +101,7 @@ ${Object.entries(e.metrics).map(([t,n])=>`| ${t} | ${n.toFixed(1)} |`).join(`
101
101
 
102
102
  ${e.recommendations.length===0?"No recommendations - all quality gates passed.":e.recommendations.map((t,n)=>`${n+1}. ${t}`).join(`
103
103
  `)}
104
- `}async ensureDirectories(e){let t=[this.resultsDir,D.join(this.resultsDir,"security"),D.join(this.resultsDir,"coverage"),D.join(this.resultsDir,"quality"),D.join(this.resultsDir,"tests"),D.join(this.resultsDir,"tests","generated")];for(let n of t)await _.mkdir(n,{recursive:!0})}formatTimestamp(e){return e.toISOString().replace(/[:.]/g,"-").slice(0,19)}sanitizeFilename(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_").toLowerCase()}getTestExtension(e,t){let n=Us[e.toLowerCase()];return n&&(n[t.toLowerCase()]||n.default)||".test.ts"}async createFileEntry(e,t){let n=await _.readFile(e),r=await _.stat(e),i=js("sha256").update(n).digest("hex").slice(0,16);return{path:e,format:t,size:r.size,checksum:i}}extractSummary(e,t){let n=t;switch(e){case"scan-security":return{vulnerabilities:n.vulnerabilities,critical:n.critical,high:n.high};case"analyze-coverage":return{lineCoverage:n.lineCoverage,branchCoverage:n.branchCoverage};case"assess-quality":return{qualityScore:n.qualityScore,passed:n.passed};case"generate-tests":return{testsGenerated:n.testsGenerated,coverageEstimate:n.coverageEstimate};default:return{}}}async updateIndex(e,t,n,r,i){let s=D.join(this.resultsDir,"index.json"),a;try{let o=await _.readFile(s,"utf-8");a=A(o)}catch{a={version:"1.0",created:new Date().toISOString(),updated:new Date().toISOString(),results:[],trends:{}}}a.results.push({id:e,type:t,timestamp:n.toISOString(),files:r.map(o=>D.relative(this.resultsDir,o.path)),summary:i}),a.updated=new Date().toISOString(),a.results.length>100&&(a.results=a.results.slice(-100)),await _.writeFile(s,JSON.stringify(a,null,2))}};function mi(c){return new An(c)}Tn();ie();H();var ua=["think","thinking","reasoning","reasoning_scratchpad"],da=new RegExp(`<(${ua.join("|")})(?:\\s[^>]*)?>[\\s\\S]*?</\\1\\s*>`,"gi");function Q(c){if(!c||typeof c!="string"||!c.includes("<"))return c;let e=c;for(let t=0;t<5;t++){let n=e.replace(da," ");if(n===e)break;e=n}return e===c?c:e.replace(/[ \t]{2,}/g," ").trim()}function wt(c){if(typeof c=="string")return Q(c);if(Array.isArray(c))return c.map(e=>wt(e));if(c!==null&&typeof c=="object"){let e={};for(let[t,n]of Object.entries(c))e[t]=wt(n);return e}return c}var ma={maxStepsPerTrajectory:100,autoEndTimeoutMs:1800*1e3,minQualityThreshold:.5,recentBufferSize:100},Rt=class{config;unifiedMemory=null;db=null;prepared=new Map;initialized=!1;activeTrajectories=new Map;recentTrajectories;stats={trajectoriesStarted:0,trajectoriesCompleted:0,trajectoriesAbandoned:0,totalStepsRecorded:0,averageQuality:0,totalQualitySum:0};constructor(e={}){this.config={...ma,...e},this.recentTrajectories=new be(this.config.recentBufferSize)}async initialize(){this.initialized||(this.unifiedMemory=j(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),this.ensureSchema(),this.prepareStatements(),await this.loadRecentTrajectories(),this.cleanupOrphanedTrajectories(),this.initialized=!0,console.log("[TrajectoryTracker] Initialized"))}cleanupOrphanedTrajectories(){if(this.db)try{let e=this.db.prepare(`
104
+ `}async ensureDirectories(e){let t=[this.resultsDir,D.join(this.resultsDir,"security"),D.join(this.resultsDir,"coverage"),D.join(this.resultsDir,"quality"),D.join(this.resultsDir,"tests"),D.join(this.resultsDir,"tests","generated")];for(let n of t)await _.mkdir(n,{recursive:!0})}formatTimestamp(e){return e.toISOString().replace(/[:.]/g,"-").slice(0,19)}sanitizeFilename(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_").toLowerCase()}getTestExtension(e,t){let n=Xs[e.toLowerCase()];return n&&(n[t.toLowerCase()]||n.default)||".test.ts"}async createFileEntry(e,t){let n=await _.readFile(e),r=await _.stat(e),i=Ks("sha256").update(n).digest("hex").slice(0,16);return{path:e,format:t,size:r.size,checksum:i}}extractSummary(e,t){let n=t;switch(e){case"scan-security":return{vulnerabilities:n.vulnerabilities,critical:n.critical,high:n.high};case"analyze-coverage":return{lineCoverage:n.lineCoverage,branchCoverage:n.branchCoverage};case"assess-quality":return{qualityScore:n.qualityScore,passed:n.passed};case"generate-tests":return{testsGenerated:n.testsGenerated,coverageEstimate:n.coverageEstimate};default:return{}}}async updateIndex(e,t,n,r,i){let s=D.join(this.resultsDir,"index.json"),a;try{let o=await _.readFile(s,"utf-8");a=A(o)}catch{a={version:"1.0",created:new Date().toISOString(),updated:new Date().toISOString(),results:[],trends:{}}}a.results.push({id:e,type:t,timestamp:n.toISOString(),files:r.map(o=>D.relative(this.resultsDir,o.path)),summary:i}),a.updated=new Date().toISOString(),a.results.length>100&&(a.results=a.results.slice(-100)),await _.writeFile(s,JSON.stringify(a,null,2))}};function vi(c){return new Mn(c)}En();ie();H();var fa=["think","thinking","reasoning","reasoning_scratchpad"],ya=new RegExp(`<(${fa.join("|")})(?:\\s[^>]*)?>[\\s\\S]*?</\\1\\s*>`,"gi");function Q(c){if(!c||typeof c!="string"||!c.includes("<"))return c;let e=c;for(let t=0;t<5;t++){let n=e.replace(ya," ");if(n===e)break;e=n}return e===c?c:e.replace(/[ \t]{2,}/g," ").trim()}function Rt(c){if(typeof c=="string")return Q(c);if(Array.isArray(c))return c.map(e=>Rt(e));if(c!==null&&typeof c=="object"){let e={};for(let[t,n]of Object.entries(c))e[t]=Rt(n);return e}return c}var va={maxStepsPerTrajectory:100,autoEndTimeoutMs:1800*1e3,minQualityThreshold:.5,recentBufferSize:100},Pt=class{config;unifiedMemory=null;db=null;prepared=new Map;initialized=!1;activeTrajectories=new Map;recentTrajectories;stats={trajectoriesStarted:0,trajectoriesCompleted:0,trajectoriesAbandoned:0,totalStepsRecorded:0,averageQuality:0,totalQualitySum:0};constructor(e={}){this.config={...va,...e},this.recentTrajectories=new be(this.config.recentBufferSize)}async initialize(){this.initialized||(this.unifiedMemory=j(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),this.ensureSchema(),this.prepareStatements(),await this.loadRecentTrajectories(),this.cleanupOrphanedTrajectories(),this.initialized=!0,console.log("[TrajectoryTracker] Initialized"))}cleanupOrphanedTrajectories(){if(this.db)try{let e=this.db.prepare(`
105
105
  UPDATE qe_trajectories
106
106
  SET success = 0,
107
107
  ended_at = datetime('now'),
@@ -161,9 +161,9 @@ ${e.recommendations.length===0?"No recommendations - all quality gates passed.":
161
161
  WHERE domain = ? AND success = 1
162
162
  ORDER BY ended_at DESC
163
163
  LIMIT ?
164
- `))}async loadRecentTrajectories(){let e=this.prepared.get("getRecentTrajectories");if(!e)return;let t=e.all(this.config.recentBufferSize);for(let n of t){let r=await this.rowToTrajectory(n);r&&this.recentTrajectories.push(r)}console.log(`[TrajectoryTracker] Loaded ${t.length} recent trajectories`)}async startTrajectory(e,t={}){this.ensureInitialized(),e=Q(e);let n=N(),r=new Date;this.activeTrajectories.set(n,{id:n,task:e,agent:t.agent,domain:t.domain,steps:[],startedAt:r,context:t.context});let i=this.prepared.get("insertTrajectory");return i&&i.run(n,e,t.agent||null,t.domain||null,r.toISOString(),t.context?JSON.stringify(t.context):null),this.stats.trajectoriesStarted++,setTimeout(()=>{this.activeTrajectories.has(n)&&(console.warn(`[TrajectoryTracker] Auto-ending abandoned trajectory: ${n}`),this.endTrajectory(n,!1,"Abandoned - timeout").catch(console.error),this.stats.trajectoriesAbandoned++)},this.config.autoEndTimeoutMs),n}async recordStep(e,t,n,r={}){this.ensureInitialized();let i=this.activeTrajectories.get(e);if(!i)throw new Error(`Trajectory not found or already ended: ${e}`);if(i.steps.length>=this.config.maxStepsPerTrajectory)throw new Error(`Maximum steps (${this.config.maxStepsPerTrajectory}) exceeded for trajectory`);let s=N(),a=r.quality??this.calculateStepQuality(n);t=Q(t),n={...n,data:n.data?wt(n.data):n.data,error:n.error?Q(n.error):n.error};let o={id:s,action:t,result:n,quality:a,durationMs:r.durationMs??0,timestamp:new Date,context:r.context,tokensUsed:r.tokensUsed};i.steps.push(o);let u=this.prepared.get("insertStep");u&&u.run(s,e,i.steps.length-1,t,n.outcome,a,r.durationMs??0,r.tokensUsed??null,n.data?JSON.stringify(n.data):null,n.error??null,n.metrics?JSON.stringify(n.metrics):null,r.context?JSON.stringify(r.context):null),this.stats.totalStepsRecorded++,this.stats.totalQualitySum+=a,this.stats.averageQuality=this.stats.totalQualitySum/this.stats.totalStepsRecorded}async endTrajectory(e,t,n){this.ensureInitialized();let r=this.activeTrajectories.get(e);if(!r)throw new Error(`Trajectory not found or already ended: ${e}`);let i=new Date,s=this.calculateMetrics(r.steps),a;t&&s.averageQuality>=this.config.minQualityThreshold?a="success":t?a="partial":a="failure";let o={id:e,task:r.task,agent:r.agent,domain:r.domain,steps:r.steps,outcome:a,metrics:s,startedAt:r.startedAt,endedAt:i,feedback:n},u=this.prepared.get("updateTrajectory");return u&&u.run(i.toISOString(),t?1:0,JSON.stringify(r.steps),JSON.stringify({metrics:s,context:r.context}),null,n??null,null,e),this.activeTrajectories.delete(e),this.recentTrajectories.push(o),this.stats.trajectoriesCompleted++,o}async getTrajectory(e){this.ensureInitialized();let t=this.activeTrajectories.get(e);if(t)return{id:t.id,task:t.task,agent:t.agent,domain:t.domain,steps:t.steps,outcome:"partial",metrics:this.calculateMetrics(t.steps),startedAt:t.startedAt};let n=this.prepared.get("getTrajectory");if(!n)return null;let r=n.get(e);return r?this.rowToTrajectory(r):null}async getSuccessfulTrajectories(e,t=10){this.ensureInitialized();let n=this.prepared.get("getTrajectoryByDomain");if(!n)return[];let r=n.all(e,t),i=[];for(let s of r){let a=await this.rowToTrajectory(s);a&&i.push(a)}return i}async findSimilarTrajectories(e,t=5){this.ensureInitialized();let n=e.toLowerCase().split(/\s+/).filter(s=>s.length>3);return this.recentTrajectories.toArray().map(s=>{let a=s.task.toLowerCase(),o=n.filter(u=>a.includes(u)).length;return{trajectory:s,score:o/n.length}}).filter(s=>s.score>.2).sort((s,a)=>a.score-s.score).slice(0,t).map(s=>s.trajectory)}getStats(){return{...this.stats,activeTrajectories:this.activeTrajectories.size,recentBufferSize:this.recentTrajectories.length}}async cleanup(e=30){if(this.ensureInitialized(),!this.db)return 0;let t=new Date;return t.setDate(t.getDate()-e),this.db.prepare(`
164
+ `))}async loadRecentTrajectories(){let e=this.prepared.get("getRecentTrajectories");if(!e)return;let t=e.all(this.config.recentBufferSize);for(let n of t){let r=await this.rowToTrajectory(n);r&&this.recentTrajectories.push(r)}console.log(`[TrajectoryTracker] Loaded ${t.length} recent trajectories`)}async startTrajectory(e,t={}){this.ensureInitialized(),e=Q(e);let n=N(),r=new Date;this.activeTrajectories.set(n,{id:n,task:e,agent:t.agent,domain:t.domain,steps:[],startedAt:r,context:t.context});let i=this.prepared.get("insertTrajectory");return i&&i.run(n,e,t.agent||null,t.domain||null,r.toISOString(),t.context?JSON.stringify(t.context):null),this.stats.trajectoriesStarted++,setTimeout(()=>{this.activeTrajectories.has(n)&&(console.warn(`[TrajectoryTracker] Auto-ending abandoned trajectory: ${n}`),this.endTrajectory(n,!1,"Abandoned - timeout").catch(console.error),this.stats.trajectoriesAbandoned++)},this.config.autoEndTimeoutMs),n}async recordStep(e,t,n,r={}){this.ensureInitialized();let i=this.activeTrajectories.get(e);if(!i)throw new Error(`Trajectory not found or already ended: ${e}`);if(i.steps.length>=this.config.maxStepsPerTrajectory)throw new Error(`Maximum steps (${this.config.maxStepsPerTrajectory}) exceeded for trajectory`);let s=N(),a=r.quality??this.calculateStepQuality(n);t=Q(t),n={...n,data:n.data?Rt(n.data):n.data,error:n.error?Q(n.error):n.error};let o={id:s,action:t,result:n,quality:a,durationMs:r.durationMs??0,timestamp:new Date,context:r.context,tokensUsed:r.tokensUsed};i.steps.push(o);let u=this.prepared.get("insertStep");u&&u.run(s,e,i.steps.length-1,t,n.outcome,a,r.durationMs??0,r.tokensUsed??null,n.data?JSON.stringify(n.data):null,n.error??null,n.metrics?JSON.stringify(n.metrics):null,r.context?JSON.stringify(r.context):null),this.stats.totalStepsRecorded++,this.stats.totalQualitySum+=a,this.stats.averageQuality=this.stats.totalQualitySum/this.stats.totalStepsRecorded}async endTrajectory(e,t,n){this.ensureInitialized();let r=this.activeTrajectories.get(e);if(!r)throw new Error(`Trajectory not found or already ended: ${e}`);let i=new Date,s=this.calculateMetrics(r.steps),a;t&&s.averageQuality>=this.config.minQualityThreshold?a="success":t?a="partial":a="failure";let o={id:e,task:r.task,agent:r.agent,domain:r.domain,steps:r.steps,outcome:a,metrics:s,startedAt:r.startedAt,endedAt:i,feedback:n},u=this.prepared.get("updateTrajectory");return u&&u.run(i.toISOString(),t?1:0,JSON.stringify(r.steps),JSON.stringify({metrics:s,context:r.context}),null,n??null,null,e),this.activeTrajectories.delete(e),this.recentTrajectories.push(o),this.stats.trajectoriesCompleted++,o}async getTrajectory(e){this.ensureInitialized();let t=this.activeTrajectories.get(e);if(t)return{id:t.id,task:t.task,agent:t.agent,domain:t.domain,steps:t.steps,outcome:"partial",metrics:this.calculateMetrics(t.steps),startedAt:t.startedAt};let n=this.prepared.get("getTrajectory");if(!n)return null;let r=n.get(e);return r?this.rowToTrajectory(r):null}async getSuccessfulTrajectories(e,t=10){this.ensureInitialized();let n=this.prepared.get("getTrajectoryByDomain");if(!n)return[];let r=n.all(e,t),i=[];for(let s of r){let a=await this.rowToTrajectory(s);a&&i.push(a)}return i}async findSimilarTrajectories(e,t=5){this.ensureInitialized();let n=e.toLowerCase().split(/\s+/).filter(s=>s.length>3);return this.recentTrajectories.toArray().map(s=>{let a=s.task.toLowerCase(),o=n.filter(u=>a.includes(u)).length;return{trajectory:s,score:o/n.length}}).filter(s=>s.score>.2).sort((s,a)=>a.score-s.score).slice(0,t).map(s=>s.trajectory)}getStats(){return{...this.stats,activeTrajectories:this.activeTrajectories.size,recentBufferSize:this.recentTrajectories.length}}async cleanup(e=30){if(this.ensureInitialized(),!this.db)return 0;let t=new Date;return t.setDate(t.getDate()-e),this.db.prepare(`
165
165
  DELETE FROM qe_trajectories WHERE ended_at < ?
166
- `).run(t.toISOString()).changes}async dispose(){this.activeTrajectories.clear(),this.recentTrajectories.clear(),this.prepared.clear(),this.db=null,this.unifiedMemory=null,this.initialized=!1,console.log("[TrajectoryTracker] Disposed")}ensureInitialized(){if(!this.initialized)throw new Error("TrajectoryTracker not initialized. Call initialize() first.")}calculateStepQuality(e){switch(e.outcome){case"success":return 1;case"partial":return .6;case"skipped":return .5;case"failure":return 0;default:return .5}}calculateMetrics(e){if(e.length===0)return{totalDurationMs:0,successfulSteps:0,failedSteps:0,averageQuality:0,totalTokensUsed:0,efficiencyScore:0};let t=0,n=0,r=0,i=0,s=0;for(let l of e)t+=l.durationMs,i+=l.quality,s+=l.tokensUsed??0,l.result.outcome==="success"?n++:l.result.outcome==="failure"&&r++;let a=i/e.length,u=n/e.length*a;return{totalDurationMs:t,successfulSteps:n,failedSteps:r,averageQuality:a,totalTokensUsed:s,efficiencyScore:u}}async rowToTrajectory(e){if(!e)return null;let t=this.prepared.get("getSteps"),n=[];if(t)n=t.all(e.id).map(a=>({id:a.id,action:a.action,result:{outcome:a.outcome,data:a.result_data?A(a.result_data):void 0,error:a.error_message??void 0,metrics:a.metrics_json?A(a.metrics_json):void 0},quality:a.quality,durationMs:a.duration_ms,timestamp:new Date(a.timestamp),context:a.context_json?A(a.context_json):void 0,tokensUsed:a.tokens_used??void 0}));else if(e.steps_json)try{n=A(e.steps_json)}catch{n=[]}let i=(e.metadata_json?A(e.metadata_json):{}).metrics??this.calculateMetrics(n);return{id:e.id,task:e.task,agent:e.agent??void 0,domain:e.domain,steps:n,outcome:e.success===1?"success":e.success===0?"failure":"partial",metrics:i,startedAt:new Date(e.started_at),endedAt:e.ended_at?new Date(e.ended_at):void 0,feedback:e.feedback??void 0,embedding:e.embedding?this.bufferToFloatArray(e.embedding):void 0,relatedPatternIds:e.related_patterns?A(e.related_patterns):void 0}}bufferToFloatArray(e){let t=e.length/4,n=[];for(let r=0;r<t;r++)n.push(e.readFloatLE(r*4));return n}};function kn(c={}){return new Rt(c)}ie();H();vt();var pa={minQualityThreshold:.6,maxExperiencesPerDomain:500,similarityThreshold:.7,topK:5,embedding:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0},autoPrune:!0,pruneThreshold:.3},Pt=class{config;unifiedMemory=null;db=null;prepared=new Map;initialized=!1;hnswIndex;idToExperienceId=new Map;experienceIdToHnswId=new Map;nextHnswId=0;recentExperiences;reservoirBuffer=null;stats={experiencesStored:0,experiencesApplied:0,totalTokensSaved:0,avgSimilarityOnRetrieval:0,totalRetrievals:0};constructor(e={}){this.config={...pa,...e},this.recentExperiences=new be(100),this.hnswIndex=new si({dimension:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"})}async initialize(){this.initialized||(this.unifiedMemory=j(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),this.ensureSchema(),this.prepareStatements(),await this.loadEmbeddingIndex(),(async()=>{try{if(!this.db)return;let e=this.db.prepare(`
166
+ `).run(t.toISOString()).changes}async dispose(){this.activeTrajectories.clear(),this.recentTrajectories.clear(),this.prepared.clear(),this.db=null,this.unifiedMemory=null,this.initialized=!1,console.log("[TrajectoryTracker] Disposed")}ensureInitialized(){if(!this.initialized)throw new Error("TrajectoryTracker not initialized. Call initialize() first.")}calculateStepQuality(e){switch(e.outcome){case"success":return 1;case"partial":return .6;case"skipped":return .5;case"failure":return 0;default:return .5}}calculateMetrics(e){if(e.length===0)return{totalDurationMs:0,successfulSteps:0,failedSteps:0,averageQuality:0,totalTokensUsed:0,efficiencyScore:0};let t=0,n=0,r=0,i=0,s=0;for(let l of e)t+=l.durationMs,i+=l.quality,s+=l.tokensUsed??0,l.result.outcome==="success"?n++:l.result.outcome==="failure"&&r++;let a=i/e.length,u=n/e.length*a;return{totalDurationMs:t,successfulSteps:n,failedSteps:r,averageQuality:a,totalTokensUsed:s,efficiencyScore:u}}async rowToTrajectory(e){if(!e)return null;let t=this.prepared.get("getSteps"),n=[];if(t)n=t.all(e.id).map(a=>({id:a.id,action:a.action,result:{outcome:a.outcome,data:a.result_data?A(a.result_data):void 0,error:a.error_message??void 0,metrics:a.metrics_json?A(a.metrics_json):void 0},quality:a.quality,durationMs:a.duration_ms,timestamp:new Date(a.timestamp),context:a.context_json?A(a.context_json):void 0,tokensUsed:a.tokens_used??void 0}));else if(e.steps_json)try{n=A(e.steps_json)}catch{n=[]}let i=(e.metadata_json?A(e.metadata_json):{}).metrics??this.calculateMetrics(n);return{id:e.id,task:e.task,agent:e.agent??void 0,domain:e.domain,steps:n,outcome:e.success===1?"success":e.success===0?"failure":"partial",metrics:i,startedAt:new Date(e.started_at),endedAt:e.ended_at?new Date(e.ended_at):void 0,feedback:e.feedback??void 0,embedding:e.embedding?this.bufferToFloatArray(e.embedding):void 0,relatedPatternIds:e.related_patterns?A(e.related_patterns):void 0}}bufferToFloatArray(e){let t=e.length/4,n=[];for(let r=0;r<t;r++)n.push(e.readFloatLE(r*4));return n}};function Dn(c={}){return new Pt(c)}ie();H();vt();var ba={minQualityThreshold:.6,maxExperiencesPerDomain:500,similarityThreshold:.7,topK:5,embedding:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0},autoPrune:!0,pruneThreshold:.3},xt=class{config;unifiedMemory=null;db=null;prepared=new Map;initialized=!1;hnswIndex;idToExperienceId=new Map;experienceIdToHnswId=new Map;nextHnswId=0;recentExperiences;reservoirBuffer=null;stats={experiencesStored:0,experiencesApplied:0,totalTokensSaved:0,avgSimilarityOnRetrieval:0,totalRetrievals:0};constructor(e={}){this.config={...ba,...e},this.recentExperiences=new be(100),this.hnswIndex=new di({dimension:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"})}async initialize(){this.initialized||(this.unifiedMemory=j(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),this.ensureSchema(),this.prepareStatements(),await this.loadEmbeddingIndex(),(async()=>{try{if(!this.db)return;let e=this.db.prepare(`
167
167
  SELECT id, domain, task FROM captured_experiences
168
168
  WHERE embedding IS NULL AND consolidated_into IS NULL
169
169
  LIMIT 200
@@ -175,7 +175,7 @@ ${e.recommendations.length===0?"No recommendations - all quality gates passed.":
175
175
  SELECT id, domain, task FROM qe_trajectories
176
176
  WHERE embedding IS NULL AND ended_at IS NOT NULL
177
177
  LIMIT 200
178
- `).all();if(t.length===0)return;let n=this.db.prepare("UPDATE qe_trajectories SET embedding = ? WHERE id = ?"),r=0;for(let i of t){let s=Q(`${i.domain??""}: ${i.task}`).slice(0,512),a=await Se(s);n.run(Buffer.from(new Float32Array(a).buffer),i.id),r++}console.log(`[ExperienceReplay] Backfilled ${r} qe_trajectories embeddings`)}catch(e){console.warn("[ExperienceReplay] Trajectory embedding backfill failed:",e instanceof Error?e.message:e)}})(),Te().useReservoirReplay&&(this.reservoirBuffer=new zr({capacity:1e4}),console.log("[ExperienceReplay] Reservoir replay buffer enabled")),this.initialized=!0,console.log("[ExperienceReplay] Initialized"))}ensureSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
178
+ `).all();if(t.length===0)return;let n=this.db.prepare("UPDATE qe_trajectories SET embedding = ? WHERE id = ?"),r=0;for(let i of t){let s=Q(`${i.domain??""}: ${i.task}`).slice(0,512),a=await Se(s);n.run(Buffer.from(new Float32Array(a).buffer),i.id),r++}console.log(`[ExperienceReplay] Backfilled ${r} qe_trajectories embeddings`)}catch(e){console.warn("[ExperienceReplay] Trajectory embedding backfill failed:",e instanceof Error?e.message:e)}})(),Te().useReservoirReplay&&(this.reservoirBuffer=new Qr({capacity:1e4}),console.log("[ExperienceReplay] Reservoir replay buffer enabled")),this.initialized=!0,console.log("[ExperienceReplay] Initialized"))}ensureSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
179
179
  CREATE TABLE IF NOT EXISTS captured_experiences (
180
180
  id TEXT PRIMARY KEY,
181
181
  task TEXT NOT NULL,
@@ -249,7 +249,7 @@ ${e.recommendations.length===0?"No recommendations - all quality gates passed.":
249
249
  VALUES (?, ?, ?, ?, ?, ?)
250
250
  `)),this.prepared.set("countByDomain",this.db.prepare(`
251
251
  SELECT domain, COUNT(*) as count FROM captured_experiences WHERE consolidated_into IS NULL GROUP BY domain
252
- `))}async loadEmbeddingIndex(){let e=this.prepared.get("getAllEmbeddings");if(!e)return;let t=e.all();this.idToExperienceId.clear(),this.experienceIdToHnswId.clear(),this.hnswIndex.clearIndex("experiences"),this.nextHnswId=0;for(let n of t)if(n.embedding&&n.embedding_dimension){let r=this.bufferToFloatArray(n.embedding,n.embedding_dimension),i=this.nextHnswId++,s={vector:r,dimension:384,namespace:"experiences",text:n.id,timestamp:Date.now(),quantization:"none",metadata:{}};this.hnswIndex.addEmbedding(s,i),this.idToExperienceId.set(i,n.id),this.experienceIdToHnswId.set(n.id,i)}console.log(`[ExperienceReplay] Loaded ${this.idToExperienceId.size} embeddings into HNSW index`)}async storeExperience(e,t,n=[]){if(this.ensureInitialized(),e.metrics.efficiencyScore<this.config.minQualityThreshold)return console.log(`[ExperienceReplay] Trajectory quality too low: ${e.metrics.efficiencyScore}`),null;let r=Q(e.task);t=Q(t);let i=e.steps.filter(m=>m.result.outcome==="success").map(m=>Q(m.action)),s=`${r} ${t} ${i.join(" ")}`,a=await Se(s,this.config.embedding),o=N(),u=e.domain||"test-generation",l={id:o,trajectoryId:e.id,task:r,domain:u,strategy:t,keyActions:i,qualityScore:e.metrics.efficiencyScore,applicationCount:0,successRate:1,avgTokenSavings:0,embedding:a,createdAt:new Date,originalMetrics:e.metrics,tags:n},d=this.prepared.get("insertExperience");if(d){let m=a?this.floatArrayToBuffer(a):null;d.run(o,r,t,u,e.metrics.efficiencyScore,JSON.stringify(i),JSON.stringify(e.metrics),m,a?.length??null,JSON.stringify(n))}if(a){let m=this.nextHnswId++,p={vector:a,dimension:384,namespace:"experiences",text:o,timestamp:Date.now(),quantization:"none",metadata:{}};this.hnswIndex.addEmbedding(p,m),this.idToExperienceId.set(m,o),this.experienceIdToHnswId.set(o,m)}return this.recentExperiences.push(l),this.reservoirBuffer&&this.reservoirBuffer.admit(l.id,l,l.qualityScore),this.stats.experiencesStored++,this.config.autoPrune&&await this.autoConsolidate(u),l}async getGuidance(e,t){this.ensureInitialized();let n=await this.findSimilarExperiences(e,t);if(this.reservoirBuffer&&this.reservoirBuffer.size()>0){let p=this.reservoirBuffer.sample(Math.max(2,Math.floor(this.config.topK/2)),.6);for(let g of p){let h=g.data;n.some(f=>f.experience.id===h.id)||t&&h.domain!==t||n.push({experience:h,similarity:g.coherenceScore*.8})}}if(n.length===0)return null;this.stats.totalRetrievals++;let r=n.reduce((p,g)=>p+g.similarity,0)/n.length;this.stats.avgSimilarityOnRetrieval=(this.stats.avgSimilarityOnRetrieval*(this.stats.totalRetrievals-1)+r)/this.stats.totalRetrievals;let i=n.map(p=>({...p,weight:p.similarity*p.experience.qualityScore}));i.sort((p,g)=>g.weight-p.weight);let a=i[0].experience.strategy,o=new Map;for(let p of i)for(let g of p.experience.keyActions)o.set(g,(o.get(g)||0)+p.weight);let u=Array.from(o.entries()).sort((p,g)=>g[1]-p[1]).slice(0,5).map(([p])=>p),l=[],d=i.reduce((p,g)=>p+g.weight,0)/i.length,m=i.reduce((p,g)=>p+g.experience.avgTokenSavings*g.similarity,0)/i.length;return{recommendedStrategy:a,suggestedActions:u,pitfallsToAvoid:l,confidence:Math.min(d,1),sourceExperiences:i.slice(0,3).map(p=>({id:p.experience.id,similarity:p.similarity,qualityScore:p.experience.qualityScore})),estimatedTokenSavings:m}}async findSimilarExperiences(e,t,n){this.ensureInitialized();let r=n??this.config.topK;if(this.idToExperienceId.size===0)return[];e=Q(e);let s={vector:await Se(e,this.config.embedding),dimension:384,namespace:"experiences",text:e,timestamp:Date.now(),quantization:"none",metadata:{}},a=t?r*4:r*2,o=this.hnswIndex.search(s,{limit:a,namespace:"experiences"}),u=[],l=this.prepared.get("getExperience");for(let{id:d,distance:m}of o){let p=1-m;if(p<this.config.similarityThreshold)continue;let g=this.idToExperienceId.get(d);if(g&&l){let h=l.get(g);if(h){if(t&&h.domain!==t)continue;let f=this.rowToExperience(h);if(f&&(u.push({experience:f,similarity:p}),u.length>=r))break}}}return u}async recordApplication(e,t,n,r=0,i){this.ensureInitialized();let s=this.prepared.get("updateApplication");s&&s.run(r,e);let a=this.prepared.get("insertApplication");a&&a.run(N(),e,t,n?1:0,r,i??null),this.stats.experiencesApplied++,this.stats.totalTokensSaved+=r}async getExperience(e){this.ensureInitialized();let t=this.prepared.get("getExperience");if(!t)return null;let n=t.get(e);return n?this.rowToExperience(n):null}async getExperiencesByDomain(e,t=10){this.ensureInitialized();let n=this.prepared.get("getExperiencesByDomain");return n?n.all(e,t).map(i=>this.rowToExperience(i)).filter(i=>i!==null):[]}async autoConsolidate(e){if(!this.db)return 0;let t=this.prepared.get("countByDomain");if(!t)return 0;let r=t.all().find(i=>i.domain===e)?.count??0;if(r>400)try{let i=new ai;await i.initialize(this.db);let s=await i.consolidateDomain(e,r);return s.merged>0&&await this.loadEmbeddingIndex(),console.log(`[ExperienceReplay] Auto-consolidated ${e}: ${s.merged} merged, ${s.archived} archived`),s.merged+s.archived}catch(i){console.warn("[ExperienceReplay] Auto-consolidation failed, skipping:",i)}return 0}async recordReuse(e,t){if(this.ensureInitialized(),!this.db)return;let n=t?"reuse_success_count":"reuse_failure_count";try{this.db.prepare(`UPDATE captured_experiences SET ${n} = ${n} + 1 WHERE id = ?`).run(e)}catch{}}getStats(){return{...this.stats,embeddingIndexSize:this.idToExperienceId.size,hnswIndexSize:this.hnswIndex.getSize("experiences"),recentBufferSize:this.recentExperiences.length}}getReservoirStats(){if(!this.reservoirBuffer)return null;let e=this.reservoirBuffer.getStats();return{size:e.size,totalAdmitted:e.totalAdmitted,totalRejected:e.totalRejected,tierCounts:e.tierCounts}}async dispose(){this.hnswIndex.clearIndex("experiences"),this.idToExperienceId.clear(),this.experienceIdToHnswId.clear(),this.recentExperiences.clear(),this.prepared.clear(),this.db=null,this.unifiedMemory=null,this.initialized=!1,console.log("[ExperienceReplay] Disposed")}ensureInitialized(){if(!this.initialized)throw new Error("ExperienceReplay not initialized. Call initialize() first.")}rowToExperience(e){return e?{id:e.id,trajectoryId:e.id,task:e.task,domain:e.domain,strategy:e.agent,keyActions:A(e.steps_json||"[]"),qualityScore:e.quality,applicationCount:e.application_count??0,successRate:e.success?1:0,avgTokenSavings:e.avg_token_savings??0,embedding:e.embedding&&e.embedding_dimension?this.bufferToFloatArray(e.embedding,e.embedding_dimension):void 0,createdAt:new Date(e.started_at),lastAppliedAt:e.last_applied_at?new Date(e.last_applied_at):void 0,originalMetrics:A(e.routing_json||"{}"),tags:A(e.tags||"[]")}:null}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 Mn(c={}){return new Pt(c)}ie();H();var ga={driftThreshold:.3,mergeSimilarityThreshold:.85,minQualityForRetention:.3,obsoleteDaysThreshold:60,maxPatternsPerDomain:200,embedding:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0},historyBufferSize:500},xt=class{config;unifiedMemory=null;db=null;prepared=new Map;initialized=!1;embeddingCache=new Map;recentEvents;stats={versionsTracked:0,driftDetections:0,significantDrifts:0,patternsMerged:0,patternsPruned:0,consolidationRuns:0};constructor(e={}){this.config={...ga,...e},this.recentEvents=new be(this.config.historyBufferSize)}async initialize(){this.initialized||(this.unifiedMemory=j(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),this.ensureSchema(),this.prepareStatements(),await this.loadEmbeddingCache(),this.initialized=!0,console.log("[PatternEvolution] Initialized"))}ensureSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
252
+ `))}async loadEmbeddingIndex(){let e=this.prepared.get("getAllEmbeddings");if(!e)return;let t=e.all();this.idToExperienceId.clear(),this.experienceIdToHnswId.clear(),this.hnswIndex.clearIndex("experiences"),this.nextHnswId=0;for(let n of t)if(n.embedding&&n.embedding_dimension){let r=this.bufferToFloatArray(n.embedding,n.embedding_dimension),i=this.nextHnswId++,s={vector:r,dimension:384,namespace:"experiences",text:n.id,timestamp:Date.now(),quantization:"none",metadata:{}};this.hnswIndex.addEmbedding(s,i),this.idToExperienceId.set(i,n.id),this.experienceIdToHnswId.set(n.id,i)}console.log(`[ExperienceReplay] Loaded ${this.idToExperienceId.size} embeddings into HNSW index`)}async storeExperience(e,t,n=[]){if(this.ensureInitialized(),e.metrics.efficiencyScore<this.config.minQualityThreshold)return console.log(`[ExperienceReplay] Trajectory quality too low: ${e.metrics.efficiencyScore}`),null;let r=Q(e.task);t=Q(t);let i=e.steps.filter(m=>m.result.outcome==="success").map(m=>Q(m.action)),s=`${r} ${t} ${i.join(" ")}`,a=await Se(s,this.config.embedding),o=N(),u=e.domain||"test-generation",l={id:o,trajectoryId:e.id,task:r,domain:u,strategy:t,keyActions:i,qualityScore:e.metrics.efficiencyScore,applicationCount:0,successRate:1,avgTokenSavings:0,embedding:a,createdAt:new Date,originalMetrics:e.metrics,tags:n},d=this.prepared.get("insertExperience");if(d){let m=a?this.floatArrayToBuffer(a):null;d.run(o,r,t,u,e.metrics.efficiencyScore,JSON.stringify(i),JSON.stringify(e.metrics),m,a?.length??null,JSON.stringify(n))}if(a){let m=this.nextHnswId++,p={vector:a,dimension:384,namespace:"experiences",text:o,timestamp:Date.now(),quantization:"none",metadata:{}};this.hnswIndex.addEmbedding(p,m),this.idToExperienceId.set(m,o),this.experienceIdToHnswId.set(o,m)}return this.recentExperiences.push(l),this.reservoirBuffer&&this.reservoirBuffer.admit(l.id,l,l.qualityScore),this.stats.experiencesStored++,this.config.autoPrune&&await this.autoConsolidate(u),l}async getGuidance(e,t){this.ensureInitialized();let n=await this.findSimilarExperiences(e,t);if(this.reservoirBuffer&&this.reservoirBuffer.size()>0){let p=this.reservoirBuffer.sample(Math.max(2,Math.floor(this.config.topK/2)),.6);for(let g of p){let h=g.data;n.some(f=>f.experience.id===h.id)||t&&h.domain!==t||n.push({experience:h,similarity:g.coherenceScore*.8})}}if(n.length===0)return null;this.stats.totalRetrievals++;let r=n.reduce((p,g)=>p+g.similarity,0)/n.length;this.stats.avgSimilarityOnRetrieval=(this.stats.avgSimilarityOnRetrieval*(this.stats.totalRetrievals-1)+r)/this.stats.totalRetrievals;let i=n.map(p=>({...p,weight:p.similarity*p.experience.qualityScore}));i.sort((p,g)=>g.weight-p.weight);let a=i[0].experience.strategy,o=new Map;for(let p of i)for(let g of p.experience.keyActions)o.set(g,(o.get(g)||0)+p.weight);let u=Array.from(o.entries()).sort((p,g)=>g[1]-p[1]).slice(0,5).map(([p])=>p),l=[],d=i.reduce((p,g)=>p+g.weight,0)/i.length,m=i.reduce((p,g)=>p+g.experience.avgTokenSavings*g.similarity,0)/i.length;return{recommendedStrategy:a,suggestedActions:u,pitfallsToAvoid:l,confidence:Math.min(d,1),sourceExperiences:i.slice(0,3).map(p=>({id:p.experience.id,similarity:p.similarity,qualityScore:p.experience.qualityScore})),estimatedTokenSavings:m}}async findSimilarExperiences(e,t,n){this.ensureInitialized();let r=n??this.config.topK;if(this.idToExperienceId.size===0)return[];e=Q(e);let s={vector:await Se(e,this.config.embedding),dimension:384,namespace:"experiences",text:e,timestamp:Date.now(),quantization:"none",metadata:{}},a=t?r*4:r*2,o=this.hnswIndex.search(s,{limit:a,namespace:"experiences"}),u=[],l=this.prepared.get("getExperience");for(let{id:d,distance:m}of o){let p=1-m;if(p<this.config.similarityThreshold)continue;let g=this.idToExperienceId.get(d);if(g&&l){let h=l.get(g);if(h){if(t&&h.domain!==t)continue;let f=this.rowToExperience(h);if(f&&(u.push({experience:f,similarity:p}),u.length>=r))break}}}return u}async recordApplication(e,t,n,r=0,i){this.ensureInitialized();let s=this.prepared.get("updateApplication");s&&s.run(r,e);let a=this.prepared.get("insertApplication");a&&a.run(N(),e,t,n?1:0,r,i??null),this.stats.experiencesApplied++,this.stats.totalTokensSaved+=r}async getExperience(e){this.ensureInitialized();let t=this.prepared.get("getExperience");if(!t)return null;let n=t.get(e);return n?this.rowToExperience(n):null}async getExperiencesByDomain(e,t=10){this.ensureInitialized();let n=this.prepared.get("getExperiencesByDomain");return n?n.all(e,t).map(i=>this.rowToExperience(i)).filter(i=>i!==null):[]}async autoConsolidate(e){if(!this.db)return 0;let t=this.prepared.get("countByDomain");if(!t)return 0;let r=t.all().find(i=>i.domain===e)?.count??0;if(r>400)try{let i=new mi;await i.initialize(this.db);let s=await i.consolidateDomain(e,r);return s.merged>0&&await this.loadEmbeddingIndex(),console.log(`[ExperienceReplay] Auto-consolidated ${e}: ${s.merged} merged, ${s.archived} archived`),s.merged+s.archived}catch(i){console.warn("[ExperienceReplay] Auto-consolidation failed, skipping:",i)}return 0}async recordReuse(e,t){if(this.ensureInitialized(),!this.db)return;let n=t?"reuse_success_count":"reuse_failure_count";try{this.db.prepare(`UPDATE captured_experiences SET ${n} = ${n} + 1 WHERE id = ?`).run(e)}catch{}}getStats(){return{...this.stats,embeddingIndexSize:this.idToExperienceId.size,hnswIndexSize:this.hnswIndex.getSize("experiences"),recentBufferSize:this.recentExperiences.length}}getReservoirStats(){if(!this.reservoirBuffer)return null;let e=this.reservoirBuffer.getStats();return{size:e.size,totalAdmitted:e.totalAdmitted,totalRejected:e.totalRejected,tierCounts:e.tierCounts}}async dispose(){this.hnswIndex.clearIndex("experiences"),this.idToExperienceId.clear(),this.experienceIdToHnswId.clear(),this.recentExperiences.clear(),this.prepared.clear(),this.db=null,this.unifiedMemory=null,this.initialized=!1,console.log("[ExperienceReplay] Disposed")}ensureInitialized(){if(!this.initialized)throw new Error("ExperienceReplay not initialized. Call initialize() first.")}rowToExperience(e){return e?{id:e.id,trajectoryId:e.id,task:e.task,domain:e.domain,strategy:e.agent,keyActions:A(e.steps_json||"[]"),qualityScore:e.quality,applicationCount:e.application_count??0,successRate:e.success?1:0,avgTokenSavings:e.avg_token_savings??0,embedding:e.embedding&&e.embedding_dimension?this.bufferToFloatArray(e.embedding,e.embedding_dimension):void 0,createdAt:new Date(e.started_at),lastAppliedAt:e.last_applied_at?new Date(e.last_applied_at):void 0,originalMetrics:A(e.routing_json||"{}"),tags:A(e.tags||"[]")}:null}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 In(c={}){return new xt(c)}ie();H();var Ca={driftThreshold:.3,mergeSimilarityThreshold:.85,minQualityForRetention:.3,obsoleteDaysThreshold:60,maxPatternsPerDomain:200,embedding:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0},historyBufferSize:500},At=class{config;unifiedMemory=null;db=null;prepared=new Map;initialized=!1;embeddingCache=new Map;recentEvents;stats={versionsTracked:0,driftDetections:0,significantDrifts:0,patternsMerged:0,patternsPruned:0,consolidationRuns:0};constructor(e={}){this.config={...Ca,...e},this.recentEvents=new be(this.config.historyBufferSize)}async initialize(){this.initialized||(this.unifiedMemory=j(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),this.ensureSchema(),this.prepareStatements(),await this.loadEmbeddingCache(),this.initialized=!0,console.log("[PatternEvolution] Initialized"))}ensureSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
253
253
  CREATE TABLE IF NOT EXISTS pattern_versions (
254
254
  id TEXT PRIMARY KEY,
255
255
  pattern_id TEXT NOT NULL,
@@ -330,7 +330,7 @@ ${e.recommendations.length===0?"No recommendations - all quality gates passed.":
330
330
  WHERE id = ?
331
331
  `).run(u,l,d,a.id);let m=this.prepared.get("insertRelationship");return m&&m.run(N(),o.id,a.id,"merged",1),this.db.prepare("UPDATE qe_patterns SET tier = 'archived' WHERE id = ?").run(o.id),await this.recordEvent(a.id,"merged",{absorbedFrom:o.id}),await this.recordEvent(o.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(`
332
332
  SELECT COUNT(*) as count FROM qe_patterns WHERE qe_domain = ? AND tier != 'archived'
333
- `).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(u=>({id:u.id,patternId:u.pattern_id,version:u.version,embedding:this.bufferToFloatArray(u.embedding,u.embedding_dimension),changes:A(u.changes||"[]"),qualityScore:u.quality_score,successRate:u.success_rate,timestamp:new Date(u.created_at),trigger:u.trigger})),o=(this.prepared.get("getEvents")?.all(e,t)??[]).map(u=>({id:u.id,patternId:u.pattern_id,eventType:u.event_type,details:A(u.details||"{}"),timestamp:new Date(u.created_at)}));return{versions:i,events:o}}async recordEvent(e,t,n){let r=this.prepared.get("insertEvent");if(r){let i={id:N(),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 Dn(c={}){return new xt(c)}M();var ha={base:{},trajectoryTracker:{},experienceReplay:{},patternEvolution:{},enableTrajectories:!0,enableExperienceReplay:!0,enablePatternEvolution:!0,autoStoreExperiences:!0,autoConsolidate:!0,consolidationIntervalMs:3600*1e3},In=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={...ha,...e}}async initialize(){if(this.initialized)return;let e=performance.now();this.reasoningBank=Pn(this.config.base),await this.reasoningBank.initialize(),this.config.enableTrajectories&&(this.trajectoryTracker=kn(this.config.trajectoryTracker),await this.trajectoryTracker.initialize()),this.config.enableExperienceReplay&&(this.experienceReplay=Mn(this.config.experienceReplay),await this.experienceReplay.initialize()),this.config.enablePatternEvolution&&(this.patternEvolution=Dn(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);if(r){n.experienceGuidance=r,n.guidance=[`Strategy: ${r.recommendedStrategy}`,...r.suggestedActions.map(i=>`Action: ${i}`),...n.guidance],this.stats.tokensSavedEstimate+=r.estimatedTokenSavings,this.stats.experiencesApplied++;for(let i of r.sourceExperiences)this.experienceReplay.recordApplication(i.id,e.task,!0,Math.round(r.estimatedTokenSavings)).catch(s=>{console.warn(`[EnhancedAdapter] Failed to record experience application: ${s}`)})}}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 I(n)}catch(t){return G($(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){if(this.ensureInitialized(),!this.experienceReplay)return null;let n=await this.experienceReplay.getGuidance(e,t);if(n){this.stats.experiencesApplied++;for(let r of n.sourceExperiences)this.experienceReplay.recordApplication(r.id,e,!0,Math.round(n.estimatedTokenSavings)).catch(i=>{console.warn(`[EnhancedAdapter] Failed to record experience application: ${i}`)})}return n}async recordExperienceApplication(e,t,n,r=0){this.ensureInitialized(),this.experienceReplay&&(await this.experienceReplay.recordApplication(e,t,n,r),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 du(c={}){return new In(c)}import{randomUUID as xa}from"crypto";var F=class extends Error{constructor(t,n,r){super(n);this.type=t;this.details=r;this.name="EmbeddingError"}type;details};var At=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}}},Pe=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 At(this.config.cacheSize)}async initialize(){if(!this.isInitialized)try{let{computeRealEmbedding:e}=await import("./real-embeddings-GUZDO5UN.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 F("RUNTIME_UNAVAILABLE","Failed to initialize ONNX runtime",e)}}async generate(e){if(this.isInitialized||await this.initialize(),!e||e.trim().length===0)throw new F("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 F("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 o={vector:s,dimensions:s.length,model:this.config.model,isHyperbolic:a};return this.cache.set(t,o),this.totalGenerated++,this.generationTimes.push(Date.now()-r),this.generationTimes.length>100&&this.generationTimes.shift(),o}catch(i){throw new F("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 F("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),o=this.cache.get(a);if(o)r.push(o),n++;else{let u=await this.generate(s);r.push(u)}}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 At(e.cacheSize)),t&&(this.isInitialized=!1)}getCacheKey(e){return`${this.config.model}:${this.config.hyperbolic}:${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 xe=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(l=>l.namespace===r.namespace));let s=[];for(let l of i){if(l.embedding.dimensions!==e.dimensions)continue;let d=this.calculateSimilarity(e.vector,l.embedding.vector,r.metric);(r.metric==="cosine"?d>=r.threshold:d<=r.threshold)&&s.push({stored:l,score:d})}let a=r.metric==="cosine"?-1:1;s.sort((l,d)=>a*(l.score-d.score));let u=s.slice(0,r.topK).map(({stored:l,score:d})=>({text:l.text,embedding:l.embedding,score:d,metadata:l.metadata}));return this.searchCount++,this.searchTimes.push(Date.now()-n),this.searchTimes.length>100&&this.searchTimes.shift(),u}catch(i){throw new F("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 F("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 F("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),o=0;for(let p=0;p<e.length;p++){let g=e[p]-t[p];o+=g*g}let u=2*o,l=(1-s)*(1-a);if(l<=0)return 1/0;let d=u/l;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 Ae=class{config;constructor(e={}){if(this.config={curvature:e.curvature??-1,epsilon:e.epsilon??1e-7},this.config.curvature>=0)throw new F("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(u=>u*s),o=this.norm(a);if(o>=1-this.config.epsilon)throw new F("HYPERBOLIC_ERROR",`Poincar\xE9 ball constraint violated: norm = ${o}`);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 F("HYPERBOLIC_ERROR","Point is on or outside Poincar\xE9 ball boundary");let a=2/i*Math.atanh(s)/n;return{vector:t.map(u=>u*a),dimensions:e.dimensions,model:e.model,isHyperbolic:!1}}distance(e,t){if(e.dimensions!==t.dimensions)throw new F("DIMENSION_MISMATCH","Embeddings must have same dimensions");if(!e.isHyperbolic||!t.isHyperbolic)throw new F("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),o=this.normSquared(r),l=2*this.euclideanDistanceSquared(n,r),d=(1-a)*(1-o);if(d<=this.config.epsilon)return 1/0;let m=l/d;return Math.acosh(1+m)/s}midpoint(e,t){if(e.dimensions!==t.dimensions)throw new F("DIMENSION_MISMATCH","Embeddings must have same dimensions");if(!e.isHyperbolic||!t.isHyperbolic)throw new F("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,o=1-n*i,u=1+2*n*r+n*n*i*s;if(Math.abs(u)<this.config.epsilon)throw new F("HYPERBOLIC_ERROR","M\xF6bius addition denominator is zero");return e.map((d,m)=>(a*d+o*t[m])/u)}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 F("HYPERBOLIC_ERROR","M\xF6bius scalar multiplication out of bounds");let a=Math.tanh(t*Math.atanh(s))/(r*i);return e.map(o=>o*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 F("HYPERBOLIC_ERROR","Curvature must be negative");this.config={...this.config,...e}}getConfig(){return{...this.config}}};ie();var Ve=class{generator;search;hyperbolic;isInitialized=!1;constructor(e={}){this.generator=new Pe(e.embedding),this.search=new xe,this.hyperbolic=new Ae(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 F("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=j();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()}_${xa().slice(0,9)}`}isReady(){return this.isInitialized&&this.generator.isReady()}};function Dt(c){return new Ve(c)}var On={enabled:!0,dbPath:".agentic-qe/memory.db",maxOutcomes:1e5,retentionDays:90,autoCleanup:!0,cleanupIntervalMs:3600*1e3};ie();M();H();var Fa={enabled:!0,haikuThreshold:.8,sonnetThreshold:.4,includeHealthSnapshot:!1,enableLogging:!0},_n=class{config;minCutService;constructor(e){this.config={...Fa,...e},this.minCutService=oi()}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 l=e.taskGraph||this.minCutService.buildTaskGraphFromTopology(n);a=this.minCutService.getStructuralHealth(l)}let o=Date.now()-t,u={modelTier:i,tierLabel:s,lambda:r.lambda,normalizedLambda:r.normalizedLambda,confidence:r.confidence,rationale:r.rationale,usedMinCut:!0,healthSnapshot:a,decisionTimeMs:o};return this.config.enableLogging&&this.logDecision(u),u}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 hi(c){return new _n(c)}import{existsSync as La}from"fs";import{join as Na}from"path";var It=class{id="memory";name="Pattern Memory";priority=80;maxTokens=2e3;async gather(e){let t=[];try{let n=Na(process.cwd(),".agentic-qe","memory.db");if(!La(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-6VBZQIJI.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 "),o=s.map(d=>`%${d}%`),l=i.prepare(`SELECT name, domain, description, confidence
333
+ `).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(u=>({id:u.id,patternId:u.pattern_id,version:u.version,embedding:this.bufferToFloatArray(u.embedding,u.embedding_dimension),changes:A(u.changes||"[]"),qualityScore:u.quality_score,successRate:u.success_rate,timestamp:new Date(u.created_at),trigger:u.trigger})),o=(this.prepared.get("getEvents")?.all(e,t)??[]).map(u=>({id:u.id,patternId:u.pattern_id,eventType:u.event_type,details:A(u.details||"{}"),timestamp:new Date(u.created_at)}));return{versions:i,events:o}}async recordEvent(e,t,n){let r=this.prepared.get("insertEvent");if(r){let i={id:N(),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 On(c={}){return new At(c)}k();var Ta={base:{},trajectoryTracker:{},experienceReplay:{},patternEvolution:{},enableTrajectories:!0,enableExperienceReplay:!0,enablePatternEvolution:!0,autoStoreExperiences:!0,autoConsolidate:!0,consolidationIntervalMs:3600*1e3},_n=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={...Ta,...e}}async initialize(){if(this.initialized)return;let e=performance.now();this.reasoningBank=An(this.config.base),await this.reasoningBank.initialize(),this.config.enableTrajectories&&(this.trajectoryTracker=Dn(this.config.trajectoryTracker),await this.trajectoryTracker.initialize()),this.config.enableExperienceReplay&&(this.experienceReplay=In(this.config.experienceReplay),await this.experienceReplay.initialize()),this.config.enablePatternEvolution&&(this.patternEvolution=On(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);if(r){n.experienceGuidance=r,n.guidance=[`Strategy: ${r.recommendedStrategy}`,...r.suggestedActions.map(i=>`Action: ${i}`),...n.guidance],this.stats.tokensSavedEstimate+=r.estimatedTokenSavings,this.stats.experiencesApplied++;for(let i of r.sourceExperiences)this.experienceReplay.recordApplication(i.id,e.task,!0,Math.round(r.estimatedTokenSavings)).catch(s=>{console.warn(`[EnhancedAdapter] Failed to record experience application: ${s}`)})}}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 I(n)}catch(t){return G($(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){if(this.ensureInitialized(),!this.experienceReplay)return null;let n=await this.experienceReplay.getGuidance(e,t);if(n){this.stats.experiencesApplied++;for(let r of n.sourceExperiences)this.experienceReplay.recordApplication(r.id,e,!0,Math.round(n.estimatedTokenSavings)).catch(i=>{console.warn(`[EnhancedAdapter] Failed to record experience application: ${i}`)})}return n}async recordExperienceApplication(e,t,n,r=0){this.ensureInitialized(),this.experienceReplay&&(await this.experienceReplay.recordApplication(e,t,n,r),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 vu(c={}){return new _n(c)}import{randomUUID as Oa}from"crypto";var L=class extends Error{constructor(t,n,r){super(n);this.type=t;this.details=r;this.name="EmbeddingError"}type;details};var kt=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}}},Pe=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 kt(this.config.cacheSize)}async initialize(){if(!this.isInitialized)try{let{computeRealEmbedding:e}=await import("./real-embeddings-ZFFDV6HC.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 L("RUNTIME_UNAVAILABLE","Failed to initialize ONNX runtime",e)}}async generate(e){if(this.isInitialized||await this.initialize(),!e||e.trim().length===0)throw new L("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 L("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 o={vector:s,dimensions:s.length,model:this.config.model,isHyperbolic:a};return this.cache.set(t,o),this.totalGenerated++,this.generationTimes.push(Date.now()-r),this.generationTimes.length>100&&this.generationTimes.shift(),o}catch(i){throw new L("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 L("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),o=this.cache.get(a);if(o)r.push(o),n++;else{let u=await this.generate(s);r.push(u)}}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 kt(e.cacheSize)),t&&(this.isInitialized=!1)}getCacheKey(e){return`${this.config.model}:${this.config.hyperbolic}:${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 xe=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(l=>l.namespace===r.namespace));let s=[];for(let l of i){if(l.embedding.dimensions!==e.dimensions)continue;let d=this.calculateSimilarity(e.vector,l.embedding.vector,r.metric);(r.metric==="cosine"?d>=r.threshold:d<=r.threshold)&&s.push({stored:l,score:d})}let a=r.metric==="cosine"?-1:1;s.sort((l,d)=>a*(l.score-d.score));let u=s.slice(0,r.topK).map(({stored:l,score:d})=>({text:l.text,embedding:l.embedding,score:d,metadata:l.metadata}));return this.searchCount++,this.searchTimes.push(Date.now()-n),this.searchTimes.length>100&&this.searchTimes.shift(),u}catch(i){throw new L("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 L("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 L("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),o=0;for(let p=0;p<e.length;p++){let g=e[p]-t[p];o+=g*g}let u=2*o,l=(1-s)*(1-a);if(l<=0)return 1/0;let d=u/l;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 Ae=class{config;constructor(e={}){if(this.config={curvature:e.curvature??-1,epsilon:e.epsilon??1e-7},this.config.curvature>=0)throw new L("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(u=>u*s),o=this.norm(a);if(o>=1-this.config.epsilon)throw new L("HYPERBOLIC_ERROR",`Poincar\xE9 ball constraint violated: norm = ${o}`);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 L("HYPERBOLIC_ERROR","Point is on or outside Poincar\xE9 ball boundary");let a=2/i*Math.atanh(s)/n;return{vector:t.map(u=>u*a),dimensions:e.dimensions,model:e.model,isHyperbolic:!1}}distance(e,t){if(e.dimensions!==t.dimensions)throw new L("DIMENSION_MISMATCH","Embeddings must have same dimensions");if(!e.isHyperbolic||!t.isHyperbolic)throw new L("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),o=this.normSquared(r),l=2*this.euclideanDistanceSquared(n,r),d=(1-a)*(1-o);if(d<=this.config.epsilon)return 1/0;let m=l/d;return Math.acosh(1+m)/s}midpoint(e,t){if(e.dimensions!==t.dimensions)throw new L("DIMENSION_MISMATCH","Embeddings must have same dimensions");if(!e.isHyperbolic||!t.isHyperbolic)throw new L("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,o=1-n*i,u=1+2*n*r+n*n*i*s;if(Math.abs(u)<this.config.epsilon)throw new L("HYPERBOLIC_ERROR","M\xF6bius addition denominator is zero");return e.map((d,m)=>(a*d+o*t[m])/u)}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 L("HYPERBOLIC_ERROR","M\xF6bius scalar multiplication out of bounds");let a=Math.tanh(t*Math.atanh(s))/(r*i);return e.map(o=>o*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 L("HYPERBOLIC_ERROR","Curvature must be negative");this.config={...this.config,...e}}getConfig(){return{...this.config}}};ie();var Ve=class{generator;search;hyperbolic;isInitialized=!1;constructor(e={}){this.generator=new Pe(e.embedding),this.search=new xe,this.hyperbolic=new Ae(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 L("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=j();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()}_${Oa().slice(0,9)}`}isReady(){return this.isInitialized&&this.generator.isReady()}};function It(c){return new Ve(c)}var Fn={enabled:!0,dbPath:".agentic-qe/memory.db",maxOutcomes:1e5,retentionDays:90,autoCleanup:!0,cleanupIntervalMs:3600*1e3};ie();k();H();var za={enabled:!0,haikuThreshold:.8,sonnetThreshold:.4,includeHealthSnapshot:!1,enableLogging:!0},Ln=class{config;minCutService;constructor(e){this.config={...za,...e},this.minCutService=pi()}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 l=e.taskGraph||this.minCutService.buildTaskGraphFromTopology(n);a=this.minCutService.getStructuralHealth(l)}let o=Date.now()-t,u={modelTier:i,tierLabel:s,lambda:r.lambda,normalizedLambda:r.normalizedLambda,confidence:r.confidence,rationale:r.rationale,usedMinCut:!0,healthSnapshot:a,decisionTimeMs:o};return this.config.enableLogging&&this.logDecision(u),u}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 Ti(c){return new Ln(c)}import{existsSync as Ba}from"fs";import{join as ja}from"path";var Ot=class{id="memory";name="Pattern Memory";priority=80;maxTokens=2e3;async gather(e){let t=[];try{let n=ja(process.cwd(),".agentic-qe","memory.db");if(!Ba(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-5DOP2J3V.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 "),o=s.map(d=>`%${d}%`),l=i.prepare(`SELECT name, domain, description, confidence
334
334
  FROM qe_patterns
335
335
  WHERE ${a}
336
336
  ORDER BY confidence DESC
@@ -338,12 +338,12 @@ ${e.recommendations.length===0?"No recommendations - all quality gates passed.":
338
338
  `);t.push({sourceId:this.id,title:"Relevant Patterns from Learning Database",content:`Found ${l.length} relevant patterns:
339
339
 
340
340
  ${d}`,estimatedTokens:Math.ceil(d.length/3.5),relevance:.8})}}}finally{i.close()}}catch{return this.fallbackGather(e)}return t.length===0?this.fallbackGather(e):t}fallbackGather(e){let t=[`Task: ${e.taskDescription}`,`Agent: ${e.agentType}`,`Files: ${e.targetFiles.join(", ")}`].join(`
341
- `);return[{sourceId:this.id,title:"Task Context",content:t,estimatedTokens:Math.ceil(t.length/3.5),relevance:.5}]}extractDomainKeywords(e){let t=[],n=e.toLowerCase(),r={"test-generation":["test","generate","create test","unit test","spec"],"coverage-analysis":["coverage","gap","branch","uncovered"],"security-compliance":["security","vulnerability","owasp","injection","auth"],"quality-assessment":["quality","review","code review","assessment"],"defect-intelligence":["defect","bug","regression","root cause"]};for(let[i,s]of Object.entries(r))s.some(a=>n.includes(a))&&t.push(i);return t.length>0?t:["test-generation"]}};import{execSync as qa}from"child_process";var Ot=class{id="git";name="Git History";priority=60;maxTokens=1500;async gather(e){let t=[];for(let n of e.targetFiles.slice(0,5))try{let r=qa(`git log --oneline -5 -- "${n}" 2>/dev/null || true`,{encoding:"utf-8",timeout:5e3}).trim();if(r){let i=`Recent commits for ${n}:
342
- ${r}`;t.push({sourceId:this.id,title:`Git history: ${n}`,content:i,estimatedTokens:Math.ceil(i.length/3.5),relevance:.5})}}catch{}return t}};import{existsSync as Ga,readFileSync as $a}from"fs";import{basename as Fn,dirname as za,join as Ln}from"path";var _t=class{id="tests";name="Existing Tests";priority=70;maxTokens=2e3;async gather(e){let t=[];for(let n of e.targetFiles.slice(0,3)){let r=this.findTestPaths(n);for(let i of r)if(Ga(i))try{let a=$a(i,"utf-8").match(/(?:it|test|describe)\s*\(\s*['"`]([^'"`]+)['"`]/g)||[];if(a.length>0){let o=`Tests for ${Fn(n)} (${i}):
341
+ `);return[{sourceId:this.id,title:"Task Context",content:t,estimatedTokens:Math.ceil(t.length/3.5),relevance:.5}]}extractDomainKeywords(e){let t=[],n=e.toLowerCase(),r={"test-generation":["test","generate","create test","unit test","spec"],"coverage-analysis":["coverage","gap","branch","uncovered"],"security-compliance":["security","vulnerability","owasp","injection","auth"],"quality-assessment":["quality","review","code review","assessment"],"defect-intelligence":["defect","bug","regression","root cause"]};for(let[i,s]of Object.entries(r))s.some(a=>n.includes(a))&&t.push(i);return t.length>0?t:["test-generation"]}};import{execSync as Ua}from"child_process";var _t=class{id="git";name="Git History";priority=60;maxTokens=1500;async gather(e){let t=[];for(let n of e.targetFiles.slice(0,5))try{let r=Ua(`git log --oneline -5 -- "${n}" 2>/dev/null || true`,{encoding:"utf-8",timeout:5e3}).trim();if(r){let i=`Recent commits for ${n}:
342
+ ${r}`;t.push({sourceId:this.id,title:`Git history: ${n}`,content:i,estimatedTokens:Math.ceil(i.length/3.5),relevance:.5})}}catch{}return t}};import{existsSync as Ha,readFileSync as Va}from"fs";import{basename as Nn,dirname as Qa,join as qn}from"path";var Ft=class{id="tests";name="Existing Tests";priority=70;maxTokens=2e3;async gather(e){let t=[];for(let n of e.targetFiles.slice(0,3)){let r=this.findTestPaths(n);for(let i of r)if(Ha(i))try{let a=Va(i,"utf-8").match(/(?:it|test|describe)\s*\(\s*['"`]([^'"`]+)['"`]/g)||[];if(a.length>0){let o=`Tests for ${Nn(n)} (${i}):
343
343
  ${a.join(`
344
- `)}`;t.push({sourceId:this.id,title:`Tests: ${Fn(n)}`,content:o,estimatedTokens:Math.ceil(o.length/3.5),relevance:.8})}}catch{}}return t}findTestPaths(e){let t=Fn(e).replace(/\.(ts|js|tsx|jsx)$/,""),n=za(e),r=[".test.ts",".spec.ts",".test.js",".spec.js"],i=[];for(let s of r)i.push(Ln(n,`${t}${s}`)),i.push(Ln(n,"__tests__",`${t}${s}`)),i.push(Ln(n,"..","tests",`${t}${s}`));return i}};import{existsSync as Ba,readFileSync as ja}from"fs";import{join as Nn,basename as Ua}from"path";var Ft=class{id="coverage";name="Coverage Data";priority=50;maxTokens=1e3;async gather(e){let t=[],n=[Nn(process.cwd(),"coverage","coverage-summary.json"),Nn(process.cwd(),"coverage","coverage-final.json"),Nn(process.cwd(),".coverage","coverage-summary.json")];for(let r of n)if(Ba(r))try{let i=ja(r,"utf-8"),s=JSON.parse(i),a=[];for(let o of e.targetFiles){let u=Ua(o);for(let[l,d]of Object.entries(s))if(l.includes(u)&&d&&typeof d=="object"){let m=d,p=m.lines?.pct??m.statements?.pct,g=m.branches?.pct,h=m.functions?.pct;p!==void 0&&a.push(`${u}: lines=${p}%${g!==void 0?`, branches=${g}%`:""}${h!==void 0?`, functions=${h}%`:""}`)}}if(a.length>0){let o=`Coverage for target files:
344
+ `)}`;t.push({sourceId:this.id,title:`Tests: ${Nn(n)}`,content:o,estimatedTokens:Math.ceil(o.length/3.5),relevance:.8})}}catch{}}return t}findTestPaths(e){let t=Nn(e).replace(/\.(ts|js|tsx|jsx)$/,""),n=Qa(e),r=[".test.ts",".spec.ts",".test.js",".spec.js"],i=[];for(let s of r)i.push(qn(n,`${t}${s}`)),i.push(qn(n,"__tests__",`${t}${s}`)),i.push(qn(n,"..","tests",`${t}${s}`));return i}};import{existsSync as Wa,readFileSync as Ka}from"fs";import{join as Gn,basename as Xa}from"path";var Lt=class{id="coverage";name="Coverage Data";priority=50;maxTokens=1e3;async gather(e){let t=[],n=[Gn(process.cwd(),"coverage","coverage-summary.json"),Gn(process.cwd(),"coverage","coverage-final.json"),Gn(process.cwd(),".coverage","coverage-summary.json")];for(let r of n)if(Wa(r))try{let i=Ka(r,"utf-8"),s=JSON.parse(i),a=[];for(let o of e.targetFiles){let u=Xa(o);for(let[l,d]of Object.entries(s))if(l.includes(u)&&d&&typeof d=="object"){let m=d,p=m.lines?.pct??m.statements?.pct,g=m.branches?.pct,h=m.functions?.pct;p!==void 0&&a.push(`${u}: lines=${p}%${g!==void 0?`, branches=${g}%`:""}${h!==void 0?`, functions=${h}%`:""}`)}}if(a.length>0){let o=`Coverage for target files:
345
345
  ${a.join(`
346
- `)}`;t.push({sourceId:this.id,title:"File Coverage Data",content:o,estimatedTokens:Math.ceil(o.length/3.5),relevance:.6})}if(s.total&&typeof s.total=="object"){let o=s.total,u=`Project coverage: lines=${o.lines?.pct??"?"}%, branches=${o.branches?.pct??"?"}%, functions=${o.functions?.pct??"?"}%`;t.push({sourceId:this.id,title:"Project Coverage Summary",content:u,estimatedTokens:Math.ceil(u.length/3.5),relevance:.4})}break}catch{continue}return t}};import{existsSync as Ha}from"fs";import{join as Va}from"path";var Lt=class{id="requirements";name="Requirements Traceability";priority=75;maxTokens=2e3;async gather(e){let t=[];try{let n=Va(process.cwd(),".agentic-qe","memory.db");if(!Ha(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-6VBZQIJI.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(u=>`%${u.split("/").pop()}%`);if(a.length>0){let u=a.map(()=>"description LIKE ?").join(" OR "),d=i.prepare(`SELECT name, domain, description, confidence
346
+ `)}`;t.push({sourceId:this.id,title:"File Coverage Data",content:o,estimatedTokens:Math.ceil(o.length/3.5),relevance:.6})}if(s.total&&typeof s.total=="object"){let o=s.total,u=`Project coverage: lines=${o.lines?.pct??"?"}%, branches=${o.branches?.pct??"?"}%, functions=${o.functions?.pct??"?"}%`;t.push({sourceId:this.id,title:"Project Coverage Summary",content:u,estimatedTokens:Math.ceil(u.length/3.5),relevance:.4})}break}catch{continue}return t}};import{existsSync as Ya}from"fs";import{join as Ja}from"path";var Nt=class{id="requirements";name="Requirements Traceability";priority=75;maxTokens=2e3;async gather(e){let t=[];try{let n=Ja(process.cwd(),".agentic-qe","memory.db");if(!Ya(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-5DOP2J3V.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(u=>`%${u.split("/").pop()}%`);if(a.length>0){let u=a.map(()=>"description LIKE ?").join(" OR "),d=i.prepare(`SELECT name, domain, description, confidence
347
347
  FROM qe_patterns
348
348
  WHERE domain LIKE '%requirement%'
349
349
  AND (${u})
@@ -359,7 +359,7 @@ ${m}`,estimatedTokens:Math.ceil(m.length/3.5),relevance:.75})}}let o=this.extrac
359
359
  LIMIT 5`).all(...l);if(m.length>0){let p=m.map(g=>`- **${g.name}**: ${g.description||"No description"}`).join(`
360
360
  `);t.push({sourceId:this.id,title:"Related Requirements",content:`Requirements related to task:
361
361
 
362
- ${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 Qa}from"fs";import{join as Wa}from"path";var Nt=class{id="defects";name="Defect Intelligence";priority=65;maxTokens=1500;async gather(e){let t=[];try{let n=Wa(process.cwd(),".agentic-qe","memory.db");if(!Qa(n))return[];let{openDatabase:r}=await import("./safe-db-6VBZQIJI.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(u=>`%${u.split("/").pop()}%`);if(a.length>0){let u=a.map(()=>"description LIKE ?").join(" OR "),d=i.prepare(`SELECT name, domain, description, confidence
362
+ ${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 Za}from"fs";import{join as eo}from"path";var qt=class{id="defects";name="Defect Intelligence";priority=65;maxTokens=1500;async gather(e){let t=[];try{let n=eo(process.cwd(),".agentic-qe","memory.db");if(!Za(n))return[];let{openDatabase:r}=await import("./safe-db-5DOP2J3V.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(u=>`%${u.split("/").pop()}%`);if(a.length>0){let u=a.map(()=>"description LIKE ?").join(" OR "),d=i.prepare(`SELECT name, domain, description, confidence
363
363
  FROM qe_patterns
364
364
  WHERE domain LIKE '%defect%'
365
365
  AND (${u})
@@ -375,16 +375,16 @@ ${m}`,estimatedTokens:Math.ceil(m.length/3.5),relevance:.7})}}let o=this.extract
375
375
  LIMIT 5`).all(...l);if(m.length>0){let p=m.map(g=>`- **${g.name}**: ${g.description||"No description"}`).join(`
376
376
  `);t.push({sourceId:this.id,title:"Regression Hotspots",content:`Known regression patterns:
377
377
 
378
- ${p}`,estimatedTokens:Math.ceil(p.length/3.5),relevance:.6})}}}finally{i.close()}}catch{return[]}return t}extractDefectKeywords(e){let t=[],n=e.toLowerCase(),r=["bug","defect","regression","fix","crash","error","null","undefined","timeout","race condition","deadlock","memory leak","overflow","injection","broken"];for(let i of r)n.includes(i)&&t.push(i);return t.slice(0,5)}};var Ka=8e3,Xa=300*1e3;function Ya(){return[new It,new Lt,new _t,new Nt,new Ot,new Ft]}var qt=class{sources;maxTokenBudget;cache=new Map;cacheTtl;constructor(e){this.sources=e?.sources||Ya(),this.maxTokenBudget=e?.maxTokenBudget||Ka,this.cacheTtl=e?.cacheTtlMs||Xa}async compile(e){let t=Date.now(),n=this.buildCacheKey(e),r=this.cache.get(n);if(r&&Date.now()-r.timestamp<this.cacheTtl)return r.result;let i=e.maxTokenBudget||this.maxTokenBudget,s=await Promise.allSettled(this.sources.map(async p=>{try{let g=await p.gather(e);return{sourceId:p.id,sourceName:p.name,priority:p.priority,fragments:g}}catch{return{sourceId:p.id,sourceName:p.name,priority:p.priority,fragments:[]}}})),a=[],o=[];for(let p of s)if(p.status==="fulfilled"){let{sourceId:g,priority:h,fragments:f}=p.value;if(f.length>0){o.push(g);for(let v of f)a.push({...v,sourcePriority:h})}}a.sort((p,g)=>p.sourcePriority!==g.sourcePriority?g.sourcePriority-p.sourcePriority:g.relevance-p.relevance);let u=[],l=0;for(let p of a)if(l+p.estimatedTokens<=i){let{sourcePriority:g,...h}=p;u.push(h),l+=p.estimatedTokens}let m={summary:this.generateSummary(e,u,o),fragments:u,totalTokens:l,sources:o,timestamp:new Date().toISOString(),duration:Date.now()-t};return this.cache.set(n,{result:m,timestamp:Date.now()}),m}clearCache(){this.cache.clear()}getCacheStats(){return{size:this.cache.size,ttlMs:this.cacheTtl}}buildCacheKey(e){return`${e.agentType}:${e.targetFiles.sort().join(",")}:${e.taskDescription.slice(0,100)}`}generateSummary(e,t,n){return[`Context compiled for ${e.agentType} agent.`,`Target: ${e.targetFiles.length} file(s).`,`Sources: ${n.join(", ")}.`,`Fragments: ${t.length} (${t.reduce((r,i)=>r+i.estimatedTokens,0)} est. tokens).`].join(" ")}};function fi(c){let e=[];e.push("## Compiled Context"),e.push(""),e.push(c.summary),e.push("");for(let t of c.fragments)e.push(`### ${t.title}`),e.push(t.content),e.push("");return e.push(`_Context compiled: ${c.timestamp} (${c.duration}ms)_`),e.join(`
379
- `)}var Ja={enabled:!0,enableAgentBooster:!0,enableLogging:!0,maxLogEntries:1e3},qn=class c{static instance=null;static initializationPromise=null;config;modelRouter;minCutRouter;routingLog=[];contextCompiler;disposed=!1;constructor(e,t){this.config=e,this.modelRouter=t,this.contextCompiler=new qt,this.minCutRouter=hi({enableLogging:e.enableLogging})}static async getInstance(e){if(c.instance&&!c.instance.disposed)return c.instance;if(c.initializationPromise)return c.initializationPromise;c.initializationPromise=c.create(e);try{return c.instance=await c.initializationPromise,c.instance}finally{c.initializationPromise=null}}static async create(e){let t={...Ja,...e},n;t.enableAgentBooster?n=await Et(t.modelRouterConfig):n=St(t.modelRouterConfig);let r=new c(t,n);return t.enableLogging&&console.error(`[TaskRouter] Initialized with Agent Booster: ${t.enableAgentBooster}`),r}async routeTask(e){if(!this.config.enabled)return this.createDisabledResult(e);if(this.disposed)throw new Error("TaskRouterService has been disposed");let t=null;if(this.minCutRouter.isEnabled()&&e.agentTopology)try{t=this.minCutRouter.route({task:e.task,domain:e.domain,agentType:e.agentType,agentTopology:e.agentTopology,isCritical:e.isCritical})}catch(g){this.config.enableLogging&&console.error(`[TaskRouter] MinCut routing failed, falling back to heuristic: ${g instanceof Error?g.message:String(g)}`)}let n={task:e.task,codeContext:e.codeContext,filePaths:e.filePaths,manualTier:e.manualTier,isCritical:e.isCritical,agentType:e.agentType,domain:e.domain,metadata:e.metadata},r=await this.modelRouter.route(n),i=r;if(t&&t.usedMinCut){let g=t.modelTier;g!==r.tier&&(i={...r,tier:g,rationale:`[MinCut] ${t.rationale} (heuristic suggested Tier ${r.tier})`},this.config.enableLogging&&console.error(`[TaskRouter] MinCut override: Tier ${r.tier} -> Tier ${g} (lambda=${t.normalizedLambda.toFixed(3)})`))}let s=Re[i.tier],a=this.mapTierToStrategy(i.tier),o={timestamp:i.metadata.timestamp,taskDescription:e.task.slice(0,200),requestedTier:e.manualTier,selectedTier:i.tier,modelId:i.modelId,complexity:i.complexityAnalysis.overall,confidence:i.confidence,wasDowngraded:i.budgetDecision.wasDowngraded,agentBoosterEligible:i.agentBoosterEligible,decisionTimeMs:i.metadata.decisionTimeMs,rationale:i.rationale};this.addLogEntry(o),this.config.enableLogging&&this.logRoutingDecision(o);let u=e.patternHints,l=u&&u.length>0?this.formatPatternContext(u):void 0,d=e.agentType,m=d?Rn(d)||Rn(d.replace("v3-qe-","qe-")):void 0,p;if(e.filePaths&&e.filePaths.length>0)try{let g=await this.contextCompiler.compile({targetFiles:e.filePaths,agentType:e.agentType||"unknown",taskDescription:e.task});p=fi(g)}catch{}return{decision:i,executionStrategy:a,useAgentBooster:i.agentBoosterEligible,modelId:i.modelId,tierInfo:{tier:i.tier,name:s.name,typicalLatencyMs:s.typicalLatencyMs,relativeCost:s.relativeCost},logEntry:o,patternHints:u,patternContext:l,overlayConfig:m,compiledContext:p}}formatPatternContext(e){if(!e||e.length===0)return"";let t=["--- Relevant Patterns from Learning ---",""];for(let n of e){let r=n.canReuse?" [REUSABLE]":"";t.push(`[${n.name}]${r}`,` ${n.description}`,` Similarity: ${(n.similarity*100).toFixed(0)}% | Confidence: ${(n.confidence*100).toFixed(0)}%`,"")}return t.push("Use these patterns as guidance when applicable."),t.join(`
380
- `)}async quickRoute(e){return this.routeTask({task:e})}async routeBatch(e){return Promise.all(e.map(t=>this.routeTask(t)))}getMetrics(){return this.modelRouter.getMetrics()}getRoutingLog(e=100,t=0){return this.routingLog.slice(t,t+e)}getRoutingStats(){let e=this.routingLog;if(e.length===0)return this.createEmptyStats();let t=new Map,n=0,r=0,i=0,s=0;for(let o of e)t.set(o.selectedTier,(t.get(o.selectedTier)||0)+1),n+=o.complexity,r+=o.decisionTimeMs,o.wasDowngraded&&i++,o.agentBoosterEligible&&s++;let a={};for(let[o,u]of t)a[o]=u/e.length;return{totalRouted:e.length,avgComplexity:n/e.length,avgDecisionTimeMs:r/e.length,downgradeRate:i/e.length,agentBoosterRate:s/e.length,tierDistribution:a,period:{start:e[0].timestamp,end:e[e.length-1].timestamp}}}reset(){this.routingLog.length=0,this.modelRouter.resetMetrics(),this.config.enableLogging&&console.error("[TaskRouter] Reset routing log and metrics")}async dispose(){this.disposed||(this.disposed=!0,await this.modelRouter.dispose(),c.instance=null,this.config.enableLogging&&console.error("[TaskRouter] Disposed"))}isEnabled(){return this.config.enabled&&!this.disposed}mapTierToStrategy(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"}}addLogEntry(e){this.routingLog.push(e),this.routingLog.length>this.config.maxLogEntries&&this.routingLog.splice(0,this.routingLog.length-this.config.maxLogEntries)}logRoutingDecision(e){let t=Re[e.selectedTier].name,n=e.agentBoosterEligible?"[AgentBooster]":`[Tier${e.selectedTier}]`;console.error(`[TaskRouter] ${n} ${t} | Complexity: ${e.complexity.toFixed(0)} | Confidence: ${(e.confidence*100).toFixed(0)}% | Time: ${e.decisionTimeMs.toFixed(1)}ms`+(e.wasDowngraded?" [DOWNGRADED]":""))}createDisabledResult(e){let n=Re[2],r={timestamp:new Date,taskDescription:e.task.slice(0,200),selectedTier:2,modelId:n.exampleModels[0],complexity:50,confidence:.5,wasDowngraded:!1,agentBoosterEligible:!1,decisionTimeMs:0,rationale:"Routing disabled - using default tier"};return{decision:{tier:2,modelId:n.exampleModels[0],complexityAnalysis:{overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.5,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:2,alternateTiers:[],explanation:"Routing disabled"},budgetDecision:{allowed:!0,reason:"Routing disabled",requestedTier:2,approvedTier:2,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:{tier:2,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:new Date,remainingBudgetUsd:100,remainingRequestsThisHour:100,remainingRequestsToday:1e3},warnings:[]},confidence:.5,rationale:"Routing disabled - using default tier",agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:0,fromCache:!1},warnings:["Routing is disabled"]},executionStrategy:"sonnet",useAgentBooster:!1,modelId:n.exampleModels[0],tierInfo:{tier:2,name:n.name,typicalLatencyMs:n.typicalLatencyMs,relativeCost:n.relativeCost},logEntry:r}}createEmptyStats(){let e=new Date;return{totalRouted:0,avgComplexity:0,avgDecisionTimeMs:0,downgradeRate:0,agentBoosterRate:0,tierDistribution:{},period:{start:e,end:e}}}};async function Gt(c){return qn.getInstance(c)}Tn();vt();var Gn=Ce("CoherenceActionGate"),Za={structuralPermit:.4,structuralDeny:.2,shiftPermit:.5,shiftDeny:.25,evidencePermit:.5,evidenceDeny:.2,combinedPermit:.5,combinedDeny:.25},$n={structural:.3,shift:.35,evidence:.35},eo={low:1,medium:.9,high:.75,critical:.6},yi=1e3,$t=class{thresholds;advisoryMode;nativeAvailable=null;evaluationHistory=[];permitCount=0;deferCount=0;denyCount=0;totalCombinedScore=0;totalStructuralScore=0;totalShiftScore=0;totalEvidenceScore=0;cusumHigh=0;cusumLow=0;cusumMean=.7;cusumK=.05;cusumH=4;cusumSampleCount=0;cusumAlertActive=!1;constructor(e){this.advisoryMode=e?.advisory??!0,this.thresholds={...Za,...e?.thresholds}}evaluate(e){let t=this.computeStructuralScore(e),n=this.computeShiftScore(e),r=this.computeEvidenceScore(e),i=t*$n.structural+n*$n.shift+r*$n.evidence,s=eo[e.riskLevel]??1,a=i*s,o=this.computeDecision(t,n,r,a),u=this.buildReasoning(e,o,t,n,r,a),l={decision:o,structuralScore:t,shiftScore:n,evidenceScore:r,combinedScore:a,reasoning:u,advisory:this.advisoryMode};return this.recordEvaluation(l),Gn.debug("Action gate evaluation",{action:e.type,domain:e.domain,decision:o,combinedScore:a,advisory:this.advisoryMode}),l}getStatistics(){let e=this.evaluationHistory.length;return{totalEvaluations:e,permitCount:this.permitCount,deferCount:this.deferCount,denyCount:this.denyCount,averageCombinedScore:e>0?this.totalCombinedScore/e:0,averageStructuralScore:e>0?this.totalStructuralScore/e:0,averageShiftScore:e>0?this.totalShiftScore/e:0,averageEvidenceScore:e>0?this.totalEvidenceScore/e:0,advisoryMode:this.advisoryMode}}configureThresholds(e){this.thresholds={...this.thresholds,...e},Gn.info("Action gate thresholds updated",{thresholds:this.thresholds})}getThresholds(){return{...this.thresholds}}isAdvisory(){return this.advisoryMode}getEvaluationHistory(){return[...this.evaluationHistory]}resetStatistics(){this.evaluationHistory=[],this.permitCount=0,this.deferCount=0,this.denyCount=0,this.totalCombinedScore=0,this.totalStructuralScore=0,this.totalShiftScore=0,this.totalEvidenceScore=0,this.resetCusum()}resetCusum(){this.cusumHigh=0,this.cusumLow=0,this.cusumAlertActive=!1,this.cusumSampleCount=0}computeStructuralScore(e){let t=.5;["generate-test","modify-code","analyze-coverage","scan-security","assess-quality","validate-contracts","test-accessibility","execute-tests","index-code","predict-defects","validate-requirements","deploy","run-chaos","optimize-learning"].includes(e.type)&&(t+=.2),JSON.stringify(e.context).toLowerCase().includes(e.domain.toLowerCase())&&(t+=.15);let i=Object.keys(e.context);return i.length>=3?t+=.15:i.length>=1&&(t+=.05),Math.min(Math.max(t,0),1)}computeShiftScore(e){let t=e.confidence,r={low:.25,medium:.5,high:.75,critical:1}[e.riskLevel]??.5,i=Math.max(0,r-e.confidence);t-=i*.3;let s=e.context;(s.stale===!0||s.outdated===!0)&&(t-=.3),(s.distributionShift===!0||s.contextChanged===!0)&&(t-=.4),this.cusumSampleCount++;let a=e.confidence;return this.cusumHigh=Math.max(0,this.cusumHigh+(a-this.cusumMean)-this.cusumK),this.cusumLow=Math.max(0,this.cusumLow-(a-this.cusumMean)-this.cusumK),this.cusumHigh>this.cusumH||this.cusumLow>this.cusumH?(t-=.2,this.cusumAlertActive||(this.cusumAlertActive=!0,Gn.warn("CUSUM shift detected",{cusumHigh:this.cusumHigh,cusumLow:this.cusumLow}))):this.cusumAlertActive=!1,Math.min(Math.max(t,0),1)}computeEvidenceScore(e){let t=.5,n=e.context,r=["testResults","coverageData","securityScan","qualityReport","peerReview","analysisResult","validationPassed","precedent","historicalSuccess"];for(let s of r)n[s]!==void 0&&n[s]!==null&&(t*=1+.15);let i=["errors","failures","warnings","regressions","conflictingResults","noTestCoverage"];for(let s of i)n[s]!==void 0&&n[s]!==null&&(t*=1-.18);if((e.riskLevel==="critical"||e.riskLevel==="high")&&!n.testResults&&!n.peerReview&&(t-=.15),typeof n.evidenceCount=="number"){let s=n.evidenceCount;t+=Math.min(s*.05,.2)}return Math.min(Math.max(t,0),1)}computeDecision(e,t,n,r){return e<this.thresholds.structuralDeny||t<this.thresholds.shiftDeny||n<this.thresholds.evidenceDeny||r<this.thresholds.combinedDeny?"DENY":e>=this.thresholds.structuralPermit&&t>=this.thresholds.shiftPermit&&n>=this.thresholds.evidencePermit&&r>=this.thresholds.combinedPermit?"PERMIT":"DEFER"}buildReasoning(e,t,n,r,i,s){let a=[];if(a.push(`Decision: ${t} for ${e.type} (${e.domain}).`),a.push(`Scores: structural=${n.toFixed(2)}, shift=${r.toFixed(2)}, evidence=${i.toFixed(2)}, combined=${s.toFixed(2)}.`),t==="DENY")n<this.thresholds.structuralDeny&&a.push("Structural filter failed: action does not fit codebase graph."),r<this.thresholds.shiftDeny&&a.push("Shift filter failed: significant context distribution shift detected."),i<this.thresholds.evidenceDeny&&a.push("Evidence filter failed: insufficient evidence to justify action."),s<this.thresholds.combinedDeny&&a.push("Combined score below minimum threshold.");else if(t==="DEFER"){let o=[];n<this.thresholds.structuralPermit&&o.push("structural"),r<this.thresholds.shiftPermit&&o.push("shift"),i<this.thresholds.evidencePermit&&o.push("evidence"),o.length>0&&a.push(`Marginal filters: ${o.join(", ")}. Human review recommended.`)}return this.advisoryMode&&a.push("(Advisory mode: decision logged only, not enforced.)"),a.join(" ")}recordEvaluation(e){switch(this.evaluationHistory.push(e),this.evaluationHistory.length>yi&&(this.evaluationHistory=this.evaluationHistory.slice(-yi)),this.totalCombinedScore+=e.combinedScore,this.totalStructuralScore+=e.structuralScore,this.totalShiftScore+=e.shiftScore,this.totalEvidenceScore+=e.evidenceScore,e.decision){case"PERMIT":this.permitCount++;break;case"DEFER":this.deferCount++;break;case"DENY":this.denyCount++;break}}};function vi(c){return new $t(c)}function bi(c,e,t,n,r,i){if(!Te().useCoherenceActionGate)return null;let a=i??new $t,o={type:c,domain:e,confidence:t,context:r,riskLevel:n};return a.evaluate(o)}import*as zt from"fs/promises";M();function to(c){return c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function no(c,e,t,n){if(!t)return{testCode:c,sourceFile:e};let r=m=>m.replace(/\.[a-z]+$/i,""),i=n?n.match(/\.(ts|tsx|js|jsx|mjs|cjs)$/i)?r(n):n:"./module-under-test",s=n?"":`// TODO: replace './module-under-test' with the actual import path of the module under test
381
- `,a=r(t),o=to(a),u=new RegExp(o+"(?:\\.[a-zA-Z]+){0,2}","g");return{testCode:c&&s+c.replace(u,i),sourceFile:e===t&&n||e}}function zn(c){c.registerHandler("generate-tests",async e=>{let t=e.payload;try{let n=c.getTestGenerator(),r=[],i;if(t.sourceFiles&&t.sourceFiles.length>0)r=t.sourceFiles;else if(t.filePath)r=[t.filePath];else if(t.sourceCode){let m={python:".py",typescript:".ts",javascript:".js",go:".go",rust:".rs",java:".java",ruby:".rb",kotlin:".kt",csharp:".cs",php:".php",swift:".swift",cpp:".cpp",c:".c",scala:".scala"}[t.language?.toLowerCase()||"typescript"]||".ts";i=`/tmp/aqe-temp-${N()}${m}`,await zt.writeFile(i,t.sourceCode,"utf-8"),r=[i]}if(r.length===0)return I({testsGenerated:0,coverageEstimate:0,tests:[],patternsUsed:[],warning:"No source files or code provided for test generation. Provide sourceCode, filePath, or sourceFiles in the payload."});let s=t.framework||"vitest",a=i?{[i]:t.filePath?t.filePath.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/i,""):"./module-under-test"}:void 0,o=await n.generateTests({sourceFiles:r,testType:t.testType||"unit",framework:s,coverageTarget:t.coverageGoal||80,patterns:[],importPathOverrides:a});if(i)try{await zt.unlink(i)}catch{}if(!o.success)return o;let u=o.value,l=u.tests.map(d=>{let m=no(d.testCode,d.sourceFile,i,t.filePath);return{name:d.name,file:d.testFile,type:d.type,sourceFile:m.sourceFile,assertions:d.assertions,testCode:m.testCode}});return I({testsGenerated:l.length,coverageEstimate:u.coverageEstimate,tests:l,patternsUsed:u.patternsUsed})}catch(n){return G($(n))}}),c.registerHandler("execute-tests",async e=>{let t=e.payload;try{let n=t.testFiles||[];if(n.length===0)return I({total:0,passed:0,failed:0,skipped:0,duration:0,coverage:0,failedTests:[],warning:"No test files specified. Provide testFiles array with paths to test files."});let r=process.cwd(),i,s=/^[a-zA-Z0-9_.\/\-@]+$/,a=n.filter(o=>s.test(o));if(a.length!==n.length)return I({total:0,passed:0,failed:0,skipped:0,duration:0,coverage:0,failedTests:[],warning:"Some test file paths contain invalid characters and were rejected."});try{let{spawnSync:o}=await import("child_process"),u=o("npx",["vitest","run",...a,"--reporter=json"],{cwd:r,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});i=u.stdout||"",!i.includes("{")&&u.status!==0&&(i=o("npx",["jest",...a,"--json"],{cwd:r,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).stdout||"")}catch(o){i=o.stdout||""}try{let o=i.indexOf("{");if(o>=0){let u=JSON.parse(i.slice(o));if(u.testResults){let l=u.numTotalTests||0,d=u.numPassedTests||0,m=u.numFailedTests||0;return I({total:l,passed:d,failed:m,skipped:l-d-m,duration:0,coverage:0,failedTests:[]})}}}catch{}return I({total:n.length,passed:0,failed:0,skipped:0,duration:0,coverage:0,failedTests:[],warning:"Could not parse test runner output. Check that vitest or jest is installed.",rawOutput:i.slice(0,500)})}catch(n){return G($(n))}})}import*as Ti from"fs/promises";import*as se from"fs";import*as Me from"path";M();H();H();import*as ke from"fs/promises";import*as Z from"path";async function Bn(c){let e=[Z.join(c,"coverage","coverage-final.json"),Z.join(c,"coverage","lcov.info"),Z.join(c,".nyc_output","coverage-final.json"),Z.join(c,"coverage-final.json"),Z.join(c,"coverage.xml"),Z.join(c,"htmlcov","status.json"),Z.join(c,"cobertura-coverage.xml")];for(let t of e)try{let n=await ke.readFile(t,"utf-8");if(t.endsWith(".json"))return ro(n);if(t.endsWith(".info"))return io(n);if(t.endsWith(".xml"))return so(n)}catch{}return null}function ro(c){let e=A(c),t=[],n=0,r=0,i=0,s=0,a=0,o=0,u=0,l=0;for(let[d,m]of Object.entries(e)){let p=m,g=p.statementMap||{},h=p.s||{},f=p.branchMap||{},v=p.b||{},y=p.f||{},C=Object.keys(h).length,b=Object.values(h).filter(q=>q>0).length,w=Object.values(v).flat().length,S=Object.values(v).flat().filter(q=>q>0).length,T=Object.keys(y).length,P=Object.values(y).filter(q=>q>0).length,O=Object.keys(g).length,z=Object.values(h).filter(q=>q>0).length,X=[];for(let[q,V]of Object.entries(h))if(V===0){let ge=g[q];ge?.start?.line&&X.push(ge.start.line)}let ee=[];for(let[q,V]of Object.entries(v)){let ge=f[q];V.forEach((gt,Y)=>{gt===0&&ge?.locations?.[Y]?.start?.line&&ee.push(ge.locations[Y].start.line)})}t.push({path:d,lines:{covered:b,total:C},branches:{covered:S,total:w},functions:{covered:P,total:T},statements:{covered:z,total:O},uncoveredLines:Array.from(new Set(X)).sort((q,V)=>q-V),uncoveredBranches:Array.from(new Set(ee)).sort((q,V)=>q-V)}),n+=C,r+=b,i+=w,s+=S,a+=T,o+=P,u+=O,l+=z}return{files:t,summary:{line:n>0?r/n*100:0,branch:i>0?s/i*100:0,function:a>0?o/a*100:0,statement:u>0?l/u*100:0,files:t.length}}}function io(c){let e=[],t=c.split(`
382
- `),n=null,r=0,i=0,s=0,a=0,o=0,u=0,l=[],d=[];for(let y of t)if(y.startsWith("SF:"))n=y.slice(3);else if(y.startsWith("LF:"))r=parseInt(y.slice(3),10);else if(y.startsWith("LH:"))i=parseInt(y.slice(3),10);else if(y.startsWith("BRF:"))s=parseInt(y.slice(4),10);else if(y.startsWith("BRH:"))a=parseInt(y.slice(4),10);else if(y.startsWith("FNF:"))o=parseInt(y.slice(4),10);else if(y.startsWith("FNH:"))u=parseInt(y.slice(4),10);else if(y.startsWith("DA:")){let[C,b]=y.slice(3).split(",").map(w=>parseInt(w,10));b===0&&l.push(C)}else if(y.startsWith("BRDA:")){let C=y.slice(5).split(","),b=parseInt(C[0],10),w=C[3];(w==="0"||w==="-")&&d.push(b)}else y==="end_of_record"&&n&&(e.push({path:n,lines:{covered:i,total:r},branches:{covered:a,total:s},functions:{covered:u,total:o},statements:{covered:i,total:r},uncoveredLines:Array.from(new Set(l)),uncoveredBranches:Array.from(new Set(d))}),n=null,r=i=0,s=a=0,o=u=0,l.length=0,d.length=0);let m=0,p=0,g=0,h=0,f=0,v=0;for(let y of e)m+=y.lines.total,p+=y.lines.covered,g+=y.branches.total,h+=y.branches.covered,f+=y.functions.total,v+=y.functions.covered;return{files:e,summary:{line:m>0?p/m*100:0,branch:g>0?h/g*100:0,function:f>0?v/f*100:0,statement:m>0?p/m*100:0,files:e.length}}}function so(c){let e=[];function t(g,h){let f=g.match(new RegExp(`${h}=["']([^"']*)["']`));return f?f[1]:null}let n=/<class\s[^>]*?>/g,r;for(;(r=n.exec(c))!==null;){let g=r[0],h=t(g,"filename");if(!h)continue;let f=parseFloat(t(g,"line-rate")||"NaN"),v=parseFloat(t(g,"branch-rate")||"NaN"),y=r.index,C=c.indexOf("</class>",y),b=C>y?c.slice(y,C):"",w=0,S=0,T=0,P=0,O=0,z=0,X=[],ee=[],q=/<line\s([^>]*?)\/>/g,V;for(;(V=q.exec(b))!==null;){let Y=V[1],ze=parseInt(t(Y,"number")||"0",10),ht=parseInt(t(Y,"hits")||"0",10),vn=t(Y,"branch")==="true",Be=t(Y,"condition-coverage");w++,ht>0?S++:X.push(ze),vn&&(T++,(Be?parseInt(Be,10):ht>0?100:0)===100?P++:ee.push(ze))}let ge=/<method\s([^>]*?)>/g,gt;for(;(gt=ge.exec(b))!==null;){O++;let Y=gt.index,ze=b.indexOf("</method>",Y);if(ze>Y){let ht=b.slice(Y,ze),vn=/<line\s([^>]*?)\/>/g,Be=!1,bn;for(;(bn=vn.exec(ht))!==null;)if(parseInt(t(bn[1],"hits")||"0",10)>0){Be=!0;break}Be&&z++}}w===0&&!isNaN(f)&&(w=1,S=f>=.5?1:0),e.push({path:h,lines:{covered:S,total:w},branches:{covered:P,total:T},functions:{covered:z,total:O},statements:{covered:S,total:w},uncoveredLines:X,uncoveredBranches:ee})}let i=0,s=0,a=0,o=0,u=0,l=0;for(let g of e)i+=g.lines.total,s+=g.lines.covered,a+=g.branches.total,o+=g.branches.covered,u+=g.functions.total,l+=g.functions.covered;let d=c.match(/<coverage\s[^>]*?>/),m=d?parseFloat(t(d[0],"line-rate")||"NaN")*100:NaN,p=d?parseFloat(t(d[0],"branch-rate")||"NaN")*100:NaN;return{files:e,summary:{line:isNaN(m)?i>0?s/i*100:0:m,branch:isNaN(p)?a>0?o/a*100:0:p,function:u>0?l/u*100:0,statement:i>0?s/i*100:0,files:e.length}}}async function re(c,e={}){let t=[],{includeTests:n=!0,languages:r,maxFiles:i=5e3}=e,s=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".go",".rs",".java",".kt",".kts",".rb",".cs",".php",".swift",".c",".h",".cpp",".hpp",".cc",".scala"];if(r&&r.length>0){s=[];for(let o of r)o==="typescript"&&s.push(".ts",".tsx"),o==="javascript"&&s.push(".js",".jsx",".mjs",".cjs"),o==="python"&&s.push(".py",".pyw"),o==="go"&&s.push(".go"),o==="rust"&&s.push(".rs"),o==="java"&&s.push(".java"),o==="kotlin"&&s.push(".kt",".kts"),o==="ruby"&&s.push(".rb"),(o==="csharp"||o==="c#")&&s.push(".cs"),o==="php"&&s.push(".php"),o==="swift"&&s.push(".swift"),(o==="c"||o==="cpp"||o==="c++")&&s.push(".c",".h",".cpp",".hpp",".cc"),o==="scala"&&s.push(".scala")}async function a(o){try{let u=await ke.readdir(o,{withFileTypes:!0});for(let l of u){let d=Z.join(o,l.name);if(l.isDirectory()){if(["node_modules",".git","dist","build","coverage",".nyc_output","__pycache__",".venv","venv",".tox",".mypy_cache","target",".gradle","vendor",".bundle",".agentic-qe",".claude",".cache",".npm",".yarn",".next",".nuxt",".svelte-kit","out",".turbo","tmp","temp",".tmp"].includes(l.name))continue;if(t.length>=i)return;await a(d)}else if(l.isFile()){let m=Z.extname(l.name);if(!s.includes(m)||!n&&(l.name.includes(".test.")||l.name.includes(".spec.")||l.name.endsWith("_test.ts")||l.name.endsWith("_test.js")||d.includes("/__tests__/")||d.includes("/test/")||d.includes("/tests/")))continue;if(t.length>=i)return;t.push(d)}}}catch{}}try{if((await ke.stat(c)).isFile())return[c];await a(c)}catch{}return t}function Ci(c){let e=new Set,t={injection:"Use parameterized queries and input validation to prevent injection attacks",xss:"Sanitize user input and use Content-Security-Policy headers","sensitive-data":"Never hardcode secrets; use environment variables or secret managers","access-control":"Implement proper authentication and authorization checks","security-misconfiguration":"Review and harden security configurations","insecure-deserialization":"Avoid deserializing untrusted data; use safe alternatives","broken-auth":"Use strong authentication mechanisms and secure session management",dependencies:"Keep dependencies updated and regularly audit for vulnerabilities"};for(let i of c){let s=t[i.category];s&&e.add(s)}let n=c.some(i=>i.severity==="critical"),r=c.some(i=>i.severity==="high");return n&&e.add("CRITICAL: Address critical vulnerabilities immediately before deployment"),r&&e.add("Prioritize fixing high-severity issues in the next sprint"),e.size===0&&c.length===0&&e.add("No vulnerabilities found - maintain current security practices"),Array.from(e)}function ao(c){let e=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]),t=new Set(["node_modules","dist","build","coverage",".git",".claude",".agentic-qe","__pycache__",".venv"]),n=[".test.",".spec.","_test.","_spec."];if(!se.existsSync(c)||!se.statSync(c).isDirectory())return null;let r=[];function i(g,h){if(h>6)return;let f;try{f=se.readdirSync(g,{withFileTypes:!0})}catch{return}for(let v of f)if(v.isDirectory()){if(t.has(v.name))continue;i(Me.join(g,v.name),h+1)}else if(v.isFile()){let y=Me.extname(v.name);if(!e.has(y)||n.some(C=>v.name.includes(C)))continue;r.push(Me.join(g,v.name))}}if(i(c,0),r.length===0)return null;let s=r.map(g=>{let h="";try{h=se.readFileSync(g,"utf-8")}catch{}let v=h.split(`
383
- `).length,y=Math.max((h.match(/\b(function|=>)\b/g)||[]).length,1),C=Math.max((h.match(/\b(if|switch|case|\?\?|\|\|)\b/g)||[]).length,1),w=[g.replace(".ts",".test.ts").replace("/src/","/tests/"),g.replace(".ts",".spec.ts").replace("/src/","/tests/"),g.replace(".ts",".test.ts"),g.replace(".js",".test.js"),g.replace(".js",".test.js").replace("/src/","/tests/")].some(q=>se.existsSync(q)),S=Math.min(C*.005,.15),T=Math.min(v*1e-4,.1),P=Math.max(.05,Math.min(.95,w?.85-S-T:.2)),O=Math.floor(v*P),z=Math.min(Math.floor(O*.7),C),X=Math.min(Math.floor(y*P*.9),y),ee=Array.from({length:v-O},(q,V)=>V+O+1);return{path:g,lines:{covered:O,total:v},branches:{covered:z,total:C},functions:{covered:X,total:y},statements:{covered:O,total:v},uncoveredLines:ee,uncoveredBranches:ee.slice(0,Math.floor(ee.length/2))}}),a=s.reduce((g,h)=>g+h.lines.total,0),o=s.reduce((g,h)=>g+h.lines.covered,0),u=s.reduce((g,h)=>g+h.branches.total,0),l=s.reduce((g,h)=>g+h.branches.covered,0),d=s.reduce((g,h)=>g+h.functions.total,0),m=s.reduce((g,h)=>g+h.functions.covered,0),p=(g,h)=>h>0?Math.round(g/h*100):0;return{files:s,summary:{line:p(o,a),branch:p(l,u),function:p(m,d),statement:p(o,a),files:s.length}}}function jn(c){c.registerHandler("analyze-coverage",async e=>{let t=e.payload;try{let n=c.getCoverageAnalyzer(),r=t.target||process.cwd(),i=t.threshold||80,s=await Bn(r);if(!s){let l=!1;try{let{execSync:d}=await import("child_process"),m="npx vitest run --coverage --reporter=json 2>/dev/null";try{let p=await Ti.readFile(Me.join(r,"package.json"),"utf-8"),g=A(p),h={...g.devDependencies||{},...g.dependencies||{}};h.jest||h["@jest/core"]?m="npx jest --coverage --json 2>/dev/null":(h.mocha||h.nyc)&&(m="npx nyc mocha 2>/dev/null")}catch{}d(m,{cwd:r,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),l=!0}catch{}if(s=await Bn(r),s||(s=ao(r)),!s)return I({lineCoverage:0,branchCoverage:0,functionCoverage:0,statementCoverage:0,totalFiles:0,coverageByFile:[],gaps:[],algorithm:"sublinear-O(log n)",warning:l?"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. Run: npm test -- --coverage"})}let a=await n.analyze({coverageData:s,threshold:i,includeFileDetails:t.detectGaps});if(!a.success)return a;let o=a.value,u=[];if(t.detectGaps){let l=await n.findGaps(s,i);l.success&&(u=l.value.gaps.map(d=>({file:d.file,lines:d.lines,risk:d.severity})))}return I({lineCoverage:Math.round(o.summary.line*10)/10,branchCoverage:Math.round(o.summary.branch*10)/10,functionCoverage:Math.round(o.summary.function*10)/10,statementCoverage:Math.round(o.summary.statement*10)/10,totalFiles:o.summary.files,coverageByFile:s.files.map(l=>({file:l.path,lineCoverage:l.lines.total>0?Math.round(l.lines.covered/l.lines.total*1e3)/10:0,branchCoverage:l.branches.total>0?Math.round(l.branches.covered/l.branches.total*1e3)/10:0,functionCoverage:l.functions.total>0?Math.round(l.functions.covered/l.functions.total*1e3)/10:0})),gaps:u,meetsThreshold:o.meetsThreshold,delta:o.delta,recommendations:o.recommendations,algorithm:"sublinear-O(log n)"})}catch(n){return G($(n))}})}import*as Un from"fs/promises";import*as Si from"path";M();function Hn(c){c.registerHandler("scan-security",async e=>{let t=e.payload;try{let n=c.getSecurityScanner(),r=t.target||process.cwd(),i=await re(r);if(i.length===0)return I({vulnerabilities:0,critical:0,high:0,medium:0,low:0,informational:0,topVulnerabilities:[],recommendations:["No source files found to scan"],scanTypes:{sast:t.sast!==!1,dast:t.dast||!1},warning:`No source files found in ${r}`});let s=i.filter(y=>/\.(ts|tsx|js|jsx|mjs|cjs)$/.test(y)),a=i.filter(y=>!/\.(ts|tsx|js|jsx|mjs|cjs)$/.test(y)),o=[];for(let y of i)try{let C=await Un.readFile(y,"utf-8"),b=C.split(`
384
- `),w=y.startsWith(r)?y.slice(r.length).replace(/^\//,""):y,S=[{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 O of S)for(let z=0;z<b.length;z++){let X=[...b[z].matchAll(O.regex)];for(let ee of X)o.push({title:O.title,severity:O.severity,location:{file:w,line:z+1},description:`Potential hardcoded secret found at line ${z+1}`,category:"sensitive-data"})}let T=/(?:execute|query|cursor\.execute)\s*\(\s*(?:f['"]|['"].*%s|['"].*\+\s*\w)/gi;for(let O=0;O<b.length;O++)T.test(b[O])&&o.push({title:"Potential SQL injection",severity:"high",location:{file:w,line:O+1},description:"String interpolation in SQL query \u2014 use parameterized queries",category:"injection"}),T.lastIndex=0;let P=[/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 O of P)if(O.test(C)){o.push({title:"CORS wildcard origin",severity:"high",location:{file:w,line:b.findIndex(z=>O.test(z))+1},description:"CORS configured with wildcard (*) origin \u2014 restrict to specific domains",category:"security-misconfiguration"});break}/(?:DEBUG|debug)\s*[=:]\s*(?:True|true|1)/i.test(C)&&o.push({title:"Debug mode enabled",severity:"medium",location:{file:w,line:b.findIndex(O=>/DEBUG\s*[=:]\s*(?:True|true|1)/i.test(O))+1},description:"Debug mode should be disabled in production",category:"security-misconfiguration"}),/\b(?:eval|exec)\s*\(/i.test(C)&&o.push({title:"Dangerous eval/exec usage",severity:"high",location:{file:w,line:b.findIndex(O=>/\b(?:eval|exec)\s*\(/.test(O))+1},description:"eval/exec can lead to code injection \u2014 avoid using with user input",category:"injection"})}catch{}let u=["requirements.txt","pyproject.toml","Gemfile","go.mod","Cargo.toml"];for(let y of u){let C=Si.join(r,y);try{let b=await Un.readFile(C,"utf-8");if(o.push({title:"Dependency audit recommended",severity:"informational",location:{file:y,line:1},description:`Found ${y} \u2014 run language-specific dependency audit (e.g., pip-audit, npm audit, cargo audit)`,category:"dependencies"}),y==="requirements.txt"||y==="pyproject.toml"){let w=[{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 S of w)S.pattern.test(b)&&o.push({title:S.title,severity:S.severity,location:{file:y,line:b.split(`
385
- `).findIndex(T=>S.pattern.test(T))+1},description:S.description,category:"dependencies"})}}catch{}}let l=s.map(y=>Br.create(y)),d=null;if(t.sast!==!1&&l.length>0){let y=await n.scanFiles(l);y.success&&(d=y.value)}let m=null;if(t.dast&&t.targetUrl){let y=await n.scanUrl(t.targetUrl,{activeScanning:!0,maxDepth:3,timeout:3e4});y.success&&(m=y.value)}let p={critical:o.filter(y=>y.severity==="critical").length,high:o.filter(y=>y.severity==="high").length,medium:o.filter(y=>y.severity==="medium").length,low:o.filter(y=>y.severity==="low").length,informational:o.filter(y=>y.severity==="informational").length},g={critical:(d?.summary?.critical||0)+(m?.summary?.critical||0)+p.critical,high:(d?.summary?.high||0)+(m?.summary?.high||0)+p.high,medium:(d?.summary?.medium||0)+(m?.summary?.medium||0)+p.medium,low:(d?.summary?.low||0)+(m?.summary?.low||0)+p.low,informational:(d?.summary?.informational||0)+(m?.summary?.informational||0)+p.informational},h=[...d?.vulnerabilities||[],...m?.vulnerabilities||[],...o],f=h.sort((y,C)=>{let b={critical:0,high:1,medium:2,low:3,informational:4};return b[y.severity]-b[C.severity]}).slice(0,10).map(y=>({type:y.title,severity:y.severity,file:y.location.file,line:y.location.line,description:y.description})),v=Ci(h);return I({vulnerabilities:h.length,critical:g.critical,high:g.high,medium:g.medium,low:g.low,informational:g.informational,topVulnerabilities:f,recommendations:v,scanTypes:{sast:t.sast!==!1,dast:t.dast||!1},filesScanned:i.length,jstsFilesScanned:s.length,otherFilesScanned:a.length,coverage:d?.coverage,...a.length>0&&s.length===0?{note:"Non-JS/TS files were scanned with cross-language pattern matching. For deeper analysis, use language-specific security tools."}:{}})}catch(n){return G($(n))}})}M();function Vn(c){c.registerHandler("assess-quality",async e=>{let t=e.payload;try{let n=c.getQualityAnalyzer(),r=t.threshold||80,i=[];if(t.sourceFiles&&t.sourceFiles.length>0)i=t.sourceFiles;else if(t.target)i=await re(t.target,{includeTests:!1});else{let l=await import("path"),d=await import("fs"),m=l.join(process.cwd(),"src"),p=d.existsSync(m)?m:process.cwd();i=await re(p,{includeTests:!1})}if(i.length===0)return I({qualityScore:0,passed:!1,threshold:r,metrics:{coverage:0,complexity:0,maintainability:0,testability:0},recommendations:["No source files found for quality assessment"],warning:"No source files found"});let s=await n.analyzeQuality({sourceFiles:i,includeMetrics:t.metrics||["coverage","complexity","maintainability","testability"]});if(!s.success)return s;let a=s.value,o=a.score.overall>=r,u={};for(let l of a.metrics)u[l.name]=l.value;return I({qualityScore:a.score.overall,passed:o,threshold:r,metrics:{coverage:a.score.coverage,complexity:a.score.complexity,maintainability:a.score.maintainability,security:a.score.security,...u},recommendations:a.recommendations.map(l=>`[${l.type}] ${l.title}: ${l.description}`),trends:a.trends.map(l=>({metric:l.metric,direction:l.direction,dataPoints:l.dataPoints.length})),filesAnalyzed:i.length})}catch(n){return G($(n))}})}import*as Ei from"fs/promises";M();function Qn(c){c.registerHandler("validate-requirements",async e=>{let t=e.payload;try{let n=t.requirementsPath||process.cwd(),r=await re(n,{includeTests:!1,languages:[]}),i=[".md",".feature",".gherkin",".txt",".rst"],s=[];for(let a of r)i.some(o=>a.endsWith(o))&&s.push(a);return I({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 G($(n))}}),c.registerHandler("validate-contracts",async e=>{let t=e.payload;try{if(!t.contractPath)return I({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 Ei.readFile(t.contractPath,"utf-8"),r=t.contractPath.endsWith(".json"),i=t.contractPath.endsWith(".yaml")||t.contractPath.endsWith(".yml");return r&&JSON.parse(n),I({contractPath:t.contractPath,valid:!0,format:r?"json":i?"yaml":"unknown",breakingChanges:[],warnings:[],linesAnalyzed:n.split(`
386
- `).length,note:"Structural validation passed. For semantic contract testing, use consumer-driven contract tests."})}catch(n){return I({contractPath:t.contractPath,valid:!1,breakingChanges:[],warnings:[],error:`Could not read or parse contract file: ${E(n)}`})}}catch(n){return G($(n))}})}import*as wi from"fs/promises";import*as Ri from"path";M();function Wn(c){c.registerHandler("index-code",async e=>{let t=e.payload;try{let n=c.getKnowledgeGraph(),r=t.target||process.cwd(),i=Date.now(),s=await re(r,{includeTests:t.includeTests!==!1,languages:t.languages});if(s.length===0)return I({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 o=a.value,u=new Set,l={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 d of s){let m=Ri.extname(d).slice(1),p=l[m];p&&u.add(p)}return I({filesIndexed:o.filesIndexed,nodesCreated:o.nodesCreated,edgesCreated:o.edgesCreated,symbolsExtracted:o.nodesCreated,relationsFound:o.edgesCreated,target:r,incremental:t.incremental||!1,languages:Array.from(u),duration:o.duration,errors:o.errors,warnings:o.warnings})}catch(n){return G($(n))}}),c.registerHandler("predict-defects",async e=>{let t=e.payload;try{let n=t.target||process.cwd(),r=t.minConfidence||.5,i=await re(n,{includeTests:!1});if(i.length===0)return I({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 l of i)try{let d=await wi.readFile(l,"utf-8"),m=d.split(`
387
- `),p=m.length,g=0,h=[];p>500?(g+=.25,h.push(`Large file (${p} lines)`)):p>300&&(g+=.15,h.push(`Medium-large file (${p} lines)`));let f=d.match(/\b(if|else|switch|case|for|while|catch|&&|\|\|)\b/g)||[],v=f.length/Math.max(p,1);v>.15?(g+=.25,h.push(`High branch density (${f.length} branches in ${p} lines)`)):v>.08&&(g+=.1,h.push("Moderate branch complexity")),Math.max(...m.map(w=>{let S=w.match(/^(\s*)/);return S?S[1].length:0}))>20&&(g+=.15,h.push("Deep nesting detected"));let C=(d.match(/\b(TODO|FIXME|HACK|XXX|WORKAROUND)\b/gi)||[]).length;C>3&&(g+=.15,h.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,h.push("Potentially long functions")),g=Math.min(g,.95),g>=r){let w=l.startsWith(n)?l.slice(n.length).replace(/^\//,""):l;s.push({file:w,probability:Math.round(g*100)/100,reason:h.join("; ")})}}catch{}s.sort((l,d)=>d.probability-l.probability);let a=s.length>0?s.reduce((l,d)=>l+d.probability,0)/s.length:0,o=Math.round(a*100),u=[];if(s.length>0){u.push(`${s.length} files flagged for potential defects out of ${i.length} analyzed`);let l=s[0];u.push(`Highest risk: ${l.file} (${Math.round(l.probability*100)}%) \u2014 ${l.reason}`)}return s.some(l=>l.reason.includes("Large file"))&&u.push("Consider splitting large files to reduce complexity"),s.some(l=>l.reason.includes("technical debt"))&&u.push("Address TODO/FIXME comments to reduce technical debt"),s.length===0&&u.push("No files exceeded the defect probability threshold \u2014 code looks healthy"),I({predictedDefects:s.slice(0,20),riskScore:o,recommendations:u,filesAnalyzed:i.length})}catch(n){return G($(n))}})}function Kn(c){c.registerHandler("test-accessibility",async e=>{let t=e.payload;return I({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>")})}),c.registerHandler("run-chaos",async e=>{let t=e.payload;return I({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)."})}),c.registerHandler("optimize-learning",async e=>{try{let t=await import("./unified-memory-hnsw-K7HA3CWV.js");return I({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 I({patternsLearned:0,modelsUpdated:0,memoryConsolidated:!1,note:'Learning system not initialized. Run "aqe init --auto" first.'})}})}var ae=Ce("TaskExecutor");function mo(c){return we.resolve(Ee.CoverageAnalyzerService)(c)}function po(c){return we.resolve(Ee.SecurityScannerService)(c)}function go(c){return we.resolve(Ee.createTestGeneratorService)(c)}function ho(c){return we.resolve(Ee.KnowledgeGraphService)(c)}function fo(c){return we.resolve(Ee.QualityAnalyzerService)(c)}function Ii(c){switch(c){case 0:return"agent-booster";case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}function yo(c){if(["generate-tests","analyze-coverage","scan-security","execute-tests","assess-quality","validate-contracts","test-accessibility","chaos-test","predict-defects","validate-requirements","index-code"].includes(c.type))return null;let t=c.payload?.codeContext||"",n=c.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 Yn=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??".agentic-qe",defaultLanguage:n?.defaultLanguage??"typescript",defaultFramework:n?.defaultFramework??"vitest"},this.resultSaver=mi(this._config.resultsDir),this.registerHandlers()}kernel;eventBus;_config;resultSaver;coverageAnalyzer=null;securityScanner=null;testGenerator=null;knowledgeGraph=null;qualityAnalyzer=null;agentBooster=null;taskRouter=null;qualityFeedbackLoop=null;coherenceActionGate=null;taskHandlers=new Map;get config(){return this._config}registerHandler(e,t){this.taskHandlers.set(e,t)}setQualityFeedbackLoop(e){this.qualityFeedbackLoop=e}getCoverageAnalyzer(){return this.coverageAnalyzer||(this.coverageAnalyzer=mo(this.kernel.memory)),this.coverageAnalyzer}getSecurityScanner(){return this.securityScanner||(this.securityScanner=po(this.kernel.memory)),this.securityScanner}getTestGenerator(){return this.testGenerator||(this.testGenerator=go(this.kernel.memory)),this.testGenerator}getKnowledgeGraph(){return this.knowledgeGraph||(this.knowledgeGraph=ho(this.kernel.memory)),this.knowledgeGraph}getQualityAnalyzer(){return this.qualityAnalyzer||(this.qualityAnalyzer=fo(this.kernel.memory)),this.qualityAnalyzer}registerHandlers(){zn(this),jn(this),Hn(this),Vn(this),Qn(this),Wn(this),Kn(this)}async getAgentBooster(){return this.agentBooster||(this.agentBooster=await Tt({enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7})),this.agentBooster}async getTaskRouterInstance(){if(!this.taskRouter)try{this.taskRouter=await Gt()}catch{return null}return this.taskRouter}async executeWithAgentBooster(e,t,n){let r=yo(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=${Ii(t)}, success=${n}, duration=${r}ms`),this.qualityFeedbackLoop){let s=e.targetDomains||[],a=n?1:0,o=r<100?1:r<500?.8:r<2e3?.6:r<5e3?.4:r<1e4?.2:.1,u=.25*a+.325+.1*o;await this.qualityFeedbackLoop.recordRoutingOutcome({taskId:e.id,taskDescription:e.type,recommendedAgent:String(t),usedAgent:String(t),followedRecommendation:!0,success:n,qualityScore:u,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,o=Ii(i);a&&e.payload&&(e.payload.__compiledContext=a),console.debug(`[TaskExecutor] Executing task ${e.id}: type=${e.type}, tier=${i}, model=${o}, useAgentBooster=${s}${a?", hasContext=true":""}`);let u=this.evaluateCoherenceGate(e,n);u&&console.debug(`[TaskExecutor] Coherence gate: task=${e.id}, decision=${u.decision}, combined=${u.combinedScore.toFixed(3)}, advisory=${u.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=>{ae.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 l=this.taskHandlers.get(e.type);if(!l){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=>{ae.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),p}let d=await Promise.race([l(e),this.timeout(e.timeout||this._config.timeout)]);if(!d.success){let p="error"in d?d.error.message:"Unknown error";return await this.publishTaskFailed(e.id,p,n),this.recordOutcome(e,i,!1,Date.now()-t).catch(g=>{ae.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),{taskId:e.id,success:!1,error:p,duration:Date.now()-t,domain:n}}await this.publishTaskCompleted(e.id,d.value,n),this.recordOutcome(e,i,!0,Date.now()-t).catch(p=>{ae.warn("recordOutcome failed",{error:p instanceof Error?p.message:String(p),taskId:e.id})});let m;if(this._config.saveResults)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(h=>h.path)}catch(p){console.error(`[TaskExecutor] Failed to save results: ${p}`)}return{taskId:e.id,success:!0,data:{...d.value,_routing:{tier:i,model:o,usedAgentBooster:!1}},duration:Date.now()-t,domain:n,savedFiles:m}}catch(l){let d=E(l);return await this.publishTaskFailed(e.id,d,n),this.recordOutcome(e,i,!1,Date.now()-t).catch(m=>{ae.warn("recordOutcome failed",{error:m instanceof Error?m.message:String(m),taskId:e.id})}),{taskId:e.id,success:!1,error:d,duration:Date.now()-t,domain:n}}}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=vi({advisory:!0}));let n=e.payload,r=typeof n?.confidence=="number"?n.confidence:.7,i=n?.riskLevel??"medium";return bi(e.type,t,r,i,n??{},this.coherenceActionGate)}catch(n){return ae.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}=(vt(),Pr(zs));if(s()){let{createReasoningQEC:a}=(Di(),Pr(Mi));this._reasoningQEC=a()}}catch(s){ae.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||ae.warn("ReasoningQEC validation found issues (advisory)",{taskId:e.id,domain:t,confidence:i.confidence,issues:i.issues.length})}catch(n){ae.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:N(),type:"TaskCompleted",timestamp:new Date,source:n,payload:{taskId:e,result:t}})}async publishTaskFailed(e,t,n){await this.eventBus.publish({id:N(),type:"TaskFailed",timestamp:new Date,source:n,payload:{taskId:e,error:t}})}};function Oi(c,e){return new Yn(c,c.eventBus,e)}async function _i(){}import{randomUUID as De}from"crypto";M();var Jn={effectiveness:.25,coverage:.2,mutationKill:.15,stability:.15,maintainability:.15,performance:.1},Zn={"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}},me={qualityWeights:Jn,promotionCriteria:Zn,autoPromote:!0,autoDemote:!0,minCoverageImprovementToLearn:5,maxOutcomesInMemory:1e4,persistOutcomes:!0,batchSize:100};ie();M();H();var er=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}},tr=class c{store;reasoningBank=null;config;db=null;persistCount=0;static RETENTION_CLEANUP_INTERVAL=100;patternMetrics=new Map;constructor(e={}){this.config={...me,...e},this.store=new er(this.config.maxOutcomesInMemory)}connectReasoningBank(e){this.reasoningBank=e}async initialize(){try{this.db=j(),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(`
378
+ ${p}`,estimatedTokens:Math.ceil(p.length/3.5),relevance:.6})}}}finally{i.close()}}catch{return[]}return t}extractDefectKeywords(e){let t=[],n=e.toLowerCase(),r=["bug","defect","regression","fix","crash","error","null","undefined","timeout","race condition","deadlock","memory leak","overflow","injection","broken"];for(let i of r)n.includes(i)&&t.push(i);return t.slice(0,5)}};var to=8e3,no=300*1e3;function ro(){return[new Ot,new Nt,new Ft,new qt,new _t,new Lt]}var Gt=class{sources;maxTokenBudget;cache=new Map;cacheTtl;constructor(e){this.sources=e?.sources||ro(),this.maxTokenBudget=e?.maxTokenBudget||to,this.cacheTtl=e?.cacheTtlMs||no}async compile(e){let t=Date.now(),n=this.buildCacheKey(e),r=this.cache.get(n);if(r&&Date.now()-r.timestamp<this.cacheTtl)return r.result;let i=e.maxTokenBudget||this.maxTokenBudget,s=await Promise.allSettled(this.sources.map(async p=>{try{let g=await p.gather(e);return{sourceId:p.id,sourceName:p.name,priority:p.priority,fragments:g}}catch{return{sourceId:p.id,sourceName:p.name,priority:p.priority,fragments:[]}}})),a=[],o=[];for(let p of s)if(p.status==="fulfilled"){let{sourceId:g,priority:h,fragments:f}=p.value;if(f.length>0){o.push(g);for(let v of f)a.push({...v,sourcePriority:h})}}a.sort((p,g)=>p.sourcePriority!==g.sourcePriority?g.sourcePriority-p.sourcePriority:g.relevance-p.relevance);let u=[],l=0;for(let p of a)if(l+p.estimatedTokens<=i){let{sourcePriority:g,...h}=p;u.push(h),l+=p.estimatedTokens}let m={summary:this.generateSummary(e,u,o),fragments:u,totalTokens:l,sources:o,timestamp:new Date().toISOString(),duration:Date.now()-t};return this.cache.set(n,{result:m,timestamp:Date.now()}),m}clearCache(){this.cache.clear()}getCacheStats(){return{size:this.cache.size,ttlMs:this.cacheTtl}}buildCacheKey(e){return`${e.agentType}:${e.targetFiles.sort().join(",")}:${e.taskDescription.slice(0,100)}`}generateSummary(e,t,n){return[`Context compiled for ${e.agentType} agent.`,`Target: ${e.targetFiles.length} file(s).`,`Sources: ${n.join(", ")}.`,`Fragments: ${t.length} (${t.reduce((r,i)=>r+i.estimatedTokens,0)} est. tokens).`].join(" ")}};function Si(c){let e=[];e.push("## Compiled Context"),e.push(""),e.push(c.summary),e.push("");for(let t of c.fragments)e.push(`### ${t.title}`),e.push(t.content),e.push("");return e.push(`_Context compiled: ${c.timestamp} (${c.duration}ms)_`),e.join(`
379
+ `)}var io={enabled:!0,enableAgentBooster:!0,enableLogging:!0,maxLogEntries:1e3},$n=class c{static instance=null;static initializationPromise=null;config;modelRouter;minCutRouter;routingLog=[];contextCompiler;disposed=!1;constructor(e,t){this.config=e,this.modelRouter=t,this.contextCompiler=new Gt,this.minCutRouter=Ti({enableLogging:e.enableLogging})}static async getInstance(e){if(c.instance&&!c.instance.disposed)return c.instance;if(c.initializationPromise)return c.initializationPromise;c.initializationPromise=c.create(e);try{return c.instance=await c.initializationPromise,c.instance}finally{c.initializationPromise=null}}static async create(e){let t={...io,...e},n;t.enableAgentBooster?n=await wt(t.modelRouterConfig):n=Et(t.modelRouterConfig);let r=new c(t,n);return t.enableLogging&&console.error(`[TaskRouter] Initialized with Agent Booster: ${t.enableAgentBooster}`),r}async routeTask(e){if(!this.config.enabled)return this.createDisabledResult(e);if(this.disposed)throw new Error("TaskRouterService has been disposed");let t=null;if(this.minCutRouter.isEnabled()&&e.agentTopology)try{t=this.minCutRouter.route({task:e.task,domain:e.domain,agentType:e.agentType,agentTopology:e.agentTopology,isCritical:e.isCritical})}catch(g){this.config.enableLogging&&console.error(`[TaskRouter] MinCut routing failed, falling back to heuristic: ${g instanceof Error?g.message:String(g)}`)}let n={task:e.task,codeContext:e.codeContext,filePaths:e.filePaths,manualTier:e.manualTier,isCritical:e.isCritical,agentType:e.agentType,domain:e.domain,metadata:e.metadata},r=await this.modelRouter.route(n),i=r;if(t&&t.usedMinCut){let g=t.modelTier;g!==r.tier&&(i={...r,tier:g,rationale:`[MinCut] ${t.rationale} (heuristic suggested Tier ${r.tier})`},this.config.enableLogging&&console.error(`[TaskRouter] MinCut override: Tier ${r.tier} -> Tier ${g} (lambda=${t.normalizedLambda.toFixed(3)})`))}let s=Re[i.tier],a=this.mapTierToStrategy(i.tier),o={timestamp:i.metadata.timestamp,taskDescription:e.task.slice(0,200),requestedTier:e.manualTier,selectedTier:i.tier,modelId:i.modelId,complexity:i.complexityAnalysis.overall,confidence:i.confidence,wasDowngraded:i.budgetDecision.wasDowngraded,agentBoosterEligible:i.agentBoosterEligible,decisionTimeMs:i.metadata.decisionTimeMs,rationale:i.rationale};this.addLogEntry(o),this.config.enableLogging&&this.logRoutingDecision(o);let u=e.patternHints,l=u&&u.length>0?this.formatPatternContext(u):void 0,d=e.agentType,m=d?xn(d)||xn(d.replace("v3-qe-","qe-")):void 0,p;if(e.filePaths&&e.filePaths.length>0)try{let g=await this.contextCompiler.compile({targetFiles:e.filePaths,agentType:e.agentType||"unknown",taskDescription:e.task});p=Si(g)}catch{}return{decision:i,executionStrategy:a,useAgentBooster:i.agentBoosterEligible,modelId:i.modelId,tierInfo:{tier:i.tier,name:s.name,typicalLatencyMs:s.typicalLatencyMs,relativeCost:s.relativeCost},logEntry:o,patternHints:u,patternContext:l,overlayConfig:m,compiledContext:p}}formatPatternContext(e){if(!e||e.length===0)return"";let t=["--- Relevant Patterns from Learning ---",""];for(let n of e){let r=n.canReuse?" [REUSABLE]":"";t.push(`[${n.name}]${r}`,` ${n.description}`,` Similarity: ${(n.similarity*100).toFixed(0)}% | Confidence: ${(n.confidence*100).toFixed(0)}%`,"")}return t.push("Use these patterns as guidance when applicable."),t.join(`
380
+ `)}async quickRoute(e){return this.routeTask({task:e})}async routeBatch(e){return Promise.all(e.map(t=>this.routeTask(t)))}getMetrics(){return this.modelRouter.getMetrics()}getRoutingLog(e=100,t=0){return this.routingLog.slice(t,t+e)}getRoutingStats(){let e=this.routingLog;if(e.length===0)return this.createEmptyStats();let t=new Map,n=0,r=0,i=0,s=0;for(let o of e)t.set(o.selectedTier,(t.get(o.selectedTier)||0)+1),n+=o.complexity,r+=o.decisionTimeMs,o.wasDowngraded&&i++,o.agentBoosterEligible&&s++;let a={};for(let[o,u]of t)a[o]=u/e.length;return{totalRouted:e.length,avgComplexity:n/e.length,avgDecisionTimeMs:r/e.length,downgradeRate:i/e.length,agentBoosterRate:s/e.length,tierDistribution:a,period:{start:e[0].timestamp,end:e[e.length-1].timestamp}}}reset(){this.routingLog.length=0,this.modelRouter.resetMetrics(),this.config.enableLogging&&console.error("[TaskRouter] Reset routing log and metrics")}async dispose(){this.disposed||(this.disposed=!0,await this.modelRouter.dispose(),c.instance=null,this.config.enableLogging&&console.error("[TaskRouter] Disposed"))}isEnabled(){return this.config.enabled&&!this.disposed}mapTierToStrategy(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"}}addLogEntry(e){this.routingLog.push(e),this.routingLog.length>this.config.maxLogEntries&&this.routingLog.splice(0,this.routingLog.length-this.config.maxLogEntries)}logRoutingDecision(e){let t=Re[e.selectedTier].name,n=e.agentBoosterEligible?"[AgentBooster]":`[Tier${e.selectedTier}]`;console.error(`[TaskRouter] ${n} ${t} | Complexity: ${e.complexity.toFixed(0)} | Confidence: ${(e.confidence*100).toFixed(0)}% | Time: ${e.decisionTimeMs.toFixed(1)}ms`+(e.wasDowngraded?" [DOWNGRADED]":""))}createDisabledResult(e){let n=Re[2],r={timestamp:new Date,taskDescription:e.task.slice(0,200),selectedTier:2,modelId:n.exampleModels[0],complexity:50,confidence:.5,wasDowngraded:!1,agentBoosterEligible:!1,decisionTimeMs:0,rationale:"Routing disabled - using default tier"};return{decision:{tier:2,modelId:n.exampleModels[0],complexityAnalysis:{overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.5,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:2,alternateTiers:[],explanation:"Routing disabled"},budgetDecision:{allowed:!0,reason:"Routing disabled",requestedTier:2,approvedTier:2,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:{tier:2,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:new Date,remainingBudgetUsd:100,remainingRequestsThisHour:100,remainingRequestsToday:1e3},warnings:[]},confidence:.5,rationale:"Routing disabled - using default tier",agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:0,fromCache:!1},warnings:["Routing is disabled"]},executionStrategy:"sonnet",useAgentBooster:!1,modelId:n.exampleModels[0],tierInfo:{tier:2,name:n.name,typicalLatencyMs:n.typicalLatencyMs,relativeCost:n.relativeCost},logEntry:r}}createEmptyStats(){let e=new Date;return{totalRouted:0,avgComplexity:0,avgDecisionTimeMs:0,downgradeRate:0,agentBoosterRate:0,tierDistribution:{},period:{start:e,end:e}}}};async function $t(c){return $n.getInstance(c)}En();vt();var zn=Ce("CoherenceActionGate"),so={structuralPermit:.4,structuralDeny:.2,shiftPermit:.5,shiftDeny:.25,evidencePermit:.5,evidenceDeny:.2,combinedPermit:.5,combinedDeny:.25},Bn={structural:.3,shift:.35,evidence:.35},ao={low:1,medium:.9,high:.75,critical:.6},Ei=1e3,zt=class{thresholds;advisoryMode;nativeAvailable=null;evaluationHistory=[];permitCount=0;deferCount=0;denyCount=0;totalCombinedScore=0;totalStructuralScore=0;totalShiftScore=0;totalEvidenceScore=0;cusumHigh=0;cusumLow=0;cusumMean=.7;cusumK=.05;cusumH=4;cusumSampleCount=0;cusumAlertActive=!1;constructor(e){this.advisoryMode=e?.advisory??!0,this.thresholds={...so,...e?.thresholds}}evaluate(e){let t=this.computeStructuralScore(e),n=this.computeShiftScore(e),r=this.computeEvidenceScore(e),i=t*Bn.structural+n*Bn.shift+r*Bn.evidence,s=ao[e.riskLevel]??1,a=i*s,o=this.computeDecision(t,n,r,a),u=this.buildReasoning(e,o,t,n,r,a),l={decision:o,structuralScore:t,shiftScore:n,evidenceScore:r,combinedScore:a,reasoning:u,advisory:this.advisoryMode};return this.recordEvaluation(l),zn.debug("Action gate evaluation",{action:e.type,domain:e.domain,decision:o,combinedScore:a,advisory:this.advisoryMode}),l}getStatistics(){let e=this.evaluationHistory.length;return{totalEvaluations:e,permitCount:this.permitCount,deferCount:this.deferCount,denyCount:this.denyCount,averageCombinedScore:e>0?this.totalCombinedScore/e:0,averageStructuralScore:e>0?this.totalStructuralScore/e:0,averageShiftScore:e>0?this.totalShiftScore/e:0,averageEvidenceScore:e>0?this.totalEvidenceScore/e:0,advisoryMode:this.advisoryMode}}configureThresholds(e){this.thresholds={...this.thresholds,...e},zn.info("Action gate thresholds updated",{thresholds:this.thresholds})}getThresholds(){return{...this.thresholds}}isAdvisory(){return this.advisoryMode}getEvaluationHistory(){return[...this.evaluationHistory]}resetStatistics(){this.evaluationHistory=[],this.permitCount=0,this.deferCount=0,this.denyCount=0,this.totalCombinedScore=0,this.totalStructuralScore=0,this.totalShiftScore=0,this.totalEvidenceScore=0,this.resetCusum()}resetCusum(){this.cusumHigh=0,this.cusumLow=0,this.cusumAlertActive=!1,this.cusumSampleCount=0}computeStructuralScore(e){let t=.5;["generate-test","modify-code","analyze-coverage","scan-security","assess-quality","validate-contracts","test-accessibility","execute-tests","index-code","predict-defects","validate-requirements","deploy","run-chaos","optimize-learning"].includes(e.type)&&(t+=.2),JSON.stringify(e.context).toLowerCase().includes(e.domain.toLowerCase())&&(t+=.15);let i=Object.keys(e.context);return i.length>=3?t+=.15:i.length>=1&&(t+=.05),Math.min(Math.max(t,0),1)}computeShiftScore(e){let t=e.confidence,r={low:.25,medium:.5,high:.75,critical:1}[e.riskLevel]??.5,i=Math.max(0,r-e.confidence);t-=i*.3;let s=e.context;(s.stale===!0||s.outdated===!0)&&(t-=.3),(s.distributionShift===!0||s.contextChanged===!0)&&(t-=.4),this.cusumSampleCount++;let a=e.confidence;return this.cusumHigh=Math.max(0,this.cusumHigh+(a-this.cusumMean)-this.cusumK),this.cusumLow=Math.max(0,this.cusumLow-(a-this.cusumMean)-this.cusumK),this.cusumHigh>this.cusumH||this.cusumLow>this.cusumH?(t-=.2,this.cusumAlertActive||(this.cusumAlertActive=!0,zn.warn("CUSUM shift detected",{cusumHigh:this.cusumHigh,cusumLow:this.cusumLow}))):this.cusumAlertActive=!1,Math.min(Math.max(t,0),1)}computeEvidenceScore(e){let t=.5,n=e.context,r=["testResults","coverageData","securityScan","qualityReport","peerReview","analysisResult","validationPassed","precedent","historicalSuccess"];for(let s of r)n[s]!==void 0&&n[s]!==null&&(t*=1+.15);let i=["errors","failures","warnings","regressions","conflictingResults","noTestCoverage"];for(let s of i)n[s]!==void 0&&n[s]!==null&&(t*=1-.18);if((e.riskLevel==="critical"||e.riskLevel==="high")&&!n.testResults&&!n.peerReview&&(t-=.15),typeof n.evidenceCount=="number"){let s=n.evidenceCount;t+=Math.min(s*.05,.2)}return Math.min(Math.max(t,0),1)}computeDecision(e,t,n,r){return e<this.thresholds.structuralDeny||t<this.thresholds.shiftDeny||n<this.thresholds.evidenceDeny||r<this.thresholds.combinedDeny?"DENY":e>=this.thresholds.structuralPermit&&t>=this.thresholds.shiftPermit&&n>=this.thresholds.evidencePermit&&r>=this.thresholds.combinedPermit?"PERMIT":"DEFER"}buildReasoning(e,t,n,r,i,s){let a=[];if(a.push(`Decision: ${t} for ${e.type} (${e.domain}).`),a.push(`Scores: structural=${n.toFixed(2)}, shift=${r.toFixed(2)}, evidence=${i.toFixed(2)}, combined=${s.toFixed(2)}.`),t==="DENY")n<this.thresholds.structuralDeny&&a.push("Structural filter failed: action does not fit codebase graph."),r<this.thresholds.shiftDeny&&a.push("Shift filter failed: significant context distribution shift detected."),i<this.thresholds.evidenceDeny&&a.push("Evidence filter failed: insufficient evidence to justify action."),s<this.thresholds.combinedDeny&&a.push("Combined score below minimum threshold.");else if(t==="DEFER"){let o=[];n<this.thresholds.structuralPermit&&o.push("structural"),r<this.thresholds.shiftPermit&&o.push("shift"),i<this.thresholds.evidencePermit&&o.push("evidence"),o.length>0&&a.push(`Marginal filters: ${o.join(", ")}. Human review recommended.`)}return this.advisoryMode&&a.push("(Advisory mode: decision logged only, not enforced.)"),a.join(" ")}recordEvaluation(e){switch(this.evaluationHistory.push(e),this.evaluationHistory.length>Ei&&(this.evaluationHistory=this.evaluationHistory.slice(-Ei)),this.totalCombinedScore+=e.combinedScore,this.totalStructuralScore+=e.structuralScore,this.totalShiftScore+=e.shiftScore,this.totalEvidenceScore+=e.evidenceScore,e.decision){case"PERMIT":this.permitCount++;break;case"DEFER":this.deferCount++;break;case"DENY":this.denyCount++;break}}};function wi(c){return new zt(c)}function Ri(c,e,t,n,r,i){if(!Te().useCoherenceActionGate)return null;let a=i??new zt,o={type:c,domain:e,confidence:t,context:r,riskLevel:n};return a.evaluate(o)}import*as Bt from"fs/promises";k();function oo(c){return c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function co(c,e,t,n){if(!t)return{testCode:c,sourceFile:e};let r=m=>m.replace(/\.[a-z]+$/i,""),i=n?n.match(/\.(ts|tsx|js|jsx|mjs|cjs)$/i)?r(n):n:"./module-under-test",s=n?"":`// TODO: replace './module-under-test' with the actual import path of the module under test
381
+ `,a=r(t),o=oo(a),u=new RegExp(o+"(?:\\.[a-zA-Z]+){0,2}","g");return{testCode:c&&s+c.replace(u,i),sourceFile:e===t&&n||e}}function jn(c){c.registerHandler("generate-tests",async e=>{let t=e.payload;try{let n=c.getTestGenerator(),r=[],i;if(t.sourceFiles&&t.sourceFiles.length>0)r=t.sourceFiles;else if(t.filePath)r=[t.filePath];else if(t.sourceCode){let m={python:".py",typescript:".ts",javascript:".js",go:".go",rust:".rs",java:".java",ruby:".rb",kotlin:".kt",csharp:".cs",php:".php",swift:".swift",cpp:".cpp",c:".c",scala:".scala"}[t.language?.toLowerCase()||"typescript"]||".ts";i=`/tmp/aqe-temp-${N()}${m}`,await Bt.writeFile(i,t.sourceCode,"utf-8"),r=[i]}if(r.length===0)return I({testsGenerated:0,coverageEstimate:0,tests:[],patternsUsed:[],warning:"No source files or code provided for test generation. Provide sourceCode, filePath, or sourceFiles in the payload."});let s=t.framework||"vitest",a=i?{[i]:t.filePath?t.filePath.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/i,""):"./module-under-test"}:void 0,o=await n.generateTests({sourceFiles:r,testType:t.testType||"unit",framework:s,coverageTarget:t.coverageGoal||80,patterns:[],importPathOverrides:a});if(i)try{await Bt.unlink(i)}catch{}if(!o.success)return o;let u=o.value,l=u.tests.map(d=>{let m=co(d.testCode,d.sourceFile,i,t.filePath);return{name:d.name,file:d.testFile,type:d.type,sourceFile:m.sourceFile,assertions:d.assertions,testCode:m.testCode}});return I({testsGenerated:l.length,coverageEstimate:u.coverageEstimate,tests:l,patternsUsed:u.patternsUsed})}catch(n){return G($(n))}}),c.registerHandler("execute-tests",async e=>{let t=e.payload;try{let n=t.testFiles||[];if(n.length===0)return I({total:0,passed:0,failed:0,skipped:0,duration:0,coverage:0,failedTests:[],warning:"No test files specified. Provide testFiles array with paths to test files."});let r=process.cwd(),i,s=/^[a-zA-Z0-9_.\/\-@]+$/,a=n.filter(o=>s.test(o));if(a.length!==n.length)return I({total:0,passed:0,failed:0,skipped:0,duration:0,coverage:0,failedTests:[],warning:"Some test file paths contain invalid characters and were rejected."});try{let{spawnSync:o}=await import("child_process"),u=o("npx",["vitest","run",...a,"--reporter=json"],{cwd:r,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});i=u.stdout||"",!i.includes("{")&&u.status!==0&&(i=o("npx",["jest",...a,"--json"],{cwd:r,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).stdout||"")}catch(o){i=o.stdout||""}try{let o=i.indexOf("{");if(o>=0){let u=JSON.parse(i.slice(o));if(u.testResults){let l=u.numTotalTests||0,d=u.numPassedTests||0,m=u.numFailedTests||0;return I({total:l,passed:d,failed:m,skipped:l-d-m,duration:0,coverage:0,failedTests:[]})}}}catch{}return I({total:n.length,passed:0,failed:0,skipped:0,duration:0,coverage:0,failedTests:[],warning:"Could not parse test runner output. Check that vitest or jest is installed.",rawOutput:i.slice(0,500)})}catch(n){return G($(n))}})}import*as xi from"fs/promises";import*as se from"fs";import*as Me from"path";k();H();H();import*as ke from"fs/promises";import*as Z from"path";async function Un(c){let e=[Z.join(c,"coverage","coverage-final.json"),Z.join(c,"coverage","lcov.info"),Z.join(c,".nyc_output","coverage-final.json"),Z.join(c,"coverage-final.json"),Z.join(c,"coverage.xml"),Z.join(c,"htmlcov","status.json"),Z.join(c,"cobertura-coverage.xml")];for(let t of e)try{let n=await ke.readFile(t,"utf-8");if(t.endsWith(".json"))return lo(n);if(t.endsWith(".info"))return uo(n);if(t.endsWith(".xml"))return mo(n)}catch{}return null}function lo(c){let e=A(c),t=[],n=0,r=0,i=0,s=0,a=0,o=0,u=0,l=0;for(let[d,m]of Object.entries(e)){let p=m,g=p.statementMap||{},h=p.s||{},f=p.branchMap||{},v=p.b||{},y=p.f||{},C=Object.keys(h).length,b=Object.values(h).filter(q=>q>0).length,w=Object.values(v).flat().length,E=Object.values(v).flat().filter(q=>q>0).length,S=Object.keys(y).length,x=Object.values(y).filter(q=>q>0).length,O=Object.keys(g).length,z=Object.values(h).filter(q=>q>0).length,X=[];for(let[q,V]of Object.entries(h))if(V===0){let ge=g[q];ge?.start?.line&&X.push(ge.start.line)}let ee=[];for(let[q,V]of Object.entries(v)){let ge=f[q];V.forEach((gt,Y)=>{gt===0&&ge?.locations?.[Y]?.start?.line&&ee.push(ge.locations[Y].start.line)})}t.push({path:d,lines:{covered:b,total:C},branches:{covered:E,total:w},functions:{covered:x,total:S},statements:{covered:z,total:O},uncoveredLines:Array.from(new Set(X)).sort((q,V)=>q-V),uncoveredBranches:Array.from(new Set(ee)).sort((q,V)=>q-V)}),n+=C,r+=b,i+=w,s+=E,a+=S,o+=x,u+=O,l+=z}return{files:t,summary:{line:n>0?r/n*100:0,branch:i>0?s/i*100:0,function:a>0?o/a*100:0,statement:u>0?l/u*100:0,files:t.length}}}function uo(c){let e=[],t=c.split(`
382
+ `),n=null,r=0,i=0,s=0,a=0,o=0,u=0,l=[],d=[];for(let y of t)if(y.startsWith("SF:"))n=y.slice(3);else if(y.startsWith("LF:"))r=parseInt(y.slice(3),10);else if(y.startsWith("LH:"))i=parseInt(y.slice(3),10);else if(y.startsWith("BRF:"))s=parseInt(y.slice(4),10);else if(y.startsWith("BRH:"))a=parseInt(y.slice(4),10);else if(y.startsWith("FNF:"))o=parseInt(y.slice(4),10);else if(y.startsWith("FNH:"))u=parseInt(y.slice(4),10);else if(y.startsWith("DA:")){let[C,b]=y.slice(3).split(",").map(w=>parseInt(w,10));b===0&&l.push(C)}else if(y.startsWith("BRDA:")){let C=y.slice(5).split(","),b=parseInt(C[0],10),w=C[3];(w==="0"||w==="-")&&d.push(b)}else y==="end_of_record"&&n&&(e.push({path:n,lines:{covered:i,total:r},branches:{covered:a,total:s},functions:{covered:u,total:o},statements:{covered:i,total:r},uncoveredLines:Array.from(new Set(l)),uncoveredBranches:Array.from(new Set(d))}),n=null,r=i=0,s=a=0,o=u=0,l.length=0,d.length=0);let m=0,p=0,g=0,h=0,f=0,v=0;for(let y of e)m+=y.lines.total,p+=y.lines.covered,g+=y.branches.total,h+=y.branches.covered,f+=y.functions.total,v+=y.functions.covered;return{files:e,summary:{line:m>0?p/m*100:0,branch:g>0?h/g*100:0,function:f>0?v/f*100:0,statement:m>0?p/m*100:0,files:e.length}}}function mo(c){let e=[];function t(g,h){let f=g.match(new RegExp(`${h}=["']([^"']*)["']`));return f?f[1]:null}let n=/<class\s[^>]*?>/g,r;for(;(r=n.exec(c))!==null;){let g=r[0],h=t(g,"filename");if(!h)continue;let f=parseFloat(t(g,"line-rate")||"NaN"),v=parseFloat(t(g,"branch-rate")||"NaN"),y=r.index,C=c.indexOf("</class>",y),b=C>y?c.slice(y,C):"",w=0,E=0,S=0,x=0,O=0,z=0,X=[],ee=[],q=/<line\s([^>]*?)\/>/g,V;for(;(V=q.exec(b))!==null;){let Y=V[1],ze=parseInt(t(Y,"number")||"0",10),ht=parseInt(t(Y,"hits")||"0",10),Cn=t(Y,"branch")==="true",Be=t(Y,"condition-coverage");w++,ht>0?E++:X.push(ze),Cn&&(S++,(Be?parseInt(Be,10):ht>0?100:0)===100?x++:ee.push(ze))}let ge=/<method\s([^>]*?)>/g,gt;for(;(gt=ge.exec(b))!==null;){O++;let Y=gt.index,ze=b.indexOf("</method>",Y);if(ze>Y){let ht=b.slice(Y,ze),Cn=/<line\s([^>]*?)\/>/g,Be=!1,Tn;for(;(Tn=Cn.exec(ht))!==null;)if(parseInt(t(Tn[1],"hits")||"0",10)>0){Be=!0;break}Be&&z++}}w===0&&!isNaN(f)&&(w=1,E=f>=.5?1:0),e.push({path:h,lines:{covered:E,total:w},branches:{covered:x,total:S},functions:{covered:z,total:O},statements:{covered:E,total:w},uncoveredLines:X,uncoveredBranches:ee})}let i=0,s=0,a=0,o=0,u=0,l=0;for(let g of e)i+=g.lines.total,s+=g.lines.covered,a+=g.branches.total,o+=g.branches.covered,u+=g.functions.total,l+=g.functions.covered;let d=c.match(/<coverage\s[^>]*?>/),m=d?parseFloat(t(d[0],"line-rate")||"NaN")*100:NaN,p=d?parseFloat(t(d[0],"branch-rate")||"NaN")*100:NaN;return{files:e,summary:{line:isNaN(m)?i>0?s/i*100:0:m,branch:isNaN(p)?a>0?o/a*100:0:p,function:u>0?l/u*100:0,statement:i>0?s/i*100:0,files:e.length}}}async function re(c,e={}){let t=[],{includeTests:n=!0,languages:r,maxFiles:i=5e3}=e,s=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".go",".rs",".java",".kt",".kts",".rb",".cs",".php",".swift",".c",".h",".cpp",".hpp",".cc",".scala"];if(r&&r.length>0){s=[];for(let o of r)o==="typescript"&&s.push(".ts",".tsx"),o==="javascript"&&s.push(".js",".jsx",".mjs",".cjs"),o==="python"&&s.push(".py",".pyw"),o==="go"&&s.push(".go"),o==="rust"&&s.push(".rs"),o==="java"&&s.push(".java"),o==="kotlin"&&s.push(".kt",".kts"),o==="ruby"&&s.push(".rb"),(o==="csharp"||o==="c#")&&s.push(".cs"),o==="php"&&s.push(".php"),o==="swift"&&s.push(".swift"),(o==="c"||o==="cpp"||o==="c++")&&s.push(".c",".h",".cpp",".hpp",".cc"),o==="scala"&&s.push(".scala")}async function a(o){try{let u=await ke.readdir(o,{withFileTypes:!0});for(let l of u){let d=Z.join(o,l.name);if(l.isDirectory()){if(["node_modules",".git","dist","build","coverage",".nyc_output","__pycache__",".venv","venv",".tox",".mypy_cache","target",".gradle","vendor",".bundle",".agentic-qe",".claude",".cache",".npm",".yarn",".next",".nuxt",".svelte-kit","out",".turbo","tmp","temp",".tmp"].includes(l.name))continue;if(t.length>=i)return;await a(d)}else if(l.isFile()){let m=Z.extname(l.name);if(!s.includes(m)||!n&&(l.name.includes(".test.")||l.name.includes(".spec.")||l.name.endsWith("_test.ts")||l.name.endsWith("_test.js")||d.includes("/__tests__/")||d.includes("/test/")||d.includes("/tests/")))continue;if(t.length>=i)return;t.push(d)}}}catch{}}try{if((await ke.stat(c)).isFile())return[c];await a(c)}catch{}return t}function Pi(c){let e=new Set,t={injection:"Use parameterized queries and input validation to prevent injection attacks",xss:"Sanitize user input and use Content-Security-Policy headers","sensitive-data":"Never hardcode secrets; use environment variables or secret managers","access-control":"Implement proper authentication and authorization checks","security-misconfiguration":"Review and harden security configurations","insecure-deserialization":"Avoid deserializing untrusted data; use safe alternatives","broken-auth":"Use strong authentication mechanisms and secure session management",dependencies:"Keep dependencies updated and regularly audit for vulnerabilities"};for(let i of c){let s=t[i.category];s&&e.add(s)}let n=c.some(i=>i.severity==="critical"),r=c.some(i=>i.severity==="high");return n&&e.add("CRITICAL: Address critical vulnerabilities immediately before deployment"),r&&e.add("Prioritize fixing high-severity issues in the next sprint"),e.size===0&&c.length===0&&e.add("No vulnerabilities found - maintain current security practices"),Array.from(e)}function po(c){let e=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]),t=new Set(["node_modules","dist","build","coverage",".git",".claude",".agentic-qe","__pycache__",".venv"]),n=[".test.",".spec.","_test.","_spec."];if(!se.existsSync(c)||!se.statSync(c).isDirectory())return null;let r=[];function i(g,h){if(h>6)return;let f;try{f=se.readdirSync(g,{withFileTypes:!0})}catch{return}for(let v of f)if(v.isDirectory()){if(t.has(v.name))continue;i(Me.join(g,v.name),h+1)}else if(v.isFile()){let y=Me.extname(v.name);if(!e.has(y)||n.some(C=>v.name.includes(C)))continue;r.push(Me.join(g,v.name))}}if(i(c,0),r.length===0)return null;let s=r.map(g=>{let h="";try{h=se.readFileSync(g,"utf-8")}catch{}let v=h.split(`
383
+ `).length,y=Math.max((h.match(/\b(function|=>)\b/g)||[]).length,1),C=Math.max((h.match(/\b(if|switch|case|\?\?|\|\|)\b/g)||[]).length,1),w=[g.replace(".ts",".test.ts").replace("/src/","/tests/"),g.replace(".ts",".spec.ts").replace("/src/","/tests/"),g.replace(".ts",".test.ts"),g.replace(".js",".test.js"),g.replace(".js",".test.js").replace("/src/","/tests/")].some(q=>se.existsSync(q)),E=Math.min(C*.005,.15),S=Math.min(v*1e-4,.1),x=Math.max(.05,Math.min(.95,w?.85-E-S:.2)),O=Math.floor(v*x),z=Math.min(Math.floor(O*.7),C),X=Math.min(Math.floor(y*x*.9),y),ee=Array.from({length:v-O},(q,V)=>V+O+1);return{path:g,lines:{covered:O,total:v},branches:{covered:z,total:C},functions:{covered:X,total:y},statements:{covered:O,total:v},uncoveredLines:ee,uncoveredBranches:ee.slice(0,Math.floor(ee.length/2))}}),a=s.reduce((g,h)=>g+h.lines.total,0),o=s.reduce((g,h)=>g+h.lines.covered,0),u=s.reduce((g,h)=>g+h.branches.total,0),l=s.reduce((g,h)=>g+h.branches.covered,0),d=s.reduce((g,h)=>g+h.functions.total,0),m=s.reduce((g,h)=>g+h.functions.covered,0),p=(g,h)=>h>0?Math.round(g/h*100):0;return{files:s,summary:{line:p(o,a),branch:p(l,u),function:p(m,d),statement:p(o,a),files:s.length}}}function Hn(c){c.registerHandler("analyze-coverage",async e=>{let t=e.payload;try{let n=c.getCoverageAnalyzer(),r=t.target||process.cwd(),i=t.threshold||80,s=await Un(r);if(!s){let l=!1;try{let{execSync:d}=await import("child_process"),m="npx vitest run --coverage --reporter=json 2>/dev/null";try{let p=await xi.readFile(Me.join(r,"package.json"),"utf-8"),g=A(p),h={...g.devDependencies||{},...g.dependencies||{}};h.jest||h["@jest/core"]?m="npx jest --coverage --json 2>/dev/null":(h.mocha||h.nyc)&&(m="npx nyc mocha 2>/dev/null")}catch{}d(m,{cwd:r,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),l=!0}catch{}if(s=await Un(r),s||(s=po(r)),!s)return I({lineCoverage:0,branchCoverage:0,functionCoverage:0,statementCoverage:0,totalFiles:0,coverageByFile:[],gaps:[],algorithm:"sublinear-O(log n)",warning:l?"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. Run: npm test -- --coverage"})}let a=await n.analyze({coverageData:s,threshold:i,includeFileDetails:t.detectGaps});if(!a.success)return a;let o=a.value,u=[];if(t.detectGaps){let l=await n.findGaps(s,i);l.success&&(u=l.value.gaps.map(d=>({file:d.file,lines:d.lines,risk:d.severity})))}return I({lineCoverage:Math.round(o.summary.line*10)/10,branchCoverage:Math.round(o.summary.branch*10)/10,functionCoverage:Math.round(o.summary.function*10)/10,statementCoverage:Math.round(o.summary.statement*10)/10,totalFiles:o.summary.files,coverageByFile:s.files.map(l=>({file:l.path,lineCoverage:l.lines.total>0?Math.round(l.lines.covered/l.lines.total*1e3)/10:0,branchCoverage:l.branches.total>0?Math.round(l.branches.covered/l.branches.total*1e3)/10:0,functionCoverage:l.functions.total>0?Math.round(l.functions.covered/l.functions.total*1e3)/10:0})),gaps:u,meetsThreshold:o.meetsThreshold,delta:o.delta,recommendations:o.recommendations,algorithm:"sublinear-O(log n)"})}catch(n){return G($(n))}})}import*as Vn from"fs/promises";import*as Ai from"path";k();function Qn(c){c.registerHandler("scan-security",async e=>{let t=e.payload;try{let n=c.getSecurityScanner(),r=t.target||process.cwd(),i=await re(r);if(i.length===0)return I({vulnerabilities:0,critical:0,high:0,medium:0,low:0,informational:0,topVulnerabilities:[],recommendations:["No source files found to scan"],scanTypes:{sast:t.sast!==!1,dast:t.dast||!1},warning:`No source files found in ${r}`});let s=i.filter(y=>/\.(ts|tsx|js|jsx|mjs|cjs)$/.test(y)),a=i.filter(y=>!/\.(ts|tsx|js|jsx|mjs|cjs)$/.test(y)),o=[];for(let y of i)try{let C=await Vn.readFile(y,"utf-8"),b=C.split(`
384
+ `),w=y.startsWith(r)?y.slice(r.length).replace(/^\//,""):y,E=[{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 O of E)for(let z=0;z<b.length;z++){let X=[...b[z].matchAll(O.regex)];for(let ee of X)o.push({title:O.title,severity:O.severity,location:{file:w,line:z+1},description:`Potential hardcoded secret found at line ${z+1}`,category:"sensitive-data"})}let S=/(?:execute|query|cursor\.execute)\s*\(\s*(?:f['"]|['"].*%s|['"].*\+\s*\w)/gi;for(let O=0;O<b.length;O++)S.test(b[O])&&o.push({title:"Potential SQL injection",severity:"high",location:{file:w,line:O+1},description:"String interpolation in SQL query \u2014 use parameterized queries",category:"injection"}),S.lastIndex=0;let x=[/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 O of x)if(O.test(C)){o.push({title:"CORS wildcard origin",severity:"high",location:{file:w,line:b.findIndex(z=>O.test(z))+1},description:"CORS configured with wildcard (*) origin \u2014 restrict to specific domains",category:"security-misconfiguration"});break}/(?:DEBUG|debug)\s*[=:]\s*(?:True|true|1)/i.test(C)&&o.push({title:"Debug mode enabled",severity:"medium",location:{file:w,line:b.findIndex(O=>/DEBUG\s*[=:]\s*(?:True|true|1)/i.test(O))+1},description:"Debug mode should be disabled in production",category:"security-misconfiguration"}),/\b(?:eval|exec)\s*\(/i.test(C)&&o.push({title:"Dangerous eval/exec usage",severity:"high",location:{file:w,line:b.findIndex(O=>/\b(?:eval|exec)\s*\(/.test(O))+1},description:"eval/exec can lead to code injection \u2014 avoid using with user input",category:"injection"})}catch{}let u=["requirements.txt","pyproject.toml","Gemfile","go.mod","Cargo.toml"];for(let y of u){let C=Ai.join(r,y);try{let b=await Vn.readFile(C,"utf-8");if(o.push({title:"Dependency audit recommended",severity:"informational",location:{file:y,line:1},description:`Found ${y} \u2014 run language-specific dependency audit (e.g., pip-audit, npm audit, cargo audit)`,category:"dependencies"}),y==="requirements.txt"||y==="pyproject.toml"){let w=[{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 E of w)E.pattern.test(b)&&o.push({title:E.title,severity:E.severity,location:{file:y,line:b.split(`
385
+ `).findIndex(S=>E.pattern.test(S))+1},description:E.description,category:"dependencies"})}}catch{}}let l=s.map(y=>Wr.create(y)),d=null;if(t.sast!==!1&&l.length>0){let y=await n.scanFiles(l);y.success&&(d=y.value)}let m=null;if(t.dast&&t.targetUrl){let y=await n.scanUrl(t.targetUrl,{activeScanning:!0,maxDepth:3,timeout:3e4});y.success&&(m=y.value)}let p={critical:o.filter(y=>y.severity==="critical").length,high:o.filter(y=>y.severity==="high").length,medium:o.filter(y=>y.severity==="medium").length,low:o.filter(y=>y.severity==="low").length,informational:o.filter(y=>y.severity==="informational").length},g={critical:(d?.summary?.critical||0)+(m?.summary?.critical||0)+p.critical,high:(d?.summary?.high||0)+(m?.summary?.high||0)+p.high,medium:(d?.summary?.medium||0)+(m?.summary?.medium||0)+p.medium,low:(d?.summary?.low||0)+(m?.summary?.low||0)+p.low,informational:(d?.summary?.informational||0)+(m?.summary?.informational||0)+p.informational},h=[...d?.vulnerabilities||[],...m?.vulnerabilities||[],...o],f=h.sort((y,C)=>{let b={critical:0,high:1,medium:2,low:3,informational:4};return b[y.severity]-b[C.severity]}).slice(0,10).map(y=>({type:y.title,severity:y.severity,file:y.location.file,line:y.location.line,description:y.description})),v=Pi(h);return I({vulnerabilities:h.length,critical:g.critical,high:g.high,medium:g.medium,low:g.low,informational:g.informational,topVulnerabilities:f,recommendations:v,scanTypes:{sast:t.sast!==!1,dast:t.dast||!1},filesScanned:i.length,jstsFilesScanned:s.length,otherFilesScanned:a.length,coverage:d?.coverage,...a.length>0&&s.length===0?{note:"Non-JS/TS files were scanned with cross-language pattern matching. For deeper analysis, use language-specific security tools."}:{}})}catch(n){return G($(n))}})}k();function Wn(c){c.registerHandler("assess-quality",async e=>{let t=e.payload;try{let n=c.getQualityAnalyzer(),r=t.threshold||80,i=[];if(t.sourceFiles&&t.sourceFiles.length>0)i=t.sourceFiles;else if(t.target)i=await re(t.target,{includeTests:!1});else{let l=await import("path"),d=await import("fs"),m=l.join(process.cwd(),"src"),p=d.existsSync(m)?m:process.cwd();i=await re(p,{includeTests:!1})}if(i.length===0)return I({qualityScore:0,passed:!1,threshold:r,metrics:{coverage:0,complexity:0,maintainability:0,testability:0},recommendations:["No source files found for quality assessment"],warning:"No source files found"});let s=await n.analyzeQuality({sourceFiles:i,includeMetrics:t.metrics||["coverage","complexity","maintainability","testability"]});if(!s.success)return s;let a=s.value,o=a.score.overall>=r,u={};for(let l of a.metrics)u[l.name]=l.value;return I({qualityScore:a.score.overall,passed:o,threshold:r,metrics:{coverage:a.score.coverage,complexity:a.score.complexity,maintainability:a.score.maintainability,security:a.score.security,...u},recommendations:a.recommendations.map(l=>`[${l.type}] ${l.title}: ${l.description}`),trends:a.trends.map(l=>({metric:l.metric,direction:l.direction,dataPoints:l.dataPoints.length})),filesAnalyzed:i.length})}catch(n){return G($(n))}})}import*as ki from"fs/promises";k();function Kn(c){c.registerHandler("validate-requirements",async e=>{let t=e.payload;try{let n=t.requirementsPath||process.cwd(),r=await re(n,{includeTests:!1,languages:[]}),i=[".md",".feature",".gherkin",".txt",".rst"],s=[];for(let a of r)i.some(o=>a.endsWith(o))&&s.push(a);return I({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 G($(n))}}),c.registerHandler("validate-contracts",async e=>{let t=e.payload;try{if(!t.contractPath)return I({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 ki.readFile(t.contractPath,"utf-8"),r=t.contractPath.endsWith(".json"),i=t.contractPath.endsWith(".yaml")||t.contractPath.endsWith(".yml");return r&&JSON.parse(n),I({contractPath:t.contractPath,valid:!0,format:r?"json":i?"yaml":"unknown",breakingChanges:[],warnings:[],linesAnalyzed:n.split(`
386
+ `).length,note:"Structural validation passed. For semantic contract testing, use consumer-driven contract tests."})}catch(n){return I({contractPath:t.contractPath,valid:!1,breakingChanges:[],warnings:[],error:`Could not read or parse contract file: ${T(n)}`})}}catch(n){return G($(n))}})}import*as Mi from"fs/promises";import*as Di from"path";k();function Xn(c){c.registerHandler("index-code",async e=>{let t=e.payload;try{let n=c.getKnowledgeGraph(),r=t.target||process.cwd(),i=Date.now(),s=await re(r,{includeTests:t.includeTests!==!1,languages:t.languages});if(s.length===0)return I({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 o=a.value,u=new Set,l={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 d of s){let m=Di.extname(d).slice(1),p=l[m];p&&u.add(p)}return I({filesIndexed:o.filesIndexed,nodesCreated:o.nodesCreated,edgesCreated:o.edgesCreated,symbolsExtracted:o.nodesCreated,relationsFound:o.edgesCreated,target:r,incremental:t.incremental||!1,languages:Array.from(u),duration:o.duration,errors:o.errors,warnings:o.warnings})}catch(n){return G($(n))}}),c.registerHandler("predict-defects",async e=>{let t=e.payload;try{let n=t.target||process.cwd(),r=t.minConfidence||.5,i=await re(n,{includeTests:!1});if(i.length===0)return I({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 l of i)try{let d=await Mi.readFile(l,"utf-8"),m=d.split(`
387
+ `),p=m.length,g=0,h=[];p>500?(g+=.25,h.push(`Large file (${p} lines)`)):p>300&&(g+=.15,h.push(`Medium-large file (${p} lines)`));let f=d.match(/\b(if|else|switch|case|for|while|catch|&&|\|\|)\b/g)||[],v=f.length/Math.max(p,1);v>.15?(g+=.25,h.push(`High branch density (${f.length} branches in ${p} lines)`)):v>.08&&(g+=.1,h.push("Moderate branch complexity")),Math.max(...m.map(w=>{let E=w.match(/^(\s*)/);return E?E[1].length:0}))>20&&(g+=.15,h.push("Deep nesting detected"));let C=(d.match(/\b(TODO|FIXME|HACK|XXX|WORKAROUND)\b/gi)||[]).length;C>3&&(g+=.15,h.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,h.push("Potentially long functions")),g=Math.min(g,.95),g>=r){let w=l.startsWith(n)?l.slice(n.length).replace(/^\//,""):l;s.push({file:w,probability:Math.round(g*100)/100,reason:h.join("; ")})}}catch{}s.sort((l,d)=>d.probability-l.probability);let a=s.length>0?s.reduce((l,d)=>l+d.probability,0)/s.length:0,o=Math.round(a*100),u=[];if(s.length>0){u.push(`${s.length} files flagged for potential defects out of ${i.length} analyzed`);let l=s[0];u.push(`Highest risk: ${l.file} (${Math.round(l.probability*100)}%) \u2014 ${l.reason}`)}return s.some(l=>l.reason.includes("Large file"))&&u.push("Consider splitting large files to reduce complexity"),s.some(l=>l.reason.includes("technical debt"))&&u.push("Address TODO/FIXME comments to reduce technical debt"),s.length===0&&u.push("No files exceeded the defect probability threshold \u2014 code looks healthy"),I({predictedDefects:s.slice(0,20),riskScore:o,recommendations:u,filesAnalyzed:i.length})}catch(n){return G($(n))}})}function Yn(c){c.registerHandler("test-accessibility",async e=>{let t=e.payload;return I({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>")})}),c.registerHandler("run-chaos",async e=>{let t=e.payload;return I({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)."})}),c.registerHandler("optimize-learning",async e=>{try{let t=await import("./unified-memory-hnsw-6NQPYA5C.js");return I({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 I({patternsLearned:0,modelsUpdated:0,memoryConsolidated:!1,note:'Learning system not initialized. Run "aqe init --auto" first.'})}})}var ae=Ce("TaskExecutor");function vo(c){return we.resolve(Ee.CoverageAnalyzerService)(c)}function bo(c){return we.resolve(Ee.SecurityScannerService)(c)}function Co(c){return we.resolve(Ee.createTestGeneratorService)(c)}function To(c){return we.resolve(Ee.KnowledgeGraphService)(c)}function So(c){return we.resolve(Ee.QualityAnalyzerService)(c)}function qi(c){switch(c){case 0:return"agent-booster";case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}function Eo(c){if(["generate-tests","analyze-coverage","scan-security","execute-tests","assess-quality","validate-contracts","test-accessibility","chaos-test","predict-defects","validate-requirements","index-code"].includes(c.type))return null;let t=c.payload?.codeContext||"",n=c.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 Zn=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??".agentic-qe",defaultLanguage:n?.defaultLanguage??"typescript",defaultFramework:n?.defaultFramework??"vitest"},this.resultSaver=vi(this._config.resultsDir),this.registerHandlers()}kernel;eventBus;_config;resultSaver;coverageAnalyzer=null;securityScanner=null;testGenerator=null;knowledgeGraph=null;qualityAnalyzer=null;agentBooster=null;taskRouter=null;qualityFeedbackLoop=null;coherenceActionGate=null;taskHandlers=new Map;get config(){return this._config}registerHandler(e,t){this.taskHandlers.set(e,t)}setQualityFeedbackLoop(e){this.qualityFeedbackLoop=e}getCoverageAnalyzer(){return this.coverageAnalyzer||(this.coverageAnalyzer=vo(this.kernel.memory)),this.coverageAnalyzer}getSecurityScanner(){return this.securityScanner||(this.securityScanner=bo(this.kernel.memory)),this.securityScanner}getTestGenerator(){return this.testGenerator||(this.testGenerator=Co(this.kernel.memory)),this.testGenerator}getKnowledgeGraph(){return this.knowledgeGraph||(this.knowledgeGraph=To(this.kernel.memory)),this.knowledgeGraph}getQualityAnalyzer(){return this.qualityAnalyzer||(this.qualityAnalyzer=So(this.kernel.memory)),this.qualityAnalyzer}registerHandlers(){jn(this),Hn(this),Qn(this),Wn(this),Kn(this),Xn(this),Yn(this)}async getAgentBooster(){return this.agentBooster||(this.agentBooster=await St({enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7})),this.agentBooster}async getTaskRouterInstance(){if(!this.taskRouter)try{this.taskRouter=await $t()}catch{return null}return this.taskRouter}async executeWithAgentBooster(e,t,n){let r=Eo(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=${qi(t)}, success=${n}, duration=${r}ms`),this.qualityFeedbackLoop){let s=e.targetDomains||[],a=n?1:0,o=r<100?1:r<500?.8:r<2e3?.6:r<5e3?.4:r<1e4?.2:.1,u=.25*a+.325+.1*o;await this.qualityFeedbackLoop.recordRoutingOutcome({taskId:e.id,taskDescription:e.type,recommendedAgent:String(t),usedAgent:String(t),followedRecommendation:!0,success:n,qualityScore:u,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,o=qi(i);a&&e.payload&&(e.payload.__compiledContext=a),console.debug(`[TaskExecutor] Executing task ${e.id}: type=${e.type}, tier=${i}, model=${o}, useAgentBooster=${s}${a?", hasContext=true":""}`);let u=this.evaluateCoherenceGate(e,n);u&&console.debug(`[TaskExecutor] Coherence gate: task=${e.id}, decision=${u.decision}, combined=${u.combinedScore.toFixed(3)}, advisory=${u.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=>{ae.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 l=this.taskHandlers.get(e.type);if(!l){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=>{ae.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),p}let d=await Promise.race([l(e),this.timeout(e.timeout||this._config.timeout)]);if(!d.success){let p="error"in d?d.error.message:"Unknown error";return await this.publishTaskFailed(e.id,p,n),this.recordOutcome(e,i,!1,Date.now()-t).catch(g=>{ae.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),{taskId:e.id,success:!1,error:p,duration:Date.now()-t,domain:n}}await this.publishTaskCompleted(e.id,d.value,n),this.recordOutcome(e,i,!0,Date.now()-t).catch(p=>{ae.warn("recordOutcome failed",{error:p instanceof Error?p.message:String(p),taskId:e.id})});let m;if(this._config.saveResults)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(h=>h.path)}catch(p){console.error(`[TaskExecutor] Failed to save results: ${p}`)}return{taskId:e.id,success:!0,data:{...d.value,_routing:{tier:i,model:o,usedAgentBooster:!1}},duration:Date.now()-t,domain:n,savedFiles:m}}catch(l){let d=T(l);return await this.publishTaskFailed(e.id,d,n),this.recordOutcome(e,i,!1,Date.now()-t).catch(m=>{ae.warn("recordOutcome failed",{error:m instanceof Error?m.message:String(m),taskId:e.id})}),{taskId:e.id,success:!1,error:d,duration:Date.now()-t,domain:n}}}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=wi({advisory:!0}));let n=e.payload,r=typeof n?.confidence=="number"?n.confidence:.7,i=n?.riskLevel??"medium";return Ri(e.type,t,r,i,n??{},this.coherenceActionGate)}catch(n){return ae.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}=(vt(),kr(Qs));if(s()){let{createReasoningQEC:a}=(Ni(),kr(Li));this._reasoningQEC=a()}}catch(s){ae.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||ae.warn("ReasoningQEC validation found issues (advisory)",{taskId:e.id,domain:t,confidence:i.confidence,issues:i.issues.length})}catch(n){ae.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:N(),type:"TaskCompleted",timestamp:new Date,source:n,payload:{taskId:e,result:t}})}async publishTaskFailed(e,t,n){await this.eventBus.publish({id:N(),type:"TaskFailed",timestamp:new Date,source:n,payload:{taskId:e,error:t}})}};function Gi(c,e){return new Zn(c,c.eventBus,e)}async function $i(){}import{randomUUID as De}from"crypto";k();var er={effectiveness:.25,coverage:.2,mutationKill:.15,stability:.15,maintainability:.15,performance:.1},tr={"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}},me={qualityWeights:er,promotionCriteria:tr,autoPromote:!0,autoDemote:!0,minCoverageImprovementToLearn:5,maxOutcomesInMemory:1e4,persistOutcomes:!0,batchSize:100};ie();k();H();var nr=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}},rr=class c{store;reasoningBank=null;config;db=null;persistCount=0;static RETENTION_CLEANUP_INTERVAL=100;patternMetrics=new Map;constructor(e={}){this.config={...me,...e},this.store=new nr(this.config.maxOutcomesInMemory)}connectReasoningBank(e){this.reasoningBank=e}async initialize(){try{this.db=j(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb()}catch(e){console.warn("[TestOutcomeTracker] DB initialization failed, using memory-only:",T(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
388
388
  SELECT * FROM test_outcomes ORDER BY created_at DESC LIMIT ?
389
389
  `).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?A(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(`
390
390
  INSERT OR REPLACE INTO test_outcomes (
@@ -395,11 +395,11 @@ ${p}`,estimatedTokens:Math.ceil(p.length/3.5),relevance:.6})}}}finally{i.close()
395
395
  maintainability_score, complexity, lines_of_code,
396
396
  assertion_count, file_path, source_file_path, metadata_json
397
397
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
398
- `).run(e.id,e.testId,e.testName,e.generatedBy,e.patternId||null,e.framework,e.language,e.domain,e.passed?1:0,e.errorMessage||null,e.coverage.lines,e.coverage.branches,e.coverage.functions,e.mutationScore??null,e.executionTimeMs,e.flaky?1:0,e.flakinessScore??null,e.maintainabilityScore,e.complexity??null,e.linesOfCode??null,e.assertionCount??null,e.filePath||null,e.sourceFilePath||null,e.metadata?JSON.stringify(e.metadata):null),this.persistCount++,this.persistCount%c.RETENTION_CLEANUP_INTERVAL===0&&this.enforceRetention(t)}catch(t){console.warn("[TestOutcomeTracker] Failed to persist outcome:",E(t))}}enforceRetention(e){try{let t=this.config.maxOutcomesInMemory*2;e.prepare(`
398
+ `).run(e.id,e.testId,e.testName,e.generatedBy,e.patternId||null,e.framework,e.language,e.domain,e.passed?1:0,e.errorMessage||null,e.coverage.lines,e.coverage.branches,e.coverage.functions,e.mutationScore??null,e.executionTimeMs,e.flaky?1:0,e.flakinessScore??null,e.maintainabilityScore,e.complexity??null,e.linesOfCode??null,e.assertionCount??null,e.filePath||null,e.sourceFilePath||null,e.metadata?JSON.stringify(e.metadata):null),this.persistCount++,this.persistCount%c.RETENTION_CLEANUP_INTERVAL===0&&this.enforceRetention(t)}catch(t){console.warn("[TestOutcomeTracker] Failed to persist outcome:",T(t))}}enforceRetention(e){try{let t=this.config.maxOutcomesInMemory*2;e.prepare(`
399
399
  DELETE FROM test_outcomes WHERE id NOT IN (
400
400
  SELECT id FROM test_outcomes ORDER BY created_at DESC LIMIT ?
401
401
  )
402
- `).run(t)}catch(t){console.warn("[TestOutcomeTracker] Retention cleanup failed:",E(t))}}async track(e){this.store.add(e),this.persistOutcome(e),e.patternId&&(this.updatePatternMetrics(e),this.reasoningBank&&await this.updateReasoningBankPattern(e),(this.config.autoPromote||this.config.autoDemote)&&await this.checkPatternTierChange(e.patternId))}async trackBatch(e){for(let t of e)await this.track(t)}updatePatternMetrics(e){let t=e.patternId,n=this.patternMetrics.get(t)||{successCount:0,failureCount:0,totalQuality:0,outcomes:0};e.passed&&!e.flaky?n.successCount++:n.failureCount++,n.totalQuality+=e.maintainabilityScore,n.outcomes++,this.patternMetrics.set(t,n)}async updateReasoningBankPattern(e){if(!this.reasoningBank||!e.patternId)return;let t=this.calculateOutcomeQuality(e),n=e.passed&&!e.flaky;await this.reasoningBank.recordPatternOutcome(e.patternId,n,t)}calculateOutcomeQuality(e){let t=this.config.qualityWeights,n=e.passed&&!e.flaky?1:0,r=(e.coverage.lines+e.coverage.branches+e.coverage.functions)/3/100,i=e.mutationScore??.5,s=e.flaky?.2:1-(e.flakinessScore??0),a=e.maintainabilityScore,u=Math.max(0,1-e.executionTimeMs/1e4);return t.effectiveness*n+t.coverage*r+t.mutationKill*i+t.stability*s+t.maintainability*a+t.performance*u}async checkPatternTierChange(e){if(!this.reasoningBank)return;let t=this.patternMetrics.get(e);if(!t)return;let n=t.successCount/(t.successCount+t.failureCount),r=t.totalQuality/t.outcomes;if(this.config.autoPromote&&await this.reasoningBank.checkPatternPromotion(e,t.successCount,n,r)&&await this.reasoningBank.promotePattern(e),this.config.autoDemote){let i=this.store.getByPattern(e).slice(-10);i.length>=5&&i.filter(a=>a.passed&&!a.flaky).length/i.length<.3&&await this.reasoningBank.demotePattern(e)}}getStats(){let e=this.store.getAll();if(e.length===0)return this.emptyStats();let t=e.filter(p=>p.passed).length,n={lines:e.reduce((p,g)=>p+g.coverage.lines,0)/e.length,branches:e.reduce((p,g)=>p+g.coverage.branches,0)/e.length,functions:e.reduce((p,g)=>p+g.coverage.functions,0)/e.length},r=e.filter(p=>p.mutationScore!==void 0),i=r.length>0?r.reduce((p,g)=>p+g.mutationScore,0)/r.length:0,s=e.reduce((p,g)=>p+g.executionTimeMs,0)/e.length,a=e.filter(p=>p.flaky).length,o=e.reduce((p,g)=>p+g.maintainabilityScore,0)/e.length,u=new Map,l=this.groupBy(e,p=>p.generatedBy);for(let[p,g]of l)u.set(p,{total:g.length,passed:g.filter(h=>h.passed).length,avgCoverage:g.reduce((h,f)=>h+f.coverage.lines,0)/g.length,avgMaintainability:g.reduce((h,f)=>h+f.maintainabilityScore,0)/g.length});let d=new Map,m=this.groupBy(e,p=>p.domain);for(let[p,g]of m)d.set(p,{total:g.length,passed:g.filter(h=>h.passed).length,avgCoverage:g.reduce((h,f)=>h+f.coverage.lines,0)/g.length});return{totalTests:e.length,passedTests:t,passRate:t/e.length,avgCoverage:n,avgMutationScore:i,avgExecutionTimeMs:s,flakyTests:a,avgMaintainability:o,byAgent:u,byDomain:d}}getPatternMetrics(e){let t=this.patternMetrics.get(e);if(!t)return null;let n=t.successCount+t.failureCount;return{successCount:t.successCount,failureCount:t.failureCount,successRate:n>0?t.successCount/n:0,avgQuality:t.outcomes>0?t.totalQuality/t.outcomes:0}}getAllPatternMetrics(){let e=new Map;for(let[t,n]of this.patternMetrics)e.set(t,this.getPatternMetrics(t));return e}getAgentOutcomes(e){return this.store.getByAgent(e)}getRecentOutcomes(e){return this.store.getRecent(e)}exportOutcomes(){return this.store.getAll()}importOutcomes(e){for(let t of e)this.store.add(t),t.patternId&&this.updatePatternMetrics(t)}clear(){this.store.clear(),this.patternMetrics.clear()}getTrackerStats(){return{totalOutcomes:this.store.size,patternsTracked:this.patternMetrics.size,hasReasoningBank:this.reasoningBank!==null}}emptyStats(){return{totalTests:0,passedTests:0,passRate:0,avgCoverage:{lines:0,branches:0,functions:0},avgMutationScore:0,avgExecutionTimeMs:0,flakyTests:0,avgMaintainability:0,byAgent:new Map,byDomain:new Map}}groupBy(e,t){let n=new Map;for(let r of e){let i=t(r),s=n.get(i)||[];s.push(r),n.set(i,s)}return n}};function Fi(c){return new tr(c)}import{randomUUID as vo}from"crypto";ie();M();H();var nr=class{sessions=[];maxSessions;constructor(e){this.maxSessions=e}add(e){this.sessions.push(e),this.sessions.length>this.maxSessions&&(this.sessions=this.sessions.slice(-this.maxSessions))}getAll(){return[...this.sessions]}getByTechnique(e){return this.sessions.filter(t=>t.technique===e)}getByAgent(e){return this.sessions.filter(t=>t.agentId===e)}getSuccessful(e){return this.sessions.filter(t=>this.calculateImprovement(t)>=e)}calculateImprovement(e){return(e.afterCoverage.lines-e.beforeCoverage.lines+(e.afterCoverage.branches-e.beforeCoverage.branches)+(e.afterCoverage.functions-e.beforeCoverage.functions))/3}clear(){this.sessions=[]}get size(){return this.sessions.length}},rr=class c{sessionStore;strategies=new Map;reasoningBank=null;config;db=null;persistCount=0;static RETENTION_CLEANUP_INTERVAL=50;constructor(e={}){this.config={...me,...e},this.sessionStore=new nr(this.config.maxOutcomesInMemory)}connectReasoningBank(e){this.reasoningBank=e}async initialize(){try{this.db=j(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb()}catch(e){console.warn("[CoverageLearner] DB init failed, using memory-only:",E(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
402
+ `).run(t)}catch(t){console.warn("[TestOutcomeTracker] Retention cleanup failed:",T(t))}}async track(e){this.store.add(e),this.persistOutcome(e),e.patternId&&(this.updatePatternMetrics(e),this.reasoningBank&&await this.updateReasoningBankPattern(e),(this.config.autoPromote||this.config.autoDemote)&&await this.checkPatternTierChange(e.patternId))}async trackBatch(e){for(let t of e)await this.track(t)}updatePatternMetrics(e){let t=e.patternId,n=this.patternMetrics.get(t)||{successCount:0,failureCount:0,totalQuality:0,outcomes:0};e.passed&&!e.flaky?n.successCount++:n.failureCount++,n.totalQuality+=e.maintainabilityScore,n.outcomes++,this.patternMetrics.set(t,n)}async updateReasoningBankPattern(e){if(!this.reasoningBank||!e.patternId)return;let t=this.calculateOutcomeQuality(e),n=e.passed&&!e.flaky;await this.reasoningBank.recordPatternOutcome(e.patternId,n,t)}calculateOutcomeQuality(e){let t=this.config.qualityWeights,n=e.passed&&!e.flaky?1:0,r=(e.coverage.lines+e.coverage.branches+e.coverage.functions)/3/100,i=e.mutationScore??.5,s=e.flaky?.2:1-(e.flakinessScore??0),a=e.maintainabilityScore,u=Math.max(0,1-e.executionTimeMs/1e4);return t.effectiveness*n+t.coverage*r+t.mutationKill*i+t.stability*s+t.maintainability*a+t.performance*u}async checkPatternTierChange(e){if(!this.reasoningBank)return;let t=this.patternMetrics.get(e);if(!t)return;let n=t.successCount/(t.successCount+t.failureCount),r=t.totalQuality/t.outcomes;if(this.config.autoPromote&&await this.reasoningBank.checkPatternPromotion(e,t.successCount,n,r)&&await this.reasoningBank.promotePattern(e),this.config.autoDemote){let i=this.store.getByPattern(e).slice(-10);i.length>=5&&i.filter(a=>a.passed&&!a.flaky).length/i.length<.3&&await this.reasoningBank.demotePattern(e)}}getStats(){let e=this.store.getAll();if(e.length===0)return this.emptyStats();let t=e.filter(p=>p.passed).length,n={lines:e.reduce((p,g)=>p+g.coverage.lines,0)/e.length,branches:e.reduce((p,g)=>p+g.coverage.branches,0)/e.length,functions:e.reduce((p,g)=>p+g.coverage.functions,0)/e.length},r=e.filter(p=>p.mutationScore!==void 0),i=r.length>0?r.reduce((p,g)=>p+g.mutationScore,0)/r.length:0,s=e.reduce((p,g)=>p+g.executionTimeMs,0)/e.length,a=e.filter(p=>p.flaky).length,o=e.reduce((p,g)=>p+g.maintainabilityScore,0)/e.length,u=new Map,l=this.groupBy(e,p=>p.generatedBy);for(let[p,g]of l)u.set(p,{total:g.length,passed:g.filter(h=>h.passed).length,avgCoverage:g.reduce((h,f)=>h+f.coverage.lines,0)/g.length,avgMaintainability:g.reduce((h,f)=>h+f.maintainabilityScore,0)/g.length});let d=new Map,m=this.groupBy(e,p=>p.domain);for(let[p,g]of m)d.set(p,{total:g.length,passed:g.filter(h=>h.passed).length,avgCoverage:g.reduce((h,f)=>h+f.coverage.lines,0)/g.length});return{totalTests:e.length,passedTests:t,passRate:t/e.length,avgCoverage:n,avgMutationScore:i,avgExecutionTimeMs:s,flakyTests:a,avgMaintainability:o,byAgent:u,byDomain:d}}getPatternMetrics(e){let t=this.patternMetrics.get(e);if(!t)return null;let n=t.successCount+t.failureCount;return{successCount:t.successCount,failureCount:t.failureCount,successRate:n>0?t.successCount/n:0,avgQuality:t.outcomes>0?t.totalQuality/t.outcomes:0}}getAllPatternMetrics(){let e=new Map;for(let[t,n]of this.patternMetrics)e.set(t,this.getPatternMetrics(t));return e}getAgentOutcomes(e){return this.store.getByAgent(e)}getRecentOutcomes(e){return this.store.getRecent(e)}exportOutcomes(){return this.store.getAll()}importOutcomes(e){for(let t of e)this.store.add(t),t.patternId&&this.updatePatternMetrics(t)}clear(){this.store.clear(),this.patternMetrics.clear()}getTrackerStats(){return{totalOutcomes:this.store.size,patternsTracked:this.patternMetrics.size,hasReasoningBank:this.reasoningBank!==null}}emptyStats(){return{totalTests:0,passedTests:0,passRate:0,avgCoverage:{lines:0,branches:0,functions:0},avgMutationScore:0,avgExecutionTimeMs:0,flakyTests:0,avgMaintainability:0,byAgent:new Map,byDomain:new Map}}groupBy(e,t){let n=new Map;for(let r of e){let i=t(r),s=n.get(i)||[];s.push(r),n.set(i,s)}return n}};function zi(c){return new rr(c)}import{randomUUID as wo}from"crypto";ie();k();H();var ir=class{sessions=[];maxSessions;constructor(e){this.maxSessions=e}add(e){this.sessions.push(e),this.sessions.length>this.maxSessions&&(this.sessions=this.sessions.slice(-this.maxSessions))}getAll(){return[...this.sessions]}getByTechnique(e){return this.sessions.filter(t=>t.technique===e)}getByAgent(e){return this.sessions.filter(t=>t.agentId===e)}getSuccessful(e){return this.sessions.filter(t=>this.calculateImprovement(t)>=e)}calculateImprovement(e){return(e.afterCoverage.lines-e.beforeCoverage.lines+(e.afterCoverage.branches-e.beforeCoverage.branches)+(e.afterCoverage.functions-e.beforeCoverage.functions))/3}clear(){this.sessions=[]}get size(){return this.sessions.length}},sr=class c{sessionStore;strategies=new Map;reasoningBank=null;config;db=null;persistCount=0;static RETENTION_CLEANUP_INTERVAL=50;constructor(e={}){this.config={...me,...e},this.sessionStore=new ir(this.config.maxOutcomesInMemory)}connectReasoningBank(e){this.reasoningBank=e}async initialize(){try{this.db=j(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb()}catch(e){console.warn("[CoverageLearner] DB init failed, using memory-only:",T(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
403
403
  SELECT * FROM coverage_sessions ORDER BY created_at DESC LIMIT ?
404
404
  `).all(this.config.maxOutcomesInMemory);for(let n of t.reverse()){let r={id:n.id,targetPath:n.target_path,agentId:n.agent_id,technique:n.technique,beforeCoverage:{lines:n.before_lines,branches:n.before_branches,functions:n.before_functions},afterCoverage:{lines:n.after_lines,branches:n.after_branches,functions:n.after_functions},testsGenerated:n.tests_generated,testsPassed:n.tests_passed,gapsTargeted:n.gaps_json?A(n.gaps_json):[],durationMs:n.duration_ms,startedAt:new Date(n.started_at),completedAt:new Date(n.completed_at),context:n.context_json?A(n.context_json):void 0};this.sessionStore.add(r);let i=(r.afterCoverage.lines-r.beforeCoverage.lines)*.4+(r.afterCoverage.branches-r.beforeCoverage.branches)*.35+(r.afterCoverage.functions-r.beforeCoverage.functions)*.25;if(i>=this.config.minCoverageImprovementToLearn){let s=this.extractFilePattern(r.targetPath),a=`${r.technique}:${s}`,o=this.strategies.get(a);o?this.strategies.set(a,{...o,avgImprovement:(o.avgImprovement*o.successCount+i)/(o.successCount+1),successCount:o.successCount+1,confidence:Math.min(1,o.confidence+.05),lastUsedAt:new Date(n.completed_at)}):this.strategies.set(a,{id:`strategy-${n.id}`,description:`Coverage strategy: ${r.technique} for ${s} files`,technique:r.technique,filePatterns:[s],avgImprovement:i,successCount:1,confidence:.5,createdAt:new Date(n.started_at),lastUsedAt:new Date(n.completed_at)})}}t.length>0&&console.log(`[CoverageLearner] Loaded ${t.length} sessions from DB`)}persistSession(e){if(this.db)try{let t=this.db.getDatabase();t.prepare(`
405
405
  INSERT OR REPLACE INTO coverage_sessions (
@@ -409,21 +409,21 @@ ${p}`,estimatedTokens:Math.ceil(p.length/3.5),relevance:.6})}}}finally{i.close()
409
409
  tests_generated, tests_passed, gaps_json,
410
410
  duration_ms, started_at, completed_at, context_json
411
411
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
412
- `).run(e.id,e.targetPath,e.agentId,e.technique,e.beforeCoverage.lines,e.beforeCoverage.branches,e.beforeCoverage.functions,e.afterCoverage.lines,e.afterCoverage.branches,e.afterCoverage.functions,e.testsGenerated,e.testsPassed,JSON.stringify(e.gapsTargeted),e.durationMs,e.startedAt instanceof Date?e.startedAt.toISOString():e.startedAt,e.completedAt instanceof Date?e.completedAt.toISOString():e.completedAt,e.context?JSON.stringify(e.context):null),this.persistCount++,this.persistCount%c.RETENTION_CLEANUP_INTERVAL===0&&this.enforceRetention(t)}catch(t){console.warn("[CoverageLearner] Failed to persist session:",E(t))}}enforceRetention(e){try{let t=this.config.maxOutcomesInMemory*2;e.prepare(`
412
+ `).run(e.id,e.targetPath,e.agentId,e.technique,e.beforeCoverage.lines,e.beforeCoverage.branches,e.beforeCoverage.functions,e.afterCoverage.lines,e.afterCoverage.branches,e.afterCoverage.functions,e.testsGenerated,e.testsPassed,JSON.stringify(e.gapsTargeted),e.durationMs,e.startedAt instanceof Date?e.startedAt.toISOString():e.startedAt,e.completedAt instanceof Date?e.completedAt.toISOString():e.completedAt,e.context?JSON.stringify(e.context):null),this.persistCount++,this.persistCount%c.RETENTION_CLEANUP_INTERVAL===0&&this.enforceRetention(t)}catch(t){console.warn("[CoverageLearner] Failed to persist session:",T(t))}}enforceRetention(e){try{let t=this.config.maxOutcomesInMemory*2;e.prepare(`
413
413
  DELETE FROM coverage_sessions WHERE id NOT IN (
414
414
  SELECT id FROM coverage_sessions ORDER BY created_at DESC LIMIT ?
415
415
  )
416
- `).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()}-${vo().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,o=Math.max(.5,1-a/30),u=i.avgImprovement*i.confidence*o;u>r&&(r=u,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,o)=>a+o,0)/t.length,i=new Map,s=new Map;for(let a of e){let o=s.get(a.technique)||[];o.push(a),s.set(a.technique,o)}for(let[a,o]of s){let u=o.map(l=>this.calculateOverallImprovement(l));i.set(a,{count:o.length,avgImprovement:u.reduce((l,d)=>l+d,0)/u.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 Li(c){return new rr(c)}var ir=class{weights;historicalScores=[];maxHistory;constructor(e={},t=100){this.weights={...Jn,...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 Ni(c,e){return new ir(c,e)}var sr=class{criteria;promotionHistory=[];demotionHistory=[];reasoningBank=null;config;constructor(e={}){this.config={...me,...e},this.criteria={...Zn}}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 qi(c){return new sr(c)}var ar=class{outcomeTracker;coverageLearner;qualityCalculator;promotionManager;routingFeedback;reasoningBank=null;config;constructor(e={}){this.config={...me,...e},this.outcomeTracker=Fi(this.config),this.coverageLearner=Li(this.config),this.qualityCalculator=Ni(this.config.qualityWeights),this.promotionManager=qi(this.config),this.routingFeedback=_r(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 Gi(c){let e=new ar(c);return await e.initialize(),$i=e,e}var $i=null;function zi(){return $i}function Ie(){return`test-${De()}`}function ji(c){return`${c}-${De()}`}function jt(c){return{enabled:!0,agentId:ji(c),message:"Experience captured asynchronously via learning pipeline"}}async function bo(c,e,t,n,r){let i=ji(c);try{let{kernel:s}=We();if(!s)return{enabled:!1,agentId:i,message:"Learning engine not available - kernel not initialized"};let a=await To();if(!a)return{enabled:!1,agentId:i,message:"Learning engine not available"};let o=a.getExperienceCaptureService();if(!o)return{enabled:!1,agentId:i,message:"Experience capture service not available"};let u=Co(e),l=o.startCapture(`${e}: ${JSON.stringify(t).slice(0,200)}`,{agent:c,domain:u||void 0,metadata:{tool:e,durationMs:r}});o.recordStep(l,{action:`execute-${e}`,result:typeof n=="object"?JSON.stringify(n).slice(0,500):String(n).slice(0,500),quality:.7});let d=await o.completeCapture(l,{success:!0,quality:.7});if(d.success){let m=d.value;return{enabled:!0,agentId:i,message:`Experience captured: ${m.id} (domain: ${u||"general"}, quality: ${m.quality})`,experienceId:m.id,domain:u||"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 Co(c){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"}[c]||null}async function To(){return Ki()}async function So(c,e,t,n){let r=zi();if(!r&&or&&(r=await or),!!r){if(c==="test-generation"&&e){let i=e.tests||e.generatedTests||[];for(let s of i.slice(0,20)){let a={id:String(s.id||De()),testId:String(s.id||s.name||De()),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(c==="coverage-analysis"&&e){let i={id:De(),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-${De().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};await r.recordCoverageSession(i)}}}function Ui(c){let e=c.split(`
417
- `).length,t=(c.match(/if|switch|for|while|catch/g)||[]).length;return{score:e+t*2,level:t>5?"high":t>2?"medium":"low"}}function Hi(c,e){let t=[];return c.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(c.score*.5)} minutes`,confidence:.85}}function Vi(c,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(c))!==null;){let u=a[1]||a[2]||a[3]||a[4];u&&s.push(u)}for(let u=0;u<Math.min(s.length,n);u++){let l=s[u]||"exampleFunction";r.push({id:Ie(),name:`test_${l}_${u}`,type:e,parameters:[],assertions:[`${l}() === null`],expectedResult:null,estimatedDuration:e==="integration"?2e3:1e3,aiGenerated:!0})}(e==="integration"||n>s.length)&&r.push({id:Ie(),name:`integration_ComponentA_${r.length}`,type:"integration",parameters:[],assertions:["ComponentA integration test passes"],expectedResult:null,estimatedDuration:2e3,aiGenerated:!0});let o=["high-complexity","deep-nesting","null-handling","empty-input"];for(let u=r.length;u<n&&u-r.length<o.length;u++)r.push({id:Ie(),name:`edge_case_${o[u-r.length]}_${u}`,type:"unit",parameters:[],assertions:[`${o[u-r.length]} edge case handled`],expectedResult:null,estimatedDuration:1500,aiGenerated:!0});return r}function Qi(c,e){let t=[],n=c.split(`
418
- `);return c.includes("eval(")&&t.push({type:"dangerous-eval",line:n.findIndex(r=>r.includes("eval("))+1,severity:"critical",suggestion:"Replace eval() with safer alternatives"}),c.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"}),c.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 Qe=null,or=null,oe=null,Eo=Number(process.env.AQE_ROUTE_TIMEOUT_MS)||5e3;function wo(c,e,t){return new Promise(n=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(t))},e);typeof i.unref=="function"&&i.unref(),c.then(s=>{r||(r=!0,clearTimeout(i),n(s))},()=>{r||(r=!0,clearTimeout(i),n(t))})})}function Ro(){if(!Qe){let{kernel:c}=We();if(!c)throw new Error("Kernel not initialized");Qe=Oi(c);let e=Qe;or=Gi().then(t=>(e.setQualityFeedbackLoop(t),t)).catch(t=>(console.warn("[HandlerFactory] Failed to initialize QualityFeedbackLoop:",t),null))}return Qe}function Wi(){if(Qe=null,oe){let c=oe;oe=null,c.dispose().catch(()=>{})}}async function Ki(){if(oe)return oe;try{let{kernel:c}=We();if(!c)return null;let{createAQELearningEngine:e}=await import("./aqe-learning-engine-FRCSXNMG.js"),t=c.memory,n=e(t,{projectRoot:process.cwd(),enableClaudeFlow:!1});return await n.initialize(),oe=n,oe}catch(c){return console.debug("[HandlerFactory] Learning engine init failed:",E(c)),null}}async function Po(c,e){try{let t=await Ki();if(!t)return[];let n=e,r=await t.searchPatterns(c,{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 xo(c,e,t){try{let n=await Po(c,e);return n.length>0&&console.debug(`[HandlerFactory] Found ${n.length} relevant patterns for ${e}`),await(await Gt()).routeTask({task:c,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 Bi(c,e,t,n){if(!(!c||c.length===0)&&oe)try{for(let r of c)r.patternId&&await oe.recordOutcome({patternId:r.patternId,success:e,metrics:{executionTimeMs:n},feedback:`Domain handler ${t} execution ${e?"succeeded":"failed"}`})}catch{}}function W(c){let{domain:e,taskType:t,priority:n="p1",defaultTimeout:r=18e4,buildTaskDescription:i,mapToPayload:s,mapToResult:a,calculateTimeout:o,includeCodeContext:u}=c;return async l=>{if(!Oe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:d}=We(),m=null;try{let p=i(l),g=u?.(l);m=await wo(xo(p,e,g),Eo,null);let h=s(l,m),f=o?.(l)??r,v=await d.submitTask({type:t,priority:n,targetDomains:[e],payload:h,timeout:f});if(!v.success)return{success:!1,error:v.error.message};let y=Ro(),C=d.getTaskStatus(v.value);if(!C)return{success:!1,error:"Task not found after submission"};let b=await y.execute(C.task);if(!b.success)return{success:!1,error:b.error||"Task execution failed"};let w=b.data,S=a(v.value,w,b.duration,b.savedFiles,l);Bi(m?.patternHints,!0,e,b.duration),bo(`qe-${e}`,t,l,w,b.duration).catch(()=>{});try{await So(e,w,b.duration,l)}catch{}return{success:!0,data:S}}catch(p){let g=E(p);return Bi(m?.patternHints,!1,e,0),{success:!1,error:`Failed to ${t.replace(/-/g," ")}: ${g}`}}}}var Ut=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,o)=>a+o.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,o)=>a+o,0)/e.length;if(t===0)return 1;let n=e.reduce((a,o)=>a+Math.pow(o-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()}},he=new Ut;Bs();function Ao(c){return typeof c=="object"&&c!==null&&!Array.isArray(c)}function ko(c){return Array.isArray(c)&&c.every(e=>typeof e=="string")}function Mo(c){return typeof c=="number"&&Number.isFinite(c)&&c>=0&&c<=1}function Xi(c){let e=[];return Ao(c)?(c.contract!=="risk-decision@1"&&e.push('contract must be "risk-decision@1"'),["approve","block","escalate"].includes(c.decision)||e.push("decision must be approve|block|escalate"),ko(c.riskFactors)||e.push("riskFactors must be string[]"),Mo(c.confidence)||e.push("confidence must be a number in [0,1]"),(typeof c.rationale!="string"||c.rationale.length===0)&&e.push("rationale must be a non-empty string"),{valid:e.length===0,errors:e}):{valid:!1,errors:["not an object"]}}function Yi(c){let{passed:e,qualityScore:t,recommendations:n=[]}=c,r=e===!0?"approve":e===!1?"block":"escalate";return{contract:"risk-decision@1",decision:r,riskFactors:n.slice(0,10),confidence:r==="escalate"?.5:.9,rationale:r==="escalate"?"Quality gate outcome indeterminate \u2014 manual review required":`Quality gate ${e?"passed":"failed"}${typeof t=="number"?` with score ${t}`:""}`}}var Ji=Object.keys(Ct);function Do(c){if(!c)return"typescript";let e=c.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]:Ji.includes(e)?e:null}var Zi={domain:"test-generation",taskType:"generate-tests",priority:"p1",defaultTimeout:12e4,buildTaskDescription:c=>`Generate ${c.testType||"unit"} tests for ${c.language||"typescript"} code`,includeCodeContext:c=>c.sourceCode,mapToPayload:(c,e)=>{let t=Do(c.language);if(t===null)throw new Error(`Unsupported language '${c.language}'. Supported languages: ${Ji.join(", ")}. Open a feature request for additional language support.`);let n;if(c.framework){n=c.framework;let r=Ir[n];if(r&&r!==t){let i=s=>s==="javascript"||s==="typescript";if(!(i(r)&&i(t)))throw new Error(`Framework '${n}' targets ${r}, but language was '${t}'. Either pick a matching framework or omit \`framework\` to use the default (${Ct[t]}).`)}}else n=Ct[t];return{sourceCode:c.sourceCode,filePath:c.filePath,language:t,framework:n,testType:c.testType||"unit",coverageGoal:c.coverageGoal||80,aiEnhancement:c.aiEnhancement!==!1,detectAntiPatterns:c.detectAntiPatterns||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(c,e,t,n,r)=>{let i=r?.sourceCode||"",s=r?.language||"typescript",a=r?.testType||"unit",o=e.testsGenerated||6,u=Ui(i),l=r?.aiEnhancement!==!1?Hi(u,a):{recommendations:[],estimatedTime:"0 minutes",confidence:0},d=r?.detectAntiPatterns?Qi(i,s):[],m=jt("test-generator"),p=e.tests,h=Array.isArray(p)&&p.length>0&&p[0].testCode?p.map((f,v)=>({id:Ie(),name:f.name||`test_${v}`,type:f.type||a,parameters:[],assertions:f.testCode?Io(f.testCode):[`test assertion ${v}`],expectedResult:null,estimatedDuration:f.type==="integration"?2e3:1e3,aiGenerated:!0,testCode:f.testCode,sourceFile:f.sourceFile,testFile:f.testFile||f.file})):Vi(i,a,s,o);return{tests:h,antiPatterns:d,suggestions:d.map(f=>`Fix: ${f.type} - ${f.suggestion}`),aiInsights:l,coverage:{predicted:e.coverageEstimate||r?.coverageGoal||80,confidence:.9,achievable:!0},properties:h.filter(f=>f.type==="property").map(f=>({name:f.name,invariant:"output_matches_expectation"})),language:s,complexity:u,learning:m,taskId:c,status:"completed",testsGenerated:h.length,coverageEstimate:e.coverageEstimate||r?.coverageGoal||80,patternsUsed:e.patternsUsed||["assertion-patterns","mock-generation","edge-case-detection"],duration:t,savedFiles:n}}},es={domain:"test-execution",taskType:"execute-tests",priority:"p1",defaultTimeout:3e5,buildTaskDescription:c=>`Execute ${c.testFiles?.length||0} test files with ${c.parallel!==!1?"parallel":"sequential"} execution`,mapToPayload:(c,e)=>({testFiles:c.testFiles||[],testSuites:c.testSuites||[],parallel:c.parallel!==!1,parallelism:c.parallelism||4,retryCount:c.retryCount||3,timeout:c.timeout||6e4,collectCoverage:c.collectCoverage||!1,reportFormat:c.reportFormat||"json",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:c=>c.timeout||3e5,mapToResult:(c,e,t,n,r)=>{let i=e.total||0,s=e.passed||0,a=e.failed||0,o=e.coverage,u=r?.parallelism||4,l=he.getRetryStats(),d=he.getWorkersUsed(),m={workersUsed:d>0?d:Math.min(u,i||1),efficiency:he.getWorkerEfficiency(),loadBalance:he.getLoadBalanceScore(),avgExecutionTime:t/Math.max(i,1)},p={totalRetries:l.totalRetries,successfulRetries:l.successfulRetries,maxRetriesReached:l.maxRetriesReached},g=jt("test-executor");return{workerStats:m,retryStats:p,results:(()=>{let h=he.getTestDurations(i);return Array.from({length:i},(f,v)=>({id:Ie(),name:`test_case_${v}`,status:v<s?"passed":"failed",duration:h[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:c,status:"completed",total:i,passed:s,failed:a,duration:t,coverage:o,savedFiles:n}}},ts={domain:"coverage-analysis",taskType:"analyze-coverage",priority:"p1",defaultTimeout:18e4,buildTaskDescription:c=>`Analyze coverage for ${c.target||"project"} with gap detection`,mapToPayload:(c,e)=>({target:c.target||".",includeRisk:c.includeRisk||!1,detectGaps:c.detectGaps!==!1,mlPowered:c.mlPowered||!1,prioritization:c.prioritization||"complexity",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(c,e,t,n)=>{let r=e.summary,i=r?.line??e.lineCoverage??0,s=r?.branch??e.branchCoverage??0,a=r?.function??e.functionCoverage??0,o=r?.statement??e.statementCoverage??i,u=r?.files??e.totalFiles??0,l=e.gaps||[],d=jt("coverage-analyzer"),m=l.map((h,f)=>{let v=h;return v?.file?{id:`gap-${Date.now()}-${f}`,file:v.file,line:v.lines?.[0]||0,uncoveredLines:v.lines||[],type:v.type||"uncovered-line",severity:v.severity||"medium",reason:v.reason||"Missing test case",priority:v.priority||"medium",suggestion:v.suggestedTest||"Add test coverage",suggestedTest:v.suggestedTest||"Add test coverage",riskScore:v.riskScore||.5,confidence:v.confidence||.7}:null}).filter(h=>h!==null),p=e.coverageByFile;return{coverageByFile:p?p.map(h=>({file:h.file,lineCoverage:h.lineCoverage||0,branchCoverage:h.branchCoverage||0,functionCoverage:h.functionCoverage||0})):[],gapAnalysis:{totalGaps:m.length,highPriority:m.filter(h=>h.priority==="high").length,gaps:m},trends:{lineCoverageTrend:u>0?"stable":"no-data",branchCoverageTrend:u>0?"stable":"no-data",weeklyChange:0},aiInsights:u>0?{recommendations:e.recommendations||["Run tests with coverage enabled to get accurate metrics"],riskAssessment:i<70?"high":i<85?"medium":"low",confidence:.88}:{recommendations:["No coverage data found. Run tests with coverage first (e.g., npm test -- --coverage, or pytest --cov)"],riskAssessment:"unknown",confidence:0},learning:d,taskId:c,status:"completed",lineCoverage:i,branchCoverage:s,functionCoverage:a,statementCoverage:o,totalFiles:u,gaps:m,duration:t,savedFiles:n}}},ns={domain:"quality-assessment",taskType:"assess-quality",priority:"p0",defaultTimeout:18e4,buildTaskDescription:c=>`Assess quality with ${c.runGate?"quality gate":"metrics analysis"}`,mapToPayload:(c,e)=>({runGate:c.runGate||!1,threshold:c.threshold||80,metrics:c.metrics||["coverage","complexity","maintainability"],routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(c,e,t,n)=>{let r=Yi({passed:typeof e.passed=="boolean"?e.passed:void 0,qualityScore:e.qualityScore,recommendations:e.recommendations||[]});return{taskId:c,status:"completed",qualityScore:e.qualityScore||0,passed:e.passed||!1,metrics:e.metrics||{},recommendations:e.recommendations||[],duration:t,savedFiles:n,...Xi(r).valid?{riskDecision:r}:{}}}},rs={domain:"security-compliance",taskType:"scan-security",priority:"p0",defaultTimeout:6e5,buildTaskDescription:c=>{let e=[];return c.sast!==!1&&e.push("SAST"),c.dast&&e.push("DAST"),`Security scan (${e.join(", ")}) for ${c.target||"project"}`},mapToPayload:(c,e)=>({sast:c.sast!==!1,dast:c.dast||!1,compliance:c.compliance||[],target:c.target||".",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(c,e,t,n)=>({taskId:c,status:"completed",vulnerabilities:e.vulnerabilities||0,critical:e.critical||0,high:e.high||0,medium:e.medium||0,low:e.low||0,topVulnerabilities:e.topVulnerabilities||[],recommendations:e.recommendations||[],duration:t,savedFiles:n})},is={domain:"contract-testing",taskType:"validate-contracts",priority:"p1",defaultTimeout:18e4,buildTaskDescription:c=>`Validate API contract at ${c.contractPath}`,mapToPayload:(c,e)=>({contractPath:c.contractPath,providerUrl:c.providerUrl,consumerName:c.consumerName,checkBreakingChanges:c.checkBreakingChanges!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(c,e,t,n)=>({taskId:c,status:"completed",valid:e.valid||!1,breakingChanges:e.breakingChanges||[],warnings:e.warnings||[],duration:t,savedFiles:n})},ss={domain:"visual-accessibility",taskType:"test-accessibility",priority:"p1",defaultTimeout:18e4,buildTaskDescription:c=>`Test accessibility for ${c.url} against ${c.standard||"WCAG 2.1 AA"} standard`,mapToPayload:(c,e)=>({url:c.url,standard:c.standard||"wcag21-aa",includeScreenReader:c.includeScreenReader||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(c,e,t,n)=>({taskId:c,status:"completed",passed:e.passed||!1,score:e.score||0,violations:e.violations||[],warnings:e.warnings||[],duration:t,savedFiles:n})},as={domain:"chaos-resilience",taskType:"run-chaos",priority:"p2",defaultTimeout:9e4,buildTaskDescription:c=>`Run chaos test with ${c.faultType||"latency"} fault injection on ${c.target}`,mapToPayload:(c,e)=>({faultType:c.faultType||"latency",target:c.target,duration:c.duration||3e4,intensity:c.intensity||50,dryRun:c.dryRun!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:c=>(c.duration||3e4)+6e4,mapToResult:(c,e,t,n)=>({taskId:c,status:"completed",faultType:e.faultType||"latency",resilience:e.resilience||{recovered:!1,recoveryTime:0,dataLoss:!1},duration:t,savedFiles:n})},os={domain:"defect-intelligence",taskType:"predict-defects",priority:"p1",defaultTimeout:18e4,buildTaskDescription:c=>`Predict defects in ${c.target||"codebase"} with ${c.lookback||30} day lookback`,mapToPayload:(c,e)=>({target:c.target||".",lookback:c.lookback||30,minConfidence:c.minConfidence||.7,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(c,e,t,n)=>({taskId:c,status:"completed",predictedDefects:e.predictedDefects||[],riskScore:e.riskScore||0,recommendations:e.recommendations||[],duration:t,savedFiles:n})},cs={domain:"requirements-validation",taskType:"validate-requirements",priority:"p1",defaultTimeout:18e4,buildTaskDescription:c=>`Validate requirements${c.generateBDD?" and generate BDD scenarios":""}`,mapToPayload:(c,e)=>({requirementsPath:c.requirementsPath,testPath:c.testPath,generateBDD:c.generateBDD||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(c,e,t,n)=>({taskId:c,status:"completed",requirementsAnalyzed:e.requirementsAnalyzed||0,testable:e.testable||0,coverage:e.coverage||0,bddScenarios:e.bddScenarios||[],duration:t,savedFiles:n})},ls={domain:"code-intelligence",taskType:"index-code",priority:"p2",defaultTimeout:3e5,buildTaskDescription:c=>`Index code in ${c.target||"codebase"}${c.incremental?" incrementally":""}`,mapToPayload:(c,e)=>({target:c.target||".",incremental:c.incremental||!1,gitSince:c.gitSince,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(c,e,t,n)=>({taskId:c,status:"completed",filesIndexed:e.filesIndexed||0,symbolsExtracted:e.symbolsExtracted||0,relationsFound:e.relationsFound||0,duration:t,savedFiles:n})};function Io(c){let e=[],t=c.split(`
419
- `);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 us(){Wi()}var hg=W(Zi),fg=W(es),yg=W(ts),vg=W(ns),bg=W(rs),Cg=W(is),Tg=W(ss),Sg=W(as),Eg=W(os),wg=W(cs),Rg=W(ls);M();var Ht=class extends x{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:Oo,streaming:!0,timeout:12e4};testGeneratorService=null;async getService(e){if(!this.testGeneratorService){let t=await L(),n=await B(e);this.testGeneratorService=Or({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:o=[],aiEnhancement:u=!0,detectAntiPatterns:l=!1}=e;try{if(this.emitStream(t,{status:"analyzing",message:`Analyzing ${n.length} source files`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(xn.isEnabled()){let v=`Generate ${r} tests for ${n.length} files using ${i}`,y=await xn.checkTaskEarlyExit(v,"test-generation");y.canExit&&y.reusedPattern&&(this.emitStream(t,{status:"pattern-reuse",message:`Reusing pattern: ${y.reusedPattern.name}`,tokensSaved:y.estimatedTokensSaved}),console.log(`[TestGenerateTool] Early exit: reusing pattern ${y.reusedPattern.name}, saving ~${y.estimatedTokensSaved} tokens`))}let d=await this.getService(t),m={sourceFiles:n,testType:r,framework:i,coverageTarget:a,patterns:o},p=await d.generateTests(m);if(!p.success)return{success:!1,error:p.error?.message||"Test generation failed"};let g=p.value,h=g.tests.map(v=>({id:v.id,name:v.name,sourceFile:v.sourceFile,testFile:v.testFile,testCode:v.testCode,type:v.type,assertions:v.assertions}));this.emitStream(t,{status:"generating",message:`Generated ${h.length} test files`,progress:50});let f=l?_o(n):[];return this.emitStream(t,{status:"complete",message:"Test generation complete",progress:100}),{success:!0,data:{tests:h,coverageEstimate:g.coverageEstimate,patternsUsed:g.patternsUsed,suggestions:No(h,u),antiPatterns:f.length>0?f:void 0}}}catch(d){return{success:!1,error:`Test generation failed: ${E(d)}`}}}resetInstanceCache(){this.testGeneratorService=null}},Oo={type:"object",properties:{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 _o(c){let e=[],t=Ns("fs");for(let n of c)try{let r;try{r=t.readFileSync(n,"utf-8")}catch{continue}let i=r.split(`
420
- `),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,h)=>{if(g.trim().startsWith("//")||g.trim().startsWith("*")||g.includes("import")||g.includes("require"))return;let f=g.match(s);if(f)for(let v of f){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}:${h+1}`,severity:"medium",suggestion:`Consider extracting ${v} into a named constant to improve readability and maintainability`});break}}});let o=/(?:it|test)\s*\(\s*['"`]([^'"`]+)['"`]\s*,/g,u;for(;(u=o.exec(r))!==null;){let g=u.index,h=u[1],f=r.substring(g),v=Fo(f);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 S=r.substring(0,g).split(`
421
- `).length;e.push({name:"no-assertions",location:`${n}:${S}`,severity:"high",suggestion:`Test "${h}" has no assertions. Add expect() or assert() calls to verify behavior`})}}}let l=[{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 h=r.indexOf(g),f=Lo(r.substring(h));if(f){let v=f.match(/^\s*let\s+(\w+)\s*(?::\s*\w+)?\s*(?:=|;)/m);if(v){let y=v[1];if((f.match(new RegExp(`(?:it|test)\\s*\\([^)]+,[^]*?${y}\\s*=`,"g"))||[]).length>=2){let b=r.substring(0,h+f.indexOf(v[0])).split(`
416
+ `).run(t)}catch(t){console.warn("[CoverageLearner] Retention cleanup failed:",T(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()}-${wo().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,o=Math.max(.5,1-a/30),u=i.avgImprovement*i.confidence*o;u>r&&(r=u,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,o)=>a+o,0)/t.length,i=new Map,s=new Map;for(let a of e){let o=s.get(a.technique)||[];o.push(a),s.set(a.technique,o)}for(let[a,o]of s){let u=o.map(l=>this.calculateOverallImprovement(l));i.set(a,{count:o.length,avgImprovement:u.reduce((l,d)=>l+d,0)/u.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 Bi(c){return new sr(c)}var ar=class{weights;historicalScores=[];maxHistory;constructor(e={},t=100){this.weights={...er,...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 ji(c,e){return new ar(c,e)}var or=class{criteria;promotionHistory=[];demotionHistory=[];reasoningBank=null;config;constructor(e={}){this.config={...me,...e},this.criteria={...tr}}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 Ui(c){return new or(c)}var cr=class{outcomeTracker;coverageLearner;qualityCalculator;promotionManager;routingFeedback;reasoningBank=null;config;constructor(e={}){this.config={...me,...e},this.outcomeTracker=zi(this.config),this.coverageLearner=Bi(this.config),this.qualityCalculator=ji(this.config.qualityWeights),this.promotionManager=Ui(this.config),this.routingFeedback=qr(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 Hi(c){let e=new cr(c);return await e.initialize(),Vi=e,e}var Vi=null;function Qi(){return Vi}function Ie(){return`test-${De()}`}function Ki(c){return`${c}-${De()}`}function Ut(c){return{enabled:!0,agentId:Ki(c),message:"Experience captured asynchronously via learning pipeline"}}async function Ro(c,e,t,n,r){let i=Ki(c);try{let{kernel:s}=We();if(!s)return{enabled:!1,agentId:i,message:"Learning engine not available - kernel not initialized"};let a=await xo();if(!a)return{enabled:!1,agentId:i,message:"Learning engine not available"};let o=a.getExperienceCaptureService();if(!o)return{enabled:!1,agentId:i,message:"Experience capture service not available"};let u=Po(e),l=o.startCapture(`${e}: ${JSON.stringify(t).slice(0,200)}`,{agent:c,domain:u||void 0,metadata:{tool:e,durationMs:r}});o.recordStep(l,{action:`execute-${e}`,result:typeof n=="object"?JSON.stringify(n).slice(0,500):String(n).slice(0,500),quality:.7});let d=await o.completeCapture(l,{success:!0,quality:.7});if(d.success){let m=d.value;return{enabled:!0,agentId:i,message:`Experience captured: ${m.id} (domain: ${u||"general"}, quality: ${m.quality})`,experienceId:m.id,domain:u||"general"}}return{enabled:!0,agentId:i,message:"Experience capture completed (no pattern extracted)"}}catch(s){return{enabled:!1,agentId:i,message:`Learning capture failed: ${T(s)}`}}}function Po(c){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"}[c]||null}async function xo(){return ts()}async function Ao(c,e,t,n){let r=Qi();if(!r&&lr&&(r=await lr),!!r){if(c==="test-generation"&&e){let i=e.tests||e.generatedTests||[];for(let s of i.slice(0,20)){let a={id:String(s.id||De()),testId:String(s.id||s.name||De()),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(c==="coverage-analysis"&&e){let i={id:De(),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-${De().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};await r.recordCoverageSession(i)}}}function Xi(c){let e=c.split(`
417
+ `).length,t=(c.match(/if|switch|for|while|catch/g)||[]).length;return{score:e+t*2,level:t>5?"high":t>2?"medium":"low"}}function Yi(c,e){let t=[];return c.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(c.score*.5)} minutes`,confidence:.85}}function Ji(c,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(c))!==null;){let u=a[1]||a[2]||a[3]||a[4];u&&s.push(u)}for(let u=0;u<Math.min(s.length,n);u++){let l=s[u]||"exampleFunction";r.push({id:Ie(),name:`test_${l}_${u}`,type:e,parameters:[],assertions:[`${l}() === null`],expectedResult:null,estimatedDuration:e==="integration"?2e3:1e3,aiGenerated:!0})}(e==="integration"||n>s.length)&&r.push({id:Ie(),name:`integration_ComponentA_${r.length}`,type:"integration",parameters:[],assertions:["ComponentA integration test passes"],expectedResult:null,estimatedDuration:2e3,aiGenerated:!0});let o=["high-complexity","deep-nesting","null-handling","empty-input"];for(let u=r.length;u<n&&u-r.length<o.length;u++)r.push({id:Ie(),name:`edge_case_${o[u-r.length]}_${u}`,type:"unit",parameters:[],assertions:[`${o[u-r.length]} edge case handled`],expectedResult:null,estimatedDuration:1500,aiGenerated:!0});return r}function Zi(c,e){let t=[],n=c.split(`
418
+ `);return c.includes("eval(")&&t.push({type:"dangerous-eval",line:n.findIndex(r=>r.includes("eval("))+1,severity:"critical",suggestion:"Replace eval() with safer alternatives"}),c.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"}),c.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 Qe=null,lr=null,oe=null,ko=Number(process.env.AQE_ROUTE_TIMEOUT_MS)||5e3;function Mo(c,e,t){return new Promise(n=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(t))},e);typeof i.unref=="function"&&i.unref(),c.then(s=>{r||(r=!0,clearTimeout(i),n(s))},()=>{r||(r=!0,clearTimeout(i),n(t))})})}function Do(){if(!Qe){let{kernel:c}=We();if(!c)throw new Error("Kernel not initialized");Qe=Gi(c);let e=Qe;lr=Hi().then(t=>(e.setQualityFeedbackLoop(t),t)).catch(t=>(console.warn("[HandlerFactory] Failed to initialize QualityFeedbackLoop:",t),null))}return Qe}function es(){if(Qe=null,oe){let c=oe;oe=null,c.dispose().catch(()=>{})}}async function ts(){if(oe)return oe;try{let{kernel:c}=We();if(!c)return null;let{createAQELearningEngine:e}=await import("./aqe-learning-engine-CA4CT5Q7.js"),t=c.memory,n=e(t,{projectRoot:process.cwd(),enableClaudeFlow:!1});return await n.initialize(),oe=n,oe}catch(c){return console.debug("[HandlerFactory] Learning engine init failed:",T(c)),null}}async function Io(c,e){try{let t=await ts();if(!t)return[];let n=e,r=await t.searchPatterns(c,{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:",T(t)),[]}}async function Oo(c,e,t){try{let n=await Io(c,e);return n.length>0&&console.debug(`[HandlerFactory] Found ${n.length} relevant patterns for ${e}`),await(await $t()).routeTask({task:c,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 Wi(c,e,t,n){if(!(!c||c.length===0)&&oe)try{for(let r of c)r.patternId&&await oe.recordOutcome({patternId:r.patternId,success:e,metrics:{executionTimeMs:n},feedback:`Domain handler ${t} execution ${e?"succeeded":"failed"}`})}catch{}}function W(c){let{domain:e,taskType:t,priority:n="p1",defaultTimeout:r=18e4,buildTaskDescription:i,mapToPayload:s,mapToResult:a,calculateTimeout:o,includeCodeContext:u}=c;return async l=>{if(!Oe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:d}=We(),m=null;try{let p=i(l),g=u?.(l);m=await Mo(Oo(p,e,g),ko,null);let h=s(l,m),f=o?.(l)??r,v=await d.submitTask({type:t,priority:n,targetDomains:[e],payload:h,timeout:f});if(!v.success)return{success:!1,error:v.error.message};let y=Do(),C=d.getTaskStatus(v.value);if(!C)return{success:!1,error:"Task not found after submission"};let b=await y.execute(C.task);if(!b.success)return{success:!1,error:b.error||"Task execution failed"};let w=b.data,E=a(v.value,w,b.duration,b.savedFiles,l);Wi(m?.patternHints,!0,e,b.duration),Ro(`qe-${e}`,t,l,w,b.duration).catch(()=>{});try{await Ao(e,w,b.duration,l)}catch{}return{success:!0,data:E}}catch(p){let g=T(p);return Wi(m?.patternHints,!1,e,0),{success:!1,error:`Failed to ${t.replace(/-/g," ")}: ${g}`}}}}var Ht=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,o)=>a+o.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,o)=>a+o,0)/e.length;if(t===0)return 1;let n=e.reduce((a,o)=>a+Math.pow(o-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()}},he=new Ht;Ws();function _o(c){return typeof c=="object"&&c!==null&&!Array.isArray(c)}function Fo(c){return Array.isArray(c)&&c.every(e=>typeof e=="string")}function Lo(c){return typeof c=="number"&&Number.isFinite(c)&&c>=0&&c<=1}function ns(c){let e=[];return _o(c)?(c.contract!=="risk-decision@1"&&e.push('contract must be "risk-decision@1"'),["approve","block","escalate"].includes(c.decision)||e.push("decision must be approve|block|escalate"),Fo(c.riskFactors)||e.push("riskFactors must be string[]"),Lo(c.confidence)||e.push("confidence must be a number in [0,1]"),(typeof c.rationale!="string"||c.rationale.length===0)&&e.push("rationale must be a non-empty string"),{valid:e.length===0,errors:e}):{valid:!1,errors:["not an object"]}}function rs(c){let{passed:e,qualityScore:t,recommendations:n=[]}=c,r=e===!0?"approve":e===!1?"block":"escalate";return{contract:"risk-decision@1",decision:r,riskFactors:n.slice(0,10),confidence:r==="escalate"?.5:.9,rationale:r==="escalate"?"Quality gate outcome indeterminate \u2014 manual review required":`Quality gate ${e?"passed":"failed"}${typeof t=="number"?` with score ${t}`:""}`}}var is=Object.keys(Ct);function No(c){if(!c)return"typescript";let e=c.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]:is.includes(e)?e:null}var ss={domain:"test-generation",taskType:"generate-tests",priority:"p1",defaultTimeout:12e4,buildTaskDescription:c=>`Generate ${c.testType||"unit"} tests for ${c.language||"typescript"} code`,includeCodeContext:c=>c.sourceCode,mapToPayload:(c,e)=>{let t=No(c.language);if(t===null)throw new Error(`Unsupported language '${c.language}'. Supported languages: ${is.join(", ")}. Open a feature request for additional language support.`);let n;if(c.framework){n=c.framework;let r=Lr[n];if(r&&r!==t){let i=s=>s==="javascript"||s==="typescript";if(!(i(r)&&i(t)))throw new Error(`Framework '${n}' targets ${r}, but language was '${t}'. Either pick a matching framework or omit \`framework\` to use the default (${Ct[t]}).`)}}else n=Ct[t];return{sourceCode:c.sourceCode,filePath:c.filePath,language:t,framework:n,testType:c.testType||"unit",coverageGoal:c.coverageGoal||80,aiEnhancement:c.aiEnhancement!==!1,detectAntiPatterns:c.detectAntiPatterns||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(c,e,t,n,r)=>{let i=r?.sourceCode||"",s=r?.language||"typescript",a=r?.testType||"unit",o=e.testsGenerated||6,u=Xi(i),l=r?.aiEnhancement!==!1?Yi(u,a):{recommendations:[],estimatedTime:"0 minutes",confidence:0},d=r?.detectAntiPatterns?Zi(i,s):[],m=Ut("test-generator"),p=e.tests,h=Array.isArray(p)&&p.length>0&&p[0].testCode?p.map((f,v)=>({id:Ie(),name:f.name||`test_${v}`,type:f.type||a,parameters:[],assertions:f.testCode?qo(f.testCode):[`test assertion ${v}`],expectedResult:null,estimatedDuration:f.type==="integration"?2e3:1e3,aiGenerated:!0,testCode:f.testCode,sourceFile:f.sourceFile,testFile:f.testFile||f.file})):Ji(i,a,s,o);return{tests:h,antiPatterns:d,suggestions:d.map(f=>`Fix: ${f.type} - ${f.suggestion}`),aiInsights:l,coverage:{predicted:e.coverageEstimate||r?.coverageGoal||80,confidence:.9,achievable:!0},properties:h.filter(f=>f.type==="property").map(f=>({name:f.name,invariant:"output_matches_expectation"})),language:s,complexity:u,learning:m,taskId:c,status:"completed",testsGenerated:h.length,coverageEstimate:e.coverageEstimate||r?.coverageGoal||80,patternsUsed:e.patternsUsed||["assertion-patterns","mock-generation","edge-case-detection"],duration:t,savedFiles:n}}},as={domain:"test-execution",taskType:"execute-tests",priority:"p1",defaultTimeout:3e5,buildTaskDescription:c=>`Execute ${c.testFiles?.length||0} test files with ${c.parallel!==!1?"parallel":"sequential"} execution`,mapToPayload:(c,e)=>({testFiles:c.testFiles||[],testSuites:c.testSuites||[],parallel:c.parallel!==!1,parallelism:c.parallelism||4,retryCount:c.retryCount||3,timeout:c.timeout||6e4,collectCoverage:c.collectCoverage||!1,reportFormat:c.reportFormat||"json",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:c=>c.timeout||3e5,mapToResult:(c,e,t,n,r)=>{let i=e.total||0,s=e.passed||0,a=e.failed||0,o=e.coverage,u=r?.parallelism||4,l=he.getRetryStats(),d=he.getWorkersUsed(),m={workersUsed:d>0?d:Math.min(u,i||1),efficiency:he.getWorkerEfficiency(),loadBalance:he.getLoadBalanceScore(),avgExecutionTime:t/Math.max(i,1)},p={totalRetries:l.totalRetries,successfulRetries:l.successfulRetries,maxRetriesReached:l.maxRetriesReached},g=Ut("test-executor");return{workerStats:m,retryStats:p,results:(()=>{let h=he.getTestDurations(i);return Array.from({length:i},(f,v)=>({id:Ie(),name:`test_case_${v}`,status:v<s?"passed":"failed",duration:h[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:c,status:"completed",total:i,passed:s,failed:a,duration:t,coverage:o,savedFiles:n}}},os={domain:"coverage-analysis",taskType:"analyze-coverage",priority:"p1",defaultTimeout:18e4,buildTaskDescription:c=>`Analyze coverage for ${c.target||"project"} with gap detection`,mapToPayload:(c,e)=>({target:c.target||".",includeRisk:c.includeRisk||!1,detectGaps:c.detectGaps!==!1,mlPowered:c.mlPowered||!1,prioritization:c.prioritization||"complexity",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(c,e,t,n)=>{let r=e.summary,i=r?.line??e.lineCoverage??0,s=r?.branch??e.branchCoverage??0,a=r?.function??e.functionCoverage??0,o=r?.statement??e.statementCoverage??i,u=r?.files??e.totalFiles??0,l=e.gaps||[],d=Ut("coverage-analyzer"),m=l.map((h,f)=>{let v=h;return v?.file?{id:`gap-${Date.now()}-${f}`,file:v.file,line:v.lines?.[0]||0,uncoveredLines:v.lines||[],type:v.type||"uncovered-line",severity:v.severity||"medium",reason:v.reason||"Missing test case",priority:v.priority||"medium",suggestion:v.suggestedTest||"Add test coverage",suggestedTest:v.suggestedTest||"Add test coverage",riskScore:v.riskScore||.5,confidence:v.confidence||.7}:null}).filter(h=>h!==null),p=e.coverageByFile;return{coverageByFile:p?p.map(h=>({file:h.file,lineCoverage:h.lineCoverage||0,branchCoverage:h.branchCoverage||0,functionCoverage:h.functionCoverage||0})):[],gapAnalysis:{totalGaps:m.length,highPriority:m.filter(h=>h.priority==="high").length,gaps:m},trends:{lineCoverageTrend:u>0?"stable":"no-data",branchCoverageTrend:u>0?"stable":"no-data",weeklyChange:0},aiInsights:u>0?{recommendations:e.recommendations||["Run tests with coverage enabled to get accurate metrics"],riskAssessment:i<70?"high":i<85?"medium":"low",confidence:.88}:{recommendations:["No coverage data found. Run tests with coverage first (e.g., npm test -- --coverage, or pytest --cov)"],riskAssessment:"unknown",confidence:0},learning:d,taskId:c,status:"completed",lineCoverage:i,branchCoverage:s,functionCoverage:a,statementCoverage:o,totalFiles:u,gaps:m,duration:t,savedFiles:n}}},cs={domain:"quality-assessment",taskType:"assess-quality",priority:"p0",defaultTimeout:18e4,buildTaskDescription:c=>`Assess quality with ${c.runGate?"quality gate":"metrics analysis"}`,mapToPayload:(c,e)=>({runGate:c.runGate||!1,threshold:c.threshold||80,metrics:c.metrics||["coverage","complexity","maintainability"],routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(c,e,t,n)=>{let r=rs({passed:typeof e.passed=="boolean"?e.passed:void 0,qualityScore:e.qualityScore,recommendations:e.recommendations||[]});return{taskId:c,status:"completed",qualityScore:e.qualityScore||0,passed:e.passed||!1,metrics:e.metrics||{},recommendations:e.recommendations||[],duration:t,savedFiles:n,...ns(r).valid?{riskDecision:r}:{}}}},ls={domain:"security-compliance",taskType:"scan-security",priority:"p0",defaultTimeout:6e5,buildTaskDescription:c=>{let e=[];return c.sast!==!1&&e.push("SAST"),c.dast&&e.push("DAST"),`Security scan (${e.join(", ")}) for ${c.target||"project"}`},mapToPayload:(c,e)=>({sast:c.sast!==!1,dast:c.dast||!1,compliance:c.compliance||[],target:c.target||".",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(c,e,t,n)=>({taskId:c,status:"completed",vulnerabilities:e.vulnerabilities||0,critical:e.critical||0,high:e.high||0,medium:e.medium||0,low:e.low||0,topVulnerabilities:e.topVulnerabilities||[],recommendations:e.recommendations||[],duration:t,savedFiles:n})},us={domain:"contract-testing",taskType:"validate-contracts",priority:"p1",defaultTimeout:18e4,buildTaskDescription:c=>`Validate API contract at ${c.contractPath}`,mapToPayload:(c,e)=>({contractPath:c.contractPath,providerUrl:c.providerUrl,consumerName:c.consumerName,checkBreakingChanges:c.checkBreakingChanges!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(c,e,t,n)=>({taskId:c,status:"completed",valid:e.valid||!1,breakingChanges:e.breakingChanges||[],warnings:e.warnings||[],duration:t,savedFiles:n})},ds={domain:"visual-accessibility",taskType:"test-accessibility",priority:"p1",defaultTimeout:18e4,buildTaskDescription:c=>`Test accessibility for ${c.url} against ${c.standard||"WCAG 2.1 AA"} standard`,mapToPayload:(c,e)=>({url:c.url,standard:c.standard||"wcag21-aa",includeScreenReader:c.includeScreenReader||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(c,e,t,n)=>({taskId:c,status:"completed",passed:e.passed||!1,score:e.score||0,violations:e.violations||[],warnings:e.warnings||[],duration:t,savedFiles:n})},ms={domain:"chaos-resilience",taskType:"run-chaos",priority:"p2",defaultTimeout:9e4,buildTaskDescription:c=>`Run chaos test with ${c.faultType||"latency"} fault injection on ${c.target}`,mapToPayload:(c,e)=>({faultType:c.faultType||"latency",target:c.target,duration:c.duration||3e4,intensity:c.intensity||50,dryRun:c.dryRun!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:c=>(c.duration||3e4)+6e4,mapToResult:(c,e,t,n)=>({taskId:c,status:"completed",faultType:e.faultType||"latency",resilience:e.resilience||{recovered:!1,recoveryTime:0,dataLoss:!1},duration:t,savedFiles:n})},ps={domain:"defect-intelligence",taskType:"predict-defects",priority:"p1",defaultTimeout:18e4,buildTaskDescription:c=>`Predict defects in ${c.target||"codebase"} with ${c.lookback||30} day lookback`,mapToPayload:(c,e)=>({target:c.target||".",lookback:c.lookback||30,minConfidence:c.minConfidence||.7,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(c,e,t,n)=>({taskId:c,status:"completed",predictedDefects:e.predictedDefects||[],riskScore:e.riskScore||0,recommendations:e.recommendations||[],duration:t,savedFiles:n})},gs={domain:"requirements-validation",taskType:"validate-requirements",priority:"p1",defaultTimeout:18e4,buildTaskDescription:c=>`Validate requirements${c.generateBDD?" and generate BDD scenarios":""}`,mapToPayload:(c,e)=>({requirementsPath:c.requirementsPath,testPath:c.testPath,generateBDD:c.generateBDD||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(c,e,t,n)=>({taskId:c,status:"completed",requirementsAnalyzed:e.requirementsAnalyzed||0,testable:e.testable||0,coverage:e.coverage||0,bddScenarios:e.bddScenarios||[],duration:t,savedFiles:n})},hs={domain:"code-intelligence",taskType:"index-code",priority:"p2",defaultTimeout:3e5,buildTaskDescription:c=>`Index code in ${c.target||"codebase"}${c.incremental?" incrementally":""}`,mapToPayload:(c,e)=>({target:c.target||".",incremental:c.incremental||!1,gitSince:c.gitSince,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(c,e,t,n)=>({taskId:c,status:"completed",filesIndexed:e.filesIndexed||0,symbolsExtracted:e.symbolsExtracted||0,relationsFound:e.relationsFound||0,duration:t,savedFiles:n})};function qo(c){let e=[],t=c.split(`
419
+ `);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 fs(){es()}var Sg=W(ss),Eg=W(as),wg=W(os),Rg=W(cs),Pg=W(ls),xg=W(us),Ag=W(ds),kg=W(ms),Mg=W(ps),Dg=W(gs),Ig=W(hs);k();var Vt=class extends P{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:Go,streaming:!0,timeout:12e4};testGeneratorService=null;async getService(e){if(!this.testGeneratorService){let t=await F(),n=await B(e);this.testGeneratorService=Nr({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:o=[],aiEnhancement:u=!0,detectAntiPatterns:l=!1}=e;try{if(this.emitStream(t,{status:"analyzing",message:`Analyzing ${n.length} source files`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(kn.isEnabled()){let v=`Generate ${r} tests for ${n.length} files using ${i}`,y=await kn.checkTaskEarlyExit(v,"test-generation");y.canExit&&y.reusedPattern&&(this.emitStream(t,{status:"pattern-reuse",message:`Reusing pattern: ${y.reusedPattern.name}`,tokensSaved:y.estimatedTokensSaved}),console.log(`[TestGenerateTool] Early exit: reusing pattern ${y.reusedPattern.name}, saving ~${y.estimatedTokensSaved} tokens`))}let d=await this.getService(t),m={sourceFiles:n,testType:r,framework:i,coverageTarget:a,patterns:o},p=await d.generateTests(m);if(!p.success)return{success:!1,error:p.error?.message||"Test generation failed"};let g=p.value,h=g.tests.map(v=>({id:v.id,name:v.name,sourceFile:v.sourceFile,testFile:v.testFile,testCode:v.testCode,type:v.type,assertions:v.assertions}));this.emitStream(t,{status:"generating",message:`Generated ${h.length} test files`,progress:50});let f=l?$o(n):[];return this.emitStream(t,{status:"complete",message:"Test generation complete",progress:100}),{success:!0,data:{tests:h,coverageEstimate:g.coverageEstimate,patternsUsed:g.patternsUsed,suggestions:jo(h,u),antiPatterns:f.length>0?f:void 0}}}catch(d){return{success:!1,error:`Test generation failed: ${T(d)}`}}}resetInstanceCache(){this.testGeneratorService=null}},Go={type:"object",properties:{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 $o(c){let e=[],t=js("fs");for(let n of c)try{let r;try{r=t.readFileSync(n,"utf-8")}catch{continue}let i=r.split(`
420
+ `),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,h)=>{if(g.trim().startsWith("//")||g.trim().startsWith("*")||g.includes("import")||g.includes("require"))return;let f=g.match(s);if(f)for(let v of f){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}:${h+1}`,severity:"medium",suggestion:`Consider extracting ${v} into a named constant to improve readability and maintainability`});break}}});let o=/(?:it|test)\s*\(\s*['"`]([^'"`]+)['"`]\s*,/g,u;for(;(u=o.exec(r))!==null;){let g=u.index,h=u[1],f=r.substring(g),v=zo(f);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 E=r.substring(0,g).split(`
421
+ `).length;e.push({name:"no-assertions",location:`${n}:${E}`,severity:"high",suggestion:`Test "${h}" has no assertions. Add expect() or assert() calls to verify behavior`})}}}let l=[{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 h=r.indexOf(g),f=Bo(r.substring(h));if(f){let v=f.match(/^\s*let\s+(\w+)\s*(?::\s*\w+)?\s*(?:=|;)/m);if(v){let y=v[1];if((f.match(new RegExp(`(?:it|test)\\s*\\([^)]+,[^]*?${y}\\s*=`,"g"))||[]).length>=2){let b=r.substring(0,h+f.indexOf(v[0])).split(`
422
422
  `).length;e.push({name:"test-interdependence",location:`${n}:${b}`,severity:"high",suggestion:`Shared mutable variable '${y}' is modified in multiple tests, causing test interdependence. Use beforeEach to reset state or isolate test data`})}}}}if(/\.test\.|\.spec\./.test(n)){let g=r.match(/import\s+.*from\s+['"].*(?:\.test|\.spec)['"]/g);g&&g.length>0&&e.push({name:"test-importing-tests",location:n,severity:"medium",suggestion:"Test file imports from another test file. Extract shared test utilities to a separate module"})}let m=/(?:it|test|describe)\s*\(\s*['"`]([^'"`]{100,})['"`]/g,p;for(;(p=m.exec(r))!==null;){let g=r.substring(0,p.index).split(`
423
423
  `).length;e.push({name:"long-test-description",location:`${n}:${g}`,severity:"low",suggestion:"Test description is too long. Consider breaking into smaller, focused tests or using a more concise description"})}if(/setTimeout|setInterval/.test(r)&&!/useFakeTimers|fakeTimers|clock/.test(r)){let h=r.match(/setTimeout|setInterval/);if(h){let f=r.substring(0,r.indexOf(h[0])).split(`
424
- `).length;e.push({name:"real-timers-in-tests",location:`${n}:${f}`,severity:"medium",suggestion:"Using real timers in tests can cause flakiness. Consider using fake timers (jest.useFakeTimers() or vi.useFakeTimers())"})}}}catch{continue}return e}function Fo(c){let e=0,t=-1,n=-1;for(let r=0;r<c.length;r++)if(c[r]==="{")t===-1&&(t=r),e++;else if(c[r]==="}"&&(e--,e===0&&t!==-1)){n=r;break}return t!==-1&&n!==-1?c.substring(t+1,n):null}function Lo(c){let e=0,t=-1,n=-1;for(let r=0;r<c.length;r++)if(c[r]==="{")t===-1&&(t=r),e++;else if(c[r]==="}"&&(e--,e===0&&t!==-1)){n=r;break}return t!==-1&&n!==-1?c.substring(t+1,n):null}function No(c,e){let t=[];return c.length===0&&t.push("No tests generated. Ensure source files are valid."),e&&(t.push("Consider adding property-based tests for edge case coverage"),t.push("Parameterized tests can reduce duplication")),t}M();je();var Vt=class extends x{config={name:"qe/tests/execute",description:"Execute test suites with parallel execution, retry logic, and coverage collection. Detects flaky tests.",domain:"test-execution",schema:qo,streaming:!0,timeout:3e5};async execute(e,t){let{testFiles:n=[],testSuites:r=[],pattern:i,parallel:s=!0,parallelism:a=4,retryCount:o=3,timeout:u=6e4,collectCoverage:l=!1,reportFormat:d="json",failFast:m=!1}=e,p=Date.now();try{let g=n.length>0?n:r.length>0?r:i?[i]:["**/*.test.ts"];if(this.emitStream(t,{status:"starting",message:`Executing ${g.length} test files`,parallel:s,parallelism:a}),this.isAborted(t))return{success:!1,error:"Test execution aborted"};let h=[],f=[];for(let b=0;b<g.length;b++){let w=g[b];this.emitStream(t,{status:"running",message:`Executing ${w}`,progress:Math.round(b/g.length*100)});let S=te()>.1,T={id:`test-${b}`,name:`Test suite for ${w.split("/").pop()}`,file:w,status:S?"passed":"failed",duration:te()*5e3,error:S?void 0:"Assertion failed",retries:S?0:Math.min(o,2)};if(h.push(T),!S&&te()>.7&&f.push({name:T.name,file:T.file,flakinessScore:ne(.5,1),failurePattern:"intermittent-timeout"}),m&&!S)break}let v={total:h.length,passed:h.filter(b=>b.status==="passed").length,failed:h.filter(b=>b.status==="failed").length,skipped:h.filter(b=>b.status==="skipped").length,pending:h.filter(b=>b.status==="pending").length,passRate:0};v.passRate=v.total>0?Math.round(v.passed/v.total*100):0;let y=l?{lines:ne(70,100),branches:ne(60,80),functions:ne(65,90),statements:ne(70,95)}:void 0,C=Date.now()-p;return this.emitStream(t,{status:"complete",message:`Test execution complete: ${v.passed}/${v.total} passed`,progress:100}),{success:v.failed===0,data:{summary:v,testResults:h,coverage:y,flakyTests:f.length>0?f:void 0,duration:C}}}catch(g){return{success:!1,error:`Test execution failed: ${E(g)}`}}}},qo={type:"object",properties:{testFiles:{type:"array",description:"Specific test files to execute",items:{type:"string",description:"Test file path"}},testSuites:{type:"array",description:"Test suite names to execute",items:{type:"string",description:"Suite name"}},pattern:{type:"string",description:"Glob pattern to match test files"},parallel:{type:"boolean",description:"Enable parallel test execution",default:!0},parallelism:{type:"number",description:"Number of parallel workers",minimum:1,maximum:16,default:4},retryCount:{type:"number",description:"Number of retries for failed tests",minimum:0,maximum:5,default:3},timeout:{type:"number",description:"Test timeout in milliseconds",minimum:1e3,default:6e4},collectCoverage:{type:"boolean",description:"Collect code coverage",default:!1},reportFormat:{type:"string",description:"Report output format",enum:["json","junit","html","markdown"],default:"json"},failFast:{type:"boolean",description:"Stop on first failure",default:!1},watch:{type:"boolean",description:"Watch mode for continuous testing",default:!1}}};H();import*as K from"fs/promises";import*as k from"path";async function cr(c,e){let t=await K.readFile(c,"utf-8");return ys(t,e||k.dirname(c))}function ys(c,e){let t=new Map,n=c.split(`
425
- `),r=null,i=new Map,s=[],a=[],o=0,u=0,l=0,d=0,m=0,p=0;for(let g of n){let h=g.trim();if(h.startsWith("SF:")){let f=h.slice(3);r={path:f,relativePath:k.relative(e,f)},i=new Map,s=[],a=[],o=0,u=0,l=0,d=0,m=0,p=0}else if(h.startsWith("DA:")){let[f,v]=h.slice(3).split(",").map(Number);!isNaN(f)&&!isNaN(v)&&(i.set(f,v),o++,v>0&&u++)}else if(h.startsWith("LF:")){let f=parseInt(h.slice(3),10);isNaN(f)||(o=f)}else if(h.startsWith("LH:")){let f=parseInt(h.slice(3),10);isNaN(f)||(u=f)}else if(h.startsWith("BRDA:")){let f=h.slice(5).split(",");if(f.length>=4){let v=parseInt(f[0],10),y=parseInt(f[1],10),C=parseInt(f[2],10),b=f[3]==="-"?0:parseInt(f[3],10);s.push({line:v,block:y,branch:C,taken:b>0,hits:b}),l++,b>0&&d++}}else if(h.startsWith("BRF:")){let f=parseInt(h.slice(4),10);isNaN(f)||(l=f)}else if(h.startsWith("BRH:")){let f=parseInt(h.slice(4),10);isNaN(f)||(d=f)}else if(h.startsWith("FN:")){let f=h.indexOf(",",3);if(f>0){let v=parseInt(h.slice(3,f),10),y=h.slice(f+1);a.find(b=>b.name===y)||a.push({name:y,line:v,hits:0})}}else if(h.startsWith("FNDA:")){let f=h.indexOf(",",5);if(f>0){let v=parseInt(h.slice(5,f),10),y=h.slice(f+1),C=a.find(b=>b.name===y);C?C.hits=v:a.push({name:y,line:0,hits:v}),m++,v>0&&p++}}else if(h.startsWith("FNF:")){let f=parseInt(h.slice(4),10);isNaN(f)||(m=f)}else if(h.startsWith("FNH:")){let f=parseInt(h.slice(4),10);isNaN(f)||(p=f)}else if(h==="end_of_record"&&r?.path){let f=Array.from(i.entries()).filter(([,b])=>b===0).map(([b])=>b).sort((b,w)=>b-w),v=s.filter(b=>!b.taken),y=a.filter(b=>b.hits===0).map(b=>b.name),C={path:r.path,relativePath:r.relativePath||r.path,lines:{total:o,covered:u,percentage:o>0?u/o*100:0,details:i,uncoveredLines:f},branches:{total:l,covered:d,percentage:l>0?d/l*100:0,uncoveredBranches:v},functions:{total:m,covered:p,percentage:m>0?p/m*100:0,details:a,uncoveredFunctions:y},statements:{total:o,covered:u,percentage:o>0?u/o*100:0},coveragePercentage:dr(u,o,d,l)};t.set(r.path,C),r=null}}return{timestamp:new Date,format:"lcov",files:t,summary:fe(t)}}async function lr(c,e){let t=await K.readFile(c,"utf-8"),n=A(t),r=e||k.dirname(c),i=new Map;for(let[s,a]of Object.entries(n)){if(typeof a!="object"||!a.statementMap)continue;let o=new Map,u=[],l=0,d=0;for(let[b,w]of Object.entries(a.s||{})){let S=a.statementMap[b];if(S?.start?.line){let T=S.start.line,P=o.get(T)||0;o.set(T,P+w)}l++,w>0&&d++}for(let[b,w]of o.entries())w===0&&u.push(b);let m=[],p=0,g=0;for(let[b,w]of Object.entries(a.branchMap||{})){let S=a.b?.[b]||[];for(let T=0;T<S.length;T++)m.push({line:w.loc?.start?.line||0,block:parseInt(b,10),branch:T,taken:S[T]>0,hits:S[T]}),p++,S[T]>0&&g++}let h=[],f=0,v=0;for(let[b,w]of Object.entries(a.fnMap||{})){let S=a.f?.[b]||0;h.push({name:w.name||`anonymous_${b}`,line:w.loc?.start?.line||w.decl?.start?.line||0,hits:S}),f++,S>0&&v++}let y=o.size,C=Array.from(o.values()).filter(b=>b>0).length;i.set(s,{path:s,relativePath:k.relative(r,s),lines:{total:y,covered:C,percentage:y>0?C/y*100:0,details:o,uncoveredLines:u.sort((b,w)=>b-w)},branches:{total:p,covered:g,percentage:p>0?g/p*100:0,uncoveredBranches:m.filter(b=>!b.taken)},functions:{total:f,covered:v,percentage:f>0?v/f*100:0,details:h,uncoveredFunctions:h.filter(b=>b.hits===0).map(b=>b.name)},statements:{total:l,covered:d,percentage:l>0?d/l*100:0},coveragePercentage:dr(C,y,g,p)})}return{timestamp:new Date,format:"json",files:i,summary:fe(i)}}async function ds(c,e){let t=await K.readFile(c,"utf-8");return Qt(t,e||k.dirname(c))}function Qt(c,e){let t=new Map,n=/<package\s+name="([^"]*)">([\s\S]*?)<\/package>/g,r;for(;(r=n.exec(c))!==null;){let i=r[1].replace(/\//g,k.sep),s=r[2],a=/<sourcefile\s+name="([^"]*)">([\s\S]*?)<\/sourcefile>/g,o;for(;(o=a.exec(s))!==null;){let u=o[1],l=o[2],d=k.join(e,i,u),m=Go(l),p=new Map,g=/<line\s+nr="(\d+)"\s+mi="(\d+)"\s+ci="(\d+)"/g,h;for(;(h=g.exec(l))!==null;){let v=parseInt(h[1],10),y=parseInt(h[3],10);p.set(v,y)}let f=Array.from(p.entries()).filter(([,v])=>v===0).map(([v])=>v).sort((v,y)=>v-y);t.set(d,{path:d,relativePath:k.join(i,u),lines:{total:m.LINE.total,covered:m.LINE.covered,percentage:m.LINE.total>0?m.LINE.covered/m.LINE.total*100:0,details:p,uncoveredLines:f},branches:{total:m.BRANCH.total,covered:m.BRANCH.covered,percentage:m.BRANCH.total>0?m.BRANCH.covered/m.BRANCH.total*100:0,uncoveredBranches:[]},functions:{total:m.METHOD.total,covered:m.METHOD.covered,percentage:m.METHOD.total>0?m.METHOD.covered/m.METHOD.total*100:0,details:[],uncoveredFunctions:[]},statements:{total:m.INSTRUCTION.total,covered:m.INSTRUCTION.covered,percentage:m.INSTRUCTION.total>0?m.INSTRUCTION.covered/m.INSTRUCTION.total*100:0},coveragePercentage:dr(m.LINE.covered,m.LINE.total,m.BRANCH.covered,m.BRANCH.total)})}}return{timestamp:new Date,format:"jacoco",language:"java",files:t,summary:fe(t)}}function Go(c){let e={LINE:{covered:0,total:0},BRANCH:{covered:0,total:0},METHOD:{covered:0,total:0},INSTRUCTION:{covered:0,total:0}},t=/<counter\s+type="(\w+)"\s+missed="(\d+)"\s+covered="(\d+)"\s*\/>/g,n;for(;(n=t.exec(c))!==null;){let r=n[1],i=parseInt(n[2],10),s=parseInt(n[3],10);e[r]&&(e[r].covered+=s,e[r].total+=i+s)}return e}async function ms(c,e){let t=await K.readFile(c,"utf-8");return vs(t,e||k.dirname(c))}function vs(c,e){let t=new Map,n=new Map,r=/<File\s+Index="(\d+)"\s+Name="([^"]*)"\s*\/>/g,i;for(;(i=r.exec(c))!==null;)n.set(i[1],i[2]);let s=/<Statement\s+FileIndex="(\d+)"\s+Line="(\d+)"\s+Column="\d+"\s+EndLine="\d+"\s+EndColumn="\d+"\s+Covered="(\w+)"\s*\/>/g,a=new Map,o;for(;(o=s.exec(c))!==null;){let u=o[1],l=parseInt(o[2],10),d=o[3]==="True",m=n.get(u)||`file-${u}`;a.has(m)||a.set(m,{lineDetails:new Map,total:0,covered:0});let p=a.get(m);p.lineDetails.set(l,d?1:0),p.total++,d&&p.covered++}if(a.size===0){let l=/CoveredStatements="(\d+)"\s+TotalStatements="(\d+)"/.exec(c);if(l){let d=parseInt(l[1],10),m=parseInt(l[2],10),p=k.join(e,"aggregate");t.set(p,{path:p,relativePath:"aggregate",lines:{total:m,covered:d,percentage:m>0?d/m*100:0,details:new Map,uncoveredLines:[]},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:m,covered:d,percentage:m>0?d/m*100:0},coveragePercentage:m>0?d/m*100:0})}}for(let[u,l]of a.entries()){let d=Array.from(l.lineDetails.entries()).filter(([,m])=>m===0).map(([m])=>m).sort((m,p)=>m-p);t.set(u,{path:u,relativePath:k.relative(e,u),lines:{total:l.lineDetails.size,covered:Array.from(l.lineDetails.values()).filter(m=>m>0).length,percentage:l.lineDetails.size>0?Array.from(l.lineDetails.values()).filter(m=>m>0).length/l.lineDetails.size*100:0,details:l.lineDetails,uncoveredLines:d},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:l.total,covered:l.covered,percentage:l.total>0?l.covered/l.total*100:0},coveragePercentage:l.total>0?l.covered/l.total*100:0})}return{timestamp:new Date,format:"dotcover",language:"csharp",files:t,summary:fe(t)}}async function ps(c,e){let t=await K.readFile(c,"utf-8"),n=e||k.dirname(c);if(t.includes("SF:")&&t.includes("end_of_record")){let r=ys(t,n);return r.format="tarpaulin",r.language="rust",r}return bs(t,n)}function bs(c,e){let t=new Map,n=A(c);for(let r of n?.files||[]){let i=r.path||"",s=new Map,a=0,o=0;for(let l of r.traces||[]){let d=l.line,m=l.stats?.Line??l.stats?.line??0;typeof d=="number"&&(s.set(d,m),a++,m>0&&o++)}let u=Array.from(s.entries()).filter(([,l])=>l===0).map(([l])=>l).sort((l,d)=>l-d);t.set(i,{path:i,relativePath:k.relative(e,i),lines:{total:a,covered:o,percentage:a>0?o/a*100:0,details:s,uncoveredLines:u},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:a,covered:o,percentage:a>0?o/a*100:0},coveragePercentage:a>0?o/a*100:0})}return{timestamp:new Date,format:"tarpaulin",language:"rust",files:t,summary:fe(t)}}async function gs(c,e){let t=await K.readFile(c,"utf-8");return Cs(t,e||k.dirname(c))}function Cs(c,e){let t=new Map,n=new Map,r=c.split(`
426
- `);for(let i of r){let s=i.trim();if(!s||s.startsWith("mode:"))continue;let a=s.match(/^(.+):(\d+)\.\d+,(\d+)\.\d+\s+(\d+)\s+(\d+)$/);if(!a)continue;let o=a[1],u=parseInt(a[2],10),l=parseInt(a[3],10),d=parseInt(a[4],10),m=parseInt(a[5],10);n.has(o)||n.set(o,{lineDetails:new Map,stmtTotal:0,stmtCovered:0});let p=n.get(o);for(let g=u;g<=l;g++){let h=p.lineDetails.get(g)||0;p.lineDetails.set(g,h+m)}p.stmtTotal+=d,m>0&&(p.stmtCovered+=d)}for(let[i,s]of n.entries()){let a=s.lineDetails.size,o=Array.from(s.lineDetails.values()).filter(l=>l>0).length,u=Array.from(s.lineDetails.entries()).filter(([,l])=>l===0).map(([l])=>l).sort((l,d)=>l-d);t.set(i,{path:i,relativePath:k.relative(e,i),lines:{total:a,covered:o,percentage:a>0?o/a*100:0,details:s.lineDetails,uncoveredLines:u},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:s.stmtTotal,covered:s.stmtCovered,percentage:s.stmtTotal>0?s.stmtCovered/s.stmtTotal*100:0},coveragePercentage:s.stmtTotal>0?s.stmtCovered/s.stmtTotal*100:0})}return{timestamp:new Date,format:"gocover",language:"go",files:t,summary:fe(t)}}async function hs(c,e){let t=await K.readFile(c,"utf-8"),n=Qt(t,e||k.dirname(c));return n.format="kover",n.language="kotlin",n}async function fs(c,e){let t=await K.readFile(c,"utf-8");return Ts(t,e||k.dirname(c))}function Ts(c,e){let t=new Map,r=A(c)?.targets||[];for(let i of r)for(let s of i.files||[]){let a=s.path||"",o=s.executableLines||0,u=s.coveredLines||0,l=s.lineCoverage||0,d=[],m=0,p=0;for(let g of s.functions||[]){let h=g.coveredLines>0?1:0;d.push({name:g.name||"unknown",line:g.lineNumber||0,hits:h}),m++,h>0&&p++}t.set(a,{path:a,relativePath:k.relative(e,a),lines:{total:o,covered:u,percentage:l*100,details:new Map,uncoveredLines:[]},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:m,covered:p,percentage:m>0?p/m*100:0,details:d,uncoveredFunctions:d.filter(g=>g.hits===0).map(g=>g.name)},statements:{total:o,covered:u,percentage:l*100},coveragePercentage:l*100})}return{timestamp:new Date,format:"xcresult",language:"swift",files:t,summary:fe(t)}}var $o={java:["jacoco","cobertura","lcov"],kotlin:["kover","jacoco"],csharp:["dotcover","cobertura"],rust:["tarpaulin","lcov"],go:["gocover"],swift:["xcresult"],dart:["lcov"],typescript:["lcov","json"],javascript:["lcov","json"],python:["lcov","cobertura","json"]};async function Ke(c,e,t,n){if(t)switch(t){case"lcov":return cr(c,e);case"json":return lr(c,e);case"jacoco":return ds(c,e);case"dotcover":return ms(c,e);case"tarpaulin":return ps(c,e);case"gocover":return gs(c,e);case"kover":return hs(c,e);case"xcresult":return fs(c,e);default:break}let r=k.extname(c).toLowerCase(),i=k.basename(c).toLowerCase();if(r===".json"||i.includes("coverage-final"))return lr(c,e);if(i==="lcov.info"||r===".info"||i.includes("lcov"))return cr(c,e);if(i.includes("jacoco")&&r===".xml")return ds(c,e);if(i.includes("dotcover")&&r===".xml")return ms(c,e);if(i.includes("tarpaulin"))return ps(c,e);if(i.includes("kover")&&r===".xml")return hs(c,e);if(i.includes("coverage")&&r===".out")return gs(c,e);if(i.includes("xcresult")||i.includes("xccov"))return fs(c,e);let s=await K.readFile(c,"utf-8"),a=s.trim();if(a.startsWith("{"))return a.includes('"files"')&&a.includes('"traces"')?bs(s,e||k.dirname(c)):a.includes('"targets"')&&a.includes('"lineCoverage"')?Ts(s,e||k.dirname(c)):lr(c,e);if(s.includes("SF:")&&s.includes("end_of_record"))return cr(c,e);if(a.startsWith("mode:"))return Cs(s,e||k.dirname(c));if(a.startsWith("<?xml")||a.startsWith("<")){if(s.includes('<counter type="')||s.includes("<report ")){if(n==="kotlin"){let o=Qt(s,e||k.dirname(c));return o.format="kover",o.language="kotlin",o}return Qt(s,e||k.dirname(c))}if(s.includes("CoveredStatements=")||s.includes("<Root"))return vs(s,e||k.dirname(c))}if(n){let o=n.toLowerCase(),u=$o[o];if(u&&u.length>0)try{return await Ke(c,e,u[0])}catch{}}throw new Error(`Unknown coverage format: ${c}`)}async function ur(c,e){let t=e||c,n=[k.join(c,"coverage","lcov.info"),k.join(c,"coverage","coverage-final.json"),k.join(c,"lcov.info"),k.join(c,".nyc_output","coverage.json"),k.join(c,"target","site","jacoco","jacoco.xml"),k.join(c,"build","reports","jacoco","test","jacocoTestReport.xml"),k.join(c,"dotcover-report.xml"),k.join(c,"tarpaulin-report.json"),k.join(c,"cobertura.xml"),k.join(c,"coverage.out"),k.join(c,"cover.out"),k.join(c,"build","reports","kover","report.xml"),k.join(c,"coverage.json")];for(let r of n)try{return await K.access(r),Ke(r,t)}catch{}return null}function dr(c,e,t,n){let r=e>0?c/e*100:0,i=n>0?t/n*100:0;return n===0?r:r*.7+i*.3}function fe(c){let e=0,t=0,n=0,r=0,i=0,s=0,a=0,o=0;for(let u of c.values())e+=u.lines.total,t+=u.lines.covered,n+=u.branches.total,r+=u.branches.covered,i+=u.functions.total,s+=u.functions.covered,a+=u.statements.total,o+=u.statements.covered;return{totalFiles:c.size,lines:{total:e,covered:t,percentage:e>0?t/e*100:0},branches:{total:n,covered:r,percentage:n>0?r/n*100:0},functions:{total:i,covered:s,percentage:i>0?s/i*100:0},statements:{total:a,covered:o,percentage:a>0?o/a*100:0}}}M();function Ss(c){let e=0,t=0,n=0,r=0,i=0,s=0,a=0,o=0;for(let u of c)e+=u.lines.total,t+=u.lines.covered,n+=u.branches.total,r+=u.branches.covered,i+=u.functions.total,s+=u.functions.covered,a+=u.statements.total,o+=u.statements.covered;return{line:e>0?t/e*100:0,branch:n>0?r/n*100:0,function:i>0?s/i*100:0,statement:a>0?o/a*100:0,files:c.length}}function Es(c){let e=[];for(let[t,n]of c.files.entries())e.push({path:n.relativePath||t,lines:{covered:n.lines.covered,total:n.lines.total},branches:{covered:n.branches.covered,total:n.branches.total},functions:{covered:n.functions.covered,total:n.functions.total},statements:{covered:n.statements.covered,total:n.statements.total},uncoveredLines:n.lines.uncoveredLines,uncoveredBranches:n.branches.uncoveredBranches.map(r=>r.line)});return e}var Wt=class extends x{config={name:"qe/coverage/analyze",description:"Analyze code coverage using real LCOV/JSON parsing and compare against thresholds. Includes risk scoring and trend analysis.",domain:"coverage-analysis",schema:zo,streaming:!0,timeout:18e4};analyzerService=null;async getService(e){if(!this.analyzerService){let t=e.memory??await L(),n=await B(e);this.analyzerService=new Fr({memory:t,llmRouter:n})}return this.analyzerService}async execute(e,t){let{target:n=".",coverageFile:r,thresholds:i={lines:80,branches:70,functions:80,statements:80},includeRisk:s=!1,includeRiskScoring:a=!1,dryRun:o=!1,coverageFormat:u,language:l}=e,d=s||a;try{if(this.emitStream(t,{status:"analyzing",message:`Analyzing coverage for ${n}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(this.isDemoMode(t)||o)return this.markAsDemoData(t,"Demo mode explicitly requested"),this.getDemoResult(n,i,d,t);let m=null;if(r)try{m=await Ke(r,n,u,l)}catch(P){return{success:!1,error:`Failed to parse coverage file '${r}': ${E(P)}`}}else m=await ur(n);if(!m||m.files.size===0)return{success:!1,error:`No coverage data found in '${n}'. Run your test suite with coverage enabled (e.g., 'npm test -- --coverage') and ensure coverage reports are generated (lcov.info, coverage-final.json, etc.)`};this.markAsRealData();let p=Es(m),h=await(await this.getService(t)).analyze({coverageData:{files:p,summary:Ss(p)},threshold:i.lines||80,includeFileDetails:!0});if(!h.success)return{success:!1,error:`Analysis failed: ${h.error?.message||"Unknown error"}`};let f=h.value,v={lines:{covered:m.summary.lines.covered,total:m.summary.lines.total,percentage:Math.round(m.summary.lines.percentage*100)/100},branches:{covered:m.summary.branches.covered,total:m.summary.branches.total,percentage:Math.round(m.summary.branches.percentage*100)/100},functions:{covered:m.summary.functions.covered,total:m.summary.functions.total,percentage:Math.round(m.summary.functions.percentage*100)/100},statements:{covered:m.summary.statements.covered,total:m.summary.statements.total,percentage:Math.round(m.summary.statements.percentage*100)/100}},y=p.map(P=>({file:P.path,lines:Math.round(P.lines.covered/(P.lines.total||1)*100),branches:Math.round(P.branches.covered/(P.branches.total||1)*100),functions:Math.round(P.functions.covered/(P.functions.total||1)*100),uncoveredLines:P.uncoveredLines.slice(0,20)})),C=v.lines.percentage>=(i.lines||0)&&v.branches.percentage>=(i.branches||0)&&v.functions.percentage>=(i.functions||0)&&v.statements.percentage>=(i.statements||0),b;if(d){let P=p.reduce((z,X)=>z+X.uncoveredLines.length,0),O=(v.lines.percentage+v.branches.percentage+v.functions.percentage)/3;b=Math.round((1-O/100+Math.min(P/1e3,.5))*100)/100}let w;f.delta&&(w={direction:f.delta.trend,delta:Math.round((f.delta.line+f.delta.branch+f.delta.function)/3*100)/100,history:[{date:new Date(Date.now()-10080*60*1e3).toISOString().split("T")[0],coverage:v.lines.percentage-(f.delta.line||0)},{date:new Date().toISOString().split("T")[0],coverage:v.lines.percentage}]}),this.emitStream(t,{status:"complete",message:`Coverage analysis complete: ${v.lines.percentage}% lines covered`,progress:100});let S=e.language||m.language,T=m.format;return{success:!0,data:{summary:v,byFile:y,thresholdsPassed:C,riskScore:b,trends:w,language:S,format:T}}}catch(m){return{success:!1,error:`Coverage analysis failed: ${E(m)}`}}}getDemoResult(e,t,n,r){let i={lines:{covered:850,total:1e3,percentage:85},branches:{covered:120,total:150,percentage:80},functions:{covered:90,total:100,percentage:90},statements:{covered:900,total:1050,percentage:85.71}},s=[{file:`${e}/service.ts`,lines:92,branches:85,functions:95,uncoveredLines:[45,67,89]},{file:`${e}/utils.ts`,lines:78,branches:70,functions:85,uncoveredLines:[12,34,56,78,90]},{file:`${e}/handler.ts`,lines:88,branches:82,functions:90,uncoveredLines:[23,45]}],a=i.lines.percentage>=(t.lines||0)&&i.branches.percentage>=(t.branches||0)&&i.functions.percentage>=(t.functions||0)&&i.statements.percentage>=(t.statements||0);return this.emitStream(r,{status:"complete",message:`Coverage analysis complete (sample data): ${i.lines.percentage}% lines covered`,progress:100}),{success:!0,data:{summary:i,byFile:s,thresholdsPassed:a,riskScore:n?.25:void 0,trends:{direction:"improving",delta:2.5,history:[{date:new Date(Date.now()-10080*60*1e3).toISOString().split("T")[0],coverage:82.5},{date:new Date().toISOString().split("T")[0],coverage:85}]}}}}resetInstanceCache(){this.analyzerService=null}},Kt=class extends x{config={name:"qe/coverage/gaps",description:"Find coverage gaps using O(log n) HNSW vector search. Prioritizes by risk, complexity, or ML confidence using real coverage data.",domain:"coverage-analysis",schema:Bo,streaming:!0,timeout:12e4};gapService=null;async getService(e){if(!this.gapService){let t=e.memory??await L(),n=await B(e);this.gapService=new Lr({memory:t,llmRouter:n})}return this.gapService}async execute(e,t){let{target:n=".",coverageFile:r,minRisk:i=.3,limit:s=20,prioritization:a="complexity",coverageFormat:o,language:u}=e;try{if(this.emitStream(t,{status:"detecting",message:`Detecting coverage gaps in ${n} (O(log n) search)`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let l=null;if(r)try{l=await Ke(r,n,o,u)}catch(C){return{success:!1,error:`Failed to parse coverage file: ${E(C)}`}}else l=await ur(n);if(this.isDemoMode(t))return this.markAsDemoData(t,"Demo mode explicitly requested"),this.getDemoGapsResult(n,i,s,t);if(!l||l.files.size===0)return r?{success:!1,error:`Coverage file '${r}' contains no usable coverage data (parsed 0 files). Verify the file is a non-empty Istanbul/LCOV/JaCoCo/etc. report.`}:{success:!1,error:`No coverage data found by autodiscovery under target '${n}'. Run your test suite with coverage enabled, or pass coverageFile pointing to an existing report.`};this.markAsRealData();let d=Es(l),m=await this.getService(t),p=a==="change-frequency"?"recent-changes":"risk",g=await m.detectGaps({coverageData:{files:d,summary:Ss(d)},minCoverage:80,prioritize:p});if(!g.success)return{success:!1,error:`Gap detection failed: ${g.error?.message||"Unknown error"}`};let h=g.value,f=h.gaps.filter(C=>C.riskScore>=i).slice(0,s).map(C=>({file:C.file,lines:C.lines,type:C.branches.length>0?"uncovered-branch":"uncovered-line",severity:C.severity,riskScore:Math.round(C.riskScore*100)/100,reason:C.recommendation})),v=f.slice(0,5).map((C,b)=>({file:C.file.replace(/\.ts$/,".test.ts"),description:`Add tests for ${C.lines.length} uncovered lines in ${C.file}`,estimatedCoverageGain:Math.round(C.lines.length/(h.totalUncoveredLines||1)*100*100)/100,priority:b+1})),y;if(e.includeGhost)try{let b=t.kernel;if(b){let w=await b.getDomainAPIAsync("coverage-analysis");if(w?.analyzeGhostCoverage){let S=await w.analyzeGhostCoverage(d.map(T=>T.path),n);S?.success&&S.value&&(y=(S.value.gaps||[]).map(T=>({category:T.category,severity:T.severity,description:T.description,confidence:T.confidence})))}}}catch{}return this.emitStream(t,{status:"complete",message:`Found ${f.length} coverage gaps (${h.totalUncoveredLines} uncovered lines)`,progress:100}),{success:!0,data:{gaps:f,totalGaps:h.gaps.length,criticalGaps:f.filter(C=>C.severity==="critical").length,suggestedTests:v,...y?{ghostGaps:y}:{}}}}catch(l){return{success:!1,error:`Gap detection failed: ${E(l)}`}}}getDemoGapsResult(e,t,n,r){let s=[{file:`${e}/service.ts`,lines:[45,67,89,102,115],type:"uncovered-line",severity:"high",riskScore:.85,reason:"Core business logic with no test coverage"},{file:`${e}/utils.ts`,lines:[12,34,56],type:"uncovered-branch",severity:"medium",riskScore:.65,reason:"Utility functions missing edge case tests"},{file:`${e}/handler.ts`,lines:[23,45,67,89],type:"uncovered-function",severity:"critical",riskScore:.92,reason:"Error handling paths untested"},{file:`${e}/validator.ts`,lines:[10,20,30],type:"uncovered-line",severity:"low",riskScore:.35,reason:"Simple validation logic"}].filter(o=>o.riskScore>=t).slice(0,n),a=s.slice(0,5).map((o,u)=>({file:o.file.replace(/\.ts$/,".test.ts"),description:`Add tests for ${o.lines.length} uncovered lines in ${o.file}`,estimatedCoverageGain:Math.round(o.lines.length/50*100*100)/100,priority:u+1}));return this.emitStream(r,{status:"complete",message:`Found ${s.length} coverage gaps (sample data)`,progress:100}),{success:!0,data:{gaps:s,totalGaps:s.length,criticalGaps:s.filter(o=>o.severity==="critical").length,suggestedTests:a}}}resetInstanceCache(){this.gapService=null}},zo={type:"object",properties:{target:{type:"string",description:"Target directory to analyze (searches for coverage files)",default:"."},coverageFile:{type:"string",description:"Path to coverage report file (lcov.info, coverage-final.json, etc.)"},thresholds:{type:"object",description:"Coverage thresholds",properties:{lines:{type:"number",description:"Line coverage threshold"},branches:{type:"number",description:"Branch coverage threshold"},functions:{type:"number",description:"Function coverage threshold"},statements:{type:"number",description:"Statement coverage threshold"}}},includeRisk:{type:"boolean",description:"Include risk score analysis",default:!1},mlPowered:{type:"boolean",description:"Use ML-powered analysis (vector similarity)",default:!1},language:{type:"string",description:"Source language hint (java, csharp, go, rust, kotlin, swift, dart, typescript, python)"},coverageFormat:{type:"string",description:"Coverage format hint",enum:["lcov","json","jacoco","dotcover","tarpaulin","gocover","kover","xcresult"]}}},Bo={type:"object",properties:{target:{type:"string",description:"Target directory to analyze",default:"."},coverageFile:{type:"string",description:"Path to coverage report file"},minRisk:{type:"number",description:"Minimum risk score to include (0-1)",minimum:0,maximum:1,default:.3},limit:{type:"number",description:"Maximum number of gaps to return",minimum:1,maximum:100,default:20},prioritization:{type:"string",description:"Gap prioritization strategy",enum:["complexity","criticality","change-frequency","ml-confidence"],default:"complexity"},includeGhost:{type:"boolean",description:"Include ADR-059 ghost intent coverage analysis (detect untested behavioral intents)",default:!1},language:{type:"string",description:"Source language filter (java, csharp, go, rust, kotlin, swift, dart)"},coverageFormat:{type:"string",description:"Coverage format hint",enum:["lcov","json","jacoco","dotcover","tarpaulin","gocover","kover","xcresult"]}}};M();var Xt=class extends x{config={name:"qe/quality/evaluate",description:"Evaluate quality gates and provide deployment recommendations. Analyzes coverage, bugs, complexity, and security.",domain:"quality-assessment",schema:jo,streaming:!0,timeout:12e4};async execute(e,t){let{metrics:n=Uo(),gateName:r="default",thresholds:i=Ho(),includeAdvice:s=!0,riskTolerance:a="medium"}=e;try{if(this.emitStream(t,{status:"evaluating",message:`Evaluating quality gate: ${r}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let o=[];i.coverage&&n.coverage!==void 0&&o.push({name:"Coverage",passed:n.coverage>=i.coverage.min,value:n.coverage,threshold:i.coverage.min,severity:"high",message:n.coverage>=i.coverage.min?`Coverage ${n.coverage}% meets threshold`:`Coverage ${n.coverage}% below ${i.coverage.min}% threshold`}),i.testsPassing&&n.testsPassing!==void 0&&o.push({name:"Tests Passing",passed:n.testsPassing>=i.testsPassing.min,value:n.testsPassing,threshold:i.testsPassing.min,severity:"critical",message:n.testsPassing>=i.testsPassing.min?`${n.testsPassing}% tests passing`:`Only ${n.testsPassing}% tests passing`}),i.criticalBugs&&n.criticalBugs!==void 0&&o.push({name:"Critical Bugs",passed:n.criticalBugs<=i.criticalBugs.max,value:n.criticalBugs,threshold:i.criticalBugs.max,severity:"critical",message:n.criticalBugs<=i.criticalBugs.max?`${n.criticalBugs} critical bugs within threshold`:`${n.criticalBugs} critical bugs exceed threshold of ${i.criticalBugs.max}`}),i.securityVulnerabilities&&n.securityVulnerabilities!==void 0&&o.push({name:"Security Vulnerabilities",passed:n.securityVulnerabilities<=i.securityVulnerabilities.max,value:n.securityVulnerabilities,threshold:i.securityVulnerabilities.max,severity:"critical",message:n.securityVulnerabilities<=i.securityVulnerabilities.max?`${n.securityVulnerabilities} vulnerabilities within threshold`:`${n.securityVulnerabilities} vulnerabilities found`}),i.codeSmells&&n.codeSmells!==void 0&&o.push({name:"Code Smells",passed:n.codeSmells<=i.codeSmells.max,value:n.codeSmells,threshold:i.codeSmells.max,severity:"medium",message:n.codeSmells<=i.codeSmells.max?`${n.codeSmells} code smells within threshold`:`${n.codeSmells} code smells detected`});let u=o.filter(f=>f.passed).length,l=o.length,d=l>0?Math.round(u/l*100):100,m=Vo(d,o),p=o.every(f=>f.passed||f.severity!=="critical"),g=s?Qo(p,d,o,a):void 0,h=Wo(o,n);return this.emitStream(t,{status:"complete",message:`Quality evaluation complete: ${m} (${d}%)`,progress:100}),{success:!0,data:{passed:p,score:d,grade:m,checks:o,deploymentAdvice:g,recommendations:h}}}catch(o){return{success:!1,error:`Quality evaluation failed: ${E(o)}`}}}},jo={type:"object",properties:{metrics:{type:"object",description:"Quality metrics to evaluate",properties:{coverage:{type:"number",description:"Code coverage percentage"},testsPassing:{type:"number",description:"Percentage of passing tests"},criticalBugs:{type:"number",description:"Number of critical bugs"},codeSmells:{type:"number",description:"Number of code smells"},securityVulnerabilities:{type:"number",description:"Number of security vulnerabilities"},technicalDebt:{type:"number",description:"Technical debt in hours"},duplications:{type:"number",description:"Code duplication percentage"},complexity:{type:"number",description:"Cyclomatic complexity"}}},gateName:{type:"string",description:"Name of the quality gate",default:"default"},thresholds:{type:"object",description:"Quality gate thresholds"},includeAdvice:{type:"boolean",description:"Include deployment advice",default:!0},riskTolerance:{type:"string",description:"Risk tolerance level",enum:["low","medium","high"],default:"medium"}}};function Uo(){return{coverage:80,testsPassing:95,criticalBugs:0,codeSmells:15,securityVulnerabilities:0,technicalDebt:4,duplications:3,complexity:8}}function Ho(){return{coverage:{min:80},testsPassing:{min:95},criticalBugs:{max:0},securityVulnerabilities:{max:0},codeSmells:{max:50},technicalDebt:{max:8}}}function Vo(c,e){return e.some(n=>!n.passed&&n.severity==="critical")?"F":c>=90?"A":c>=80?"B":c>=70?"C":c>=60?"D":"F"}function Qo(c,e,t,n){let r=t.filter(d=>!d.passed&&d.severity==="critical"),i=t.filter(d=>!d.passed&&d.severity==="high"),s=r.length*.4+i.length*.2+(100-e)/100,a=Math.min(s,1),o,l={low:{block:.2,warn:.1},medium:{block:.4,warn:.2},high:{block:.6,warn:.4}}[n];return a>=l.block||r.length>0?o="blocked":a>=l.warn?o="warning":o="approved",{decision:o,confidence:Math.round((1-a)*100)/100,riskScore:Math.round(a*100)/100,reasons:[...r.map(d=>`Critical: ${d.name} - ${d.message}`),...i.map(d=>`High: ${d.name} - ${d.message}`)],conditions:o==="warning"?["Monitor closely after deployment","Prepare rollback plan"]:void 0,rollbackPlan:o!=="approved"?"Revert to previous version if issues detected":void 0}}function Wo(c,e){let t=[],n=c.filter(r=>!r.passed);for(let r of n)t.push({type:r.severity==="critical"?"critical":r.severity==="high"?"warning":"improvement",title:`Fix ${r.name}`,description:r.message,impact:r.severity==="critical"||r.severity==="high"?"high":"medium",effort:"medium"});return(e.coverage||0)<90&&t.push({type:"improvement",title:"Increase test coverage",description:`Current coverage is ${e.coverage}%. Consider adding tests for critical paths.`,impact:"medium",effort:"medium"}),t}M();var Yt={codeComplexity:"High cyclomatic complexity increases defect probability",changeFrequency:"Frequently modified files are more prone to defects",bugHistory:"Previous defects in this area indicate higher risk",testCoverage:"Low test coverage increases undetected defect risk",developerExperience:"Code written by less experienced developers may have more issues",codeAge:"New code is more likely to have defects than mature, stable code",complexity:"High cyclomatic complexity increases defect probability",churn:"Frequently modified files are more prone to defects",history:"Previous defects in this area indicate higher risk",coverage:"Low test coverage increases undetected defect risk",coupling:"High coupling makes changes risky",age:"New code may have more defects than stable code"},Jt=class extends x{config={name:"qe/defects/predict",description:"Predict defect probability for files using ML models. Analyzes code complexity, change frequency, git history, and test coverage.",domain:"defect-intelligence",schema:Ko,streaming:!0,timeout:18e4};predictorService=null;async getService(e){if(!this.predictorService){let t=e.memory??await L(),n=await B(e);this.predictorService=new Nr({memory:t,llmRouter:n})}return this.predictorService}async execute(e,t){let{files:n=[],threshold:r=.5,minConfidence:i=.7,features:s=[{name:"codeComplexity",weight:.25},{name:"changeFrequency",weight:.2},{name:"developerExperience",weight:.15},{name:"testCoverage",weight:.2},{name:"codeAge",weight:.1},{name:"bugHistory",weight:.1}]}=e;try{if(this.emitStream(t,{status:"analyzing",message:`Analyzing ${n.length||"provided"} files using ML-based prediction`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(this.isDemoMode(t))return this.markAsDemoData(t,"Demo mode explicitly requested"),this.getDemoResult(n);let a=await this.getService(t),o=await a.predictDefects({files:n,features:s.map(g=>({name:g.name,weight:g.weight??.25})),threshold:r});if(!o.success)return{success:!1,error:`Defect prediction failed: ${o.error?.message||"Service unavailable"}. Ensure the defect-intelligence domain is properly initialized.`};this.markAsRealData();let d=o.value.predictions.filter(g=>g.probability>=1-i).map(g=>({file:g.file,probability:Math.round(g.probability*100)/100,riskLevel:Xo(g.riskLevel),factors:g.factors.map(h=>({name:h.name,contribution:h.contribution,description:Yt[h.name]||`${h.name} contributes to defect risk`})),recommendations:g.recommendations}));d.sort((g,h)=>h.probability-g.probability);let m=Yo(d),p=await a.getModelMetrics();return this.emitStream(t,{status:"complete",message:`Analyzed ${n.length} files, ${d.length} with elevated risk`,progress:100}),{success:!0,data:{predictions:d,modelConfidence:o.value.modelConfidence,topRiskFactors:m,recommendations:Zo(d),modelMetrics:{accuracy:p.accuracy,precision:p.precision,recall:p.recall,f1Score:p.f1Score}}}}catch(a){return{success:!1,error:`Defect prediction failed: ${E(a)}`}}}getDemoResult(e){let n=(e.length>0?e:["src/service.ts","src/handler.ts","src/utils.ts"]).map((r,i)=>({file:r,probability:Math.max(.9-i*.15,.35),riskLevel:i===0?"high":i===1?"medium":"low",factors:[{name:"codeComplexity",contribution:.35,description:Yt.codeComplexity},{name:"changeFrequency",contribution:.25,description:Yt.changeFrequency},{name:"testCoverage",contribution:.2,description:Yt.testCoverage}],recommendations:[`Increase test coverage for ${r}`,"Consider refactoring complex functions","Review recent changes for potential issues"]}));return{success:!0,data:{predictions:n,modelConfidence:.85,topRiskFactors:[{name:"High Complexity",impact:.35,affectedFiles:n.length},{name:"Frequent Changes",impact:.25,affectedFiles:Math.ceil(n.length*.7)},{name:"Low Coverage",impact:.2,affectedFiles:Math.ceil(n.length*.5)}],recommendations:["Focus testing on files with highest defect probability","Increase test coverage in high-risk areas","Review recent changes to frequently-modified files","Consider refactoring complex modules"],modelMetrics:{accuracy:.82,precision:.78,recall:.85,f1Score:.81}}}}resetInstanceCache(){this.predictorService=null}},Ko={type:"object",properties:{files:{type:"array",description:"Specific files to analyze",items:{type:"string",description:"File path"}},target:{type:"string",description:"Target directory to analyze",default:"."},lookback:{type:"number",description:"Days of history to consider",minimum:7,maximum:365,default:30},threshold:{type:"number",description:"Risk threshold for classification (0-1)",minimum:0,maximum:1,default:.5},minConfidence:{type:"number",description:"Minimum prediction confidence (0-1)",minimum:0,maximum:1,default:.7},features:{type:"array",description:"Features to use for prediction",items:{type:"object",description:"Prediction feature",properties:{name:{type:"string",description:"Feature name"},weight:{type:"number",description:"Feature weight"}}}}}};function Xo(c){switch(c){case"critical":return"critical";case"high":return"high";case"medium":return"medium";default:return"low"}}function Yo(c){let e=new Map;for(let n of c)for(let r of n.factors){let i=e.get(r.name)||{impact:0,count:0};i.impact+=r.contribution,i.count+=1,e.set(r.name,i)}let t=[];for(let[n,r]of e)t.push({name:Jo(n),impact:Math.round(r.impact/r.count*100)/100,affectedFiles:r.count});return t.sort((n,r)=>r.impact-n.impact),t.slice(0,5)}function Jo(c){return{codeComplexity:"High Complexity",changeFrequency:"Frequent Changes",bugHistory:"Bug History",testCoverage:"Low Coverage",developerExperience:"Developer Experience",codeAge:"Code Age"}[c]||c.replace(/([A-Z])/g," $1").trim()}function Zo(c){let e=[],t=c.filter(i=>i.riskLevel==="critical").length,n=c.filter(i=>i.riskLevel==="high").length,r=c.length>0?c.reduce((i,s)=>i+s.probability,0)/c.length:0;return t>0&&(e.push(`CRITICAL: ${t} files require immediate attention`),e.push("Consider code review and comprehensive testing before deployment")),n>0&&(e.push(`High risk detected in ${n} files`),e.push("Increase test coverage in high-risk areas")),r>.5?(e.push("Overall defect risk is elevated - consider delaying release"),e.push("Run full regression test suite before deployment")):e.push("Focus testing on files with highest defect probability"),e.push("Review recent changes to frequently-modified files"),e.push("Consider refactoring complex modules"),[...new Set(e)]}M();var Zt=class extends x{config={name:"qe/requirements/validate",description:"Validate requirements for testability. Scores each requirement, detects ambiguity, and optionally generates BDD scenarios.",domain:"requirements-validation",schema:ec,streaming:!0,timeout:12e4};async execute(e,t){let{requirements:n,generateBDD:r=!1,checkAmbiguity:i=!0,minTestability:s=60}=e;try{if(this.emitStream(t,{status:"validating",message:`Validating ${n.length} requirements`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let a=[],o=[];for(let l of n){this.emitStream(t,{status:"processing",message:`Analyzing: ${l.title}`});let d=tc(l),m=nc(l,s,d),p=i?rc(l):void 0;a.push({requirementId:l.id,isValid:m.filter(g=>g.severity==="error").length===0,testabilityScore:d,errors:m,ambiguityReport:p}),r&&d.value>=s&&o.push(...sc(l))}let u={total:n.length,valid:a.filter(l=>l.isValid).length,invalid:a.filter(l=>!l.isValid).length,avgTestability:a.reduce((l,d)=>l+d.testabilityScore.value,0)/n.length,blockers:a.filter(l=>l.errors.some(d=>d.severity==="error")).length};return this.emitStream(t,{status:"complete",message:`Validation complete: ${u.valid}/${u.total} valid`,progress:100}),{success:!0,data:{validationResults:a,summary:u,bddScenarios:o.length>0?o:void 0,recommendations:ac(a)}}}catch(a){return{success:!1,error:`Validation failed: ${E(a)}`}}}},ec={type:"object",properties:{requirements:{type:"array",description:"Requirements to validate",items:{type:"object",description:"Requirement input",properties:{id:{type:"string",description:"Requirement ID"},title:{type:"string",description:"Requirement title"},description:{type:"string",description:"Requirement description"},acceptanceCriteria:{type:"array",description:"Acceptance criteria",items:{type:"string",description:"Criterion"}},type:{type:"string",description:"Requirement type",enum:["user-story","functional","non-functional","technical"]}},required:["id","title","description"]}},generateBDD:{type:"boolean",description:"Generate BDD scenarios from requirements",default:!1},checkAmbiguity:{type:"boolean",description:"Check for ambiguous language",default:!0},minTestability:{type:"number",description:"Minimum testability score (0-100)",minimum:0,maximum:100,default:60}},required:["requirements"]};function tc(c){let e=[],t=c.acceptanceCriteria&&c.acceptanceCriteria.length>0?90:40;e.push({name:"Acceptance Criteria",score:t,issues:t<70?["Missing or incomplete acceptance criteria"]:[]});let n=c.description.length,r=n>100?85:n>50?70:50;e.push({name:"Description Clarity",score:r,issues:r<70?["Description may be too brief"]:[]});let a=["should","must","when","then","verify","validate"].some(u=>c.description.toLowerCase().includes(u))?80:50;e.push({name:"Measurability",score:a,issues:a<70?["Requirement lacks measurable criteria"]:[]});let o=Math.round(e.reduce((u,l)=>u+l.score,0)/e.length);return{value:o,category:o>=80?"excellent":o>=70?"good":o>=50?"fair":"poor",factors:e}}function nc(c,e,t){let n=[];return t.value<e&&n.push({code:"LOW_TESTABILITY",message:`Testability score ${t.value} is below minimum ${e}`,severity:"error",suggestion:"Add clear acceptance criteria and measurable outcomes"}),(!c.acceptanceCriteria||c.acceptanceCriteria.length===0)&&n.push({code:"MISSING_AC",message:"No acceptance criteria defined",severity:"warning",suggestion:"Define specific, testable acceptance criteria"}),c.description.length<30&&n.push({code:"BRIEF_DESC",message:"Description is too brief",severity:"warning",suggestion:"Expand description with more context and details"}),n}function rc(c){let e=[],t=["some","few","many","fast","slow","good","better","appropriate"];for(let n of t)c.description.toLowerCase().includes(n)&&e.push({term:n,context:`Found in: "${c.description.substring(0,50)}..."`,alternatives:ic(n)});return{ambiguousTerms:e,overallScore:Math.max(0,100-e.length*15),suggestions:e.length>0?["Replace vague terms with specific, measurable criteria"]:["Requirement language is clear"]}}function ic(c){return{some:["exactly N","at least N","between N and M"],few:["1-3","less than 5"],many:["more than 10","at least N"],fast:["within X milliseconds","response time < Xs"],slow:["longer than X seconds"],good:["score >= 80%","passes all criteria"],better:["improves by X%","exceeds baseline by N"],appropriate:["meets requirement X","validates against schema"]}[c]||["Be more specific"]}function sc(c){let e=[];return e.push({id:`scenario-${c.id}-1`,feature:c.title,scenario:`Verify ${c.title}`,given:["the system is initialized","the user is authenticated"],when:["the user performs the action"],then:["the expected outcome is observed","the system state is updated"],tags:["@generated",`@${c.type||"functional"}`]}),c.acceptanceCriteria&&c.acceptanceCriteria.length>0&&c.acceptanceCriteria.forEach((t,n)=>{e.push({id:`scenario-${c.id}-ac${n+1}`,feature:c.title,scenario:`Acceptance Criteria: ${t.substring(0,50)}`,given:["the preconditions are met"],when:["the specified action is taken"],then:[t],tags:["@generated","@acceptance"]})}),e}function ac(c){let e=[],t=c.filter(r=>r.testabilityScore.value<60).length,n=c.filter(r=>r.errors.some(i=>i.code==="MISSING_AC")).length;return t>0&&e.push(`${t} requirements have low testability scores. Consider adding acceptance criteria.`),n>0&&e.push(`${n} requirements lack acceptance criteria. Define testable criteria for each.`),c.every(r=>r.isValid)&&e.push("All requirements are valid and testable."),e}import{existsSync as mr,readFileSync as ws}from"fs";import{join as pr,dirname as oc}from"path";import{fileURLToPath as cc}from"url";var _e=["Capability","Reliability","Usability","Charisma","Security","Scalability","Compatibility","Performance","Installability","Development"],Fe=["Capability","Reliability","Security","Performance","Development"];var lc=cc(import.meta.url),uc=oc(lc),Xe=class{config;templateCache=null;constructor(e={}){this.config={enableSemanticAnalysis:e.enableSemanticAnalysis??!0,defaultOutputFormat:e.defaultOutputFormat??"html",templatePath:e.templatePath??this.findTemplatePath(),minimumCategories:e.minimumCategories??8}}findTemplatePath(){let e=[pr(process.cwd(),".claude/helpers/v3/quality-criteria/quality-criteria-reference-template.html"),pr(process.cwd(),"node_modules/agentic-qe/assets/agents/v3/helpers/quality-criteria/quality-criteria-reference-template.html"),pr(uc,"../../../../../assets/agents/v3/helpers/quality-criteria/quality-criteria-reference-template.html")];for(let t of e)if(mr(t))return t;return e[0]}analyze(e){let t=e.epicContent||"";if(e.epicPath&&mr(e.epicPath)&&(t=ws(e.epicPath,"utf-8")),!t&&!e.epicPath)throw new Error("Either epicPath or epicContent is required for analysis");return{agentInvocation:{required:!0,agentType:"qe-quality-criteria-recommender",prompt:this.buildAgentPrompt({assessmentName:e.assessmentName,epicContent:t,epicPath:e.epicPath,sourcePaths:e.sourcePaths,outputFormat:e.outputFormat,outputPath:e.outputPath}),timeout:3e5,expectedOutput:"QualityCriteriaAnalysis",instructions:`Claude Code MUST spawn the qe-quality-criteria-recommender agent with this prompt. The agent will perform real semantic HTSM analysis using Claude's reasoning capabilities. Use: Task("HTSM Quality Criteria Analysis", { prompt: <this prompt> }, "qe-quality-criteria-recommender")`},message:"AGENT INVOCATION REQUIRED: This service cannot perform semantic HTSM analysis alone. Claude Code must spawn the qe-quality-criteria-recommender agent with the provided prompt."}}buildAgentPrompt(e){let{assessmentName:t,epicContent:n,epicPath:r,sourcePaths:i,outputFormat:s,outputPath:a}=e,o=i&&i.length>0?`
424
+ `).length;e.push({name:"real-timers-in-tests",location:`${n}:${f}`,severity:"medium",suggestion:"Using real timers in tests can cause flakiness. Consider using fake timers (jest.useFakeTimers() or vi.useFakeTimers())"})}}}catch{continue}return e}function zo(c){let e=0,t=-1,n=-1;for(let r=0;r<c.length;r++)if(c[r]==="{")t===-1&&(t=r),e++;else if(c[r]==="}"&&(e--,e===0&&t!==-1)){n=r;break}return t!==-1&&n!==-1?c.substring(t+1,n):null}function Bo(c){let e=0,t=-1,n=-1;for(let r=0;r<c.length;r++)if(c[r]==="{")t===-1&&(t=r),e++;else if(c[r]==="}"&&(e--,e===0&&t!==-1)){n=r;break}return t!==-1&&n!==-1?c.substring(t+1,n):null}function jo(c,e){let t=[];return c.length===0&&t.push("No tests generated. Ensure source files are valid."),e&&(t.push("Consider adding property-based tests for edge case coverage"),t.push("Parameterized tests can reduce duplication")),t}k();je();var Qt=class extends P{config={name:"qe/tests/execute",description:"Execute test suites with parallel execution, retry logic, and coverage collection. Detects flaky tests.",domain:"test-execution",schema:Uo,streaming:!0,timeout:3e5};async execute(e,t){let{testFiles:n=[],testSuites:r=[],pattern:i,parallel:s=!0,parallelism:a=4,retryCount:o=3,timeout:u=6e4,collectCoverage:l=!1,reportFormat:d="json",failFast:m=!1}=e,p=Date.now();try{let g=n.length>0?n:r.length>0?r:i?[i]:["**/*.test.ts"];if(this.emitStream(t,{status:"starting",message:`Executing ${g.length} test files`,parallel:s,parallelism:a}),this.isAborted(t))return{success:!1,error:"Test execution aborted"};let h=[],f=[];for(let b=0;b<g.length;b++){let w=g[b];this.emitStream(t,{status:"running",message:`Executing ${w}`,progress:Math.round(b/g.length*100)});let E=te()>.1,S={id:`test-${b}`,name:`Test suite for ${w.split("/").pop()}`,file:w,status:E?"passed":"failed",duration:te()*5e3,error:E?void 0:"Assertion failed",retries:E?0:Math.min(o,2)};if(h.push(S),!E&&te()>.7&&f.push({name:S.name,file:S.file,flakinessScore:ne(.5,1),failurePattern:"intermittent-timeout"}),m&&!E)break}let v={total:h.length,passed:h.filter(b=>b.status==="passed").length,failed:h.filter(b=>b.status==="failed").length,skipped:h.filter(b=>b.status==="skipped").length,pending:h.filter(b=>b.status==="pending").length,passRate:0};v.passRate=v.total>0?Math.round(v.passed/v.total*100):0;let y=l?{lines:ne(70,100),branches:ne(60,80),functions:ne(65,90),statements:ne(70,95)}:void 0,C=Date.now()-p;return this.emitStream(t,{status:"complete",message:`Test execution complete: ${v.passed}/${v.total} passed`,progress:100}),{success:v.failed===0,data:{summary:v,testResults:h,coverage:y,flakyTests:f.length>0?f:void 0,duration:C}}}catch(g){return{success:!1,error:`Test execution failed: ${T(g)}`}}}},Uo={type:"object",properties:{testFiles:{type:"array",description:"Specific test files to execute",items:{type:"string",description:"Test file path"}},testSuites:{type:"array",description:"Test suite names to execute",items:{type:"string",description:"Suite name"}},pattern:{type:"string",description:"Glob pattern to match test files"},parallel:{type:"boolean",description:"Enable parallel test execution",default:!0},parallelism:{type:"number",description:"Number of parallel workers",minimum:1,maximum:16,default:4},retryCount:{type:"number",description:"Number of retries for failed tests",minimum:0,maximum:5,default:3},timeout:{type:"number",description:"Test timeout in milliseconds",minimum:1e3,default:6e4},collectCoverage:{type:"boolean",description:"Collect code coverage",default:!1},reportFormat:{type:"string",description:"Report output format",enum:["json","junit","html","markdown"],default:"json"},failFast:{type:"boolean",description:"Stop on first failure",default:!1},watch:{type:"boolean",description:"Watch mode for continuous testing",default:!1}}};H();import*as K from"fs/promises";import*as M from"path";async function ur(c,e){let t=await K.readFile(c,"utf-8");return Es(t,e||M.dirname(c))}function Es(c,e){let t=new Map,n=c.split(`
425
+ `),r=null,i=new Map,s=[],a=[],o=0,u=0,l=0,d=0,m=0,p=0;for(let g of n){let h=g.trim();if(h.startsWith("SF:")){let f=h.slice(3);r={path:f,relativePath:M.relative(e,f)},i=new Map,s=[],a=[],o=0,u=0,l=0,d=0,m=0,p=0}else if(h.startsWith("DA:")){let[f,v]=h.slice(3).split(",").map(Number);!isNaN(f)&&!isNaN(v)&&(i.set(f,v),o++,v>0&&u++)}else if(h.startsWith("LF:")){let f=parseInt(h.slice(3),10);isNaN(f)||(o=f)}else if(h.startsWith("LH:")){let f=parseInt(h.slice(3),10);isNaN(f)||(u=f)}else if(h.startsWith("BRDA:")){let f=h.slice(5).split(",");if(f.length>=4){let v=parseInt(f[0],10),y=parseInt(f[1],10),C=parseInt(f[2],10),b=f[3]==="-"?0:parseInt(f[3],10);s.push({line:v,block:y,branch:C,taken:b>0,hits:b}),l++,b>0&&d++}}else if(h.startsWith("BRF:")){let f=parseInt(h.slice(4),10);isNaN(f)||(l=f)}else if(h.startsWith("BRH:")){let f=parseInt(h.slice(4),10);isNaN(f)||(d=f)}else if(h.startsWith("FN:")){let f=h.indexOf(",",3);if(f>0){let v=parseInt(h.slice(3,f),10),y=h.slice(f+1);a.find(b=>b.name===y)||a.push({name:y,line:v,hits:0})}}else if(h.startsWith("FNDA:")){let f=h.indexOf(",",5);if(f>0){let v=parseInt(h.slice(5,f),10),y=h.slice(f+1),C=a.find(b=>b.name===y);C?C.hits=v:a.push({name:y,line:0,hits:v}),m++,v>0&&p++}}else if(h.startsWith("FNF:")){let f=parseInt(h.slice(4),10);isNaN(f)||(m=f)}else if(h.startsWith("FNH:")){let f=parseInt(h.slice(4),10);isNaN(f)||(p=f)}else if(h==="end_of_record"&&r?.path){let f=Array.from(i.entries()).filter(([,b])=>b===0).map(([b])=>b).sort((b,w)=>b-w),v=s.filter(b=>!b.taken),y=a.filter(b=>b.hits===0).map(b=>b.name),C={path:r.path,relativePath:r.relativePath||r.path,lines:{total:o,covered:u,percentage:o>0?u/o*100:0,details:i,uncoveredLines:f},branches:{total:l,covered:d,percentage:l>0?d/l*100:0,uncoveredBranches:v},functions:{total:m,covered:p,percentage:m>0?p/m*100:0,details:a,uncoveredFunctions:y},statements:{total:o,covered:u,percentage:o>0?u/o*100:0},coveragePercentage:pr(u,o,d,l)};t.set(r.path,C),r=null}}return{timestamp:new Date,format:"lcov",files:t,summary:fe(t)}}async function dr(c,e){let t=await K.readFile(c,"utf-8"),n=A(t),r=e||M.dirname(c),i=new Map;for(let[s,a]of Object.entries(n)){if(typeof a!="object"||!a.statementMap)continue;let o=new Map,u=[],l=0,d=0;for(let[b,w]of Object.entries(a.s||{})){let E=a.statementMap[b];if(E?.start?.line){let S=E.start.line,x=o.get(S)||0;o.set(S,x+w)}l++,w>0&&d++}for(let[b,w]of o.entries())w===0&&u.push(b);let m=[],p=0,g=0;for(let[b,w]of Object.entries(a.branchMap||{})){let E=a.b?.[b]||[];for(let S=0;S<E.length;S++)m.push({line:w.loc?.start?.line||0,block:parseInt(b,10),branch:S,taken:E[S]>0,hits:E[S]}),p++,E[S]>0&&g++}let h=[],f=0,v=0;for(let[b,w]of Object.entries(a.fnMap||{})){let E=a.f?.[b]||0;h.push({name:w.name||`anonymous_${b}`,line:w.loc?.start?.line||w.decl?.start?.line||0,hits:E}),f++,E>0&&v++}let y=o.size,C=Array.from(o.values()).filter(b=>b>0).length;i.set(s,{path:s,relativePath:M.relative(r,s),lines:{total:y,covered:C,percentage:y>0?C/y*100:0,details:o,uncoveredLines:u.sort((b,w)=>b-w)},branches:{total:p,covered:g,percentage:p>0?g/p*100:0,uncoveredBranches:m.filter(b=>!b.taken)},functions:{total:f,covered:v,percentage:f>0?v/f*100:0,details:h,uncoveredFunctions:h.filter(b=>b.hits===0).map(b=>b.name)},statements:{total:l,covered:d,percentage:l>0?d/l*100:0},coveragePercentage:pr(C,y,g,p)})}return{timestamp:new Date,format:"json",files:i,summary:fe(i)}}async function ys(c,e){let t=await K.readFile(c,"utf-8");return Wt(t,e||M.dirname(c))}function Wt(c,e){let t=new Map,n=/<package\s+name="([^"]*)">([\s\S]*?)<\/package>/g,r;for(;(r=n.exec(c))!==null;){let i=r[1].replace(/\//g,M.sep),s=r[2],a=/<sourcefile\s+name="([^"]*)">([\s\S]*?)<\/sourcefile>/g,o;for(;(o=a.exec(s))!==null;){let u=o[1],l=o[2],d=M.join(e,i,u),m=Ho(l),p=new Map,g=/<line\s+nr="(\d+)"\s+mi="(\d+)"\s+ci="(\d+)"/g,h;for(;(h=g.exec(l))!==null;){let v=parseInt(h[1],10),y=parseInt(h[3],10);p.set(v,y)}let f=Array.from(p.entries()).filter(([,v])=>v===0).map(([v])=>v).sort((v,y)=>v-y);t.set(d,{path:d,relativePath:M.join(i,u),lines:{total:m.LINE.total,covered:m.LINE.covered,percentage:m.LINE.total>0?m.LINE.covered/m.LINE.total*100:0,details:p,uncoveredLines:f},branches:{total:m.BRANCH.total,covered:m.BRANCH.covered,percentage:m.BRANCH.total>0?m.BRANCH.covered/m.BRANCH.total*100:0,uncoveredBranches:[]},functions:{total:m.METHOD.total,covered:m.METHOD.covered,percentage:m.METHOD.total>0?m.METHOD.covered/m.METHOD.total*100:0,details:[],uncoveredFunctions:[]},statements:{total:m.INSTRUCTION.total,covered:m.INSTRUCTION.covered,percentage:m.INSTRUCTION.total>0?m.INSTRUCTION.covered/m.INSTRUCTION.total*100:0},coveragePercentage:pr(m.LINE.covered,m.LINE.total,m.BRANCH.covered,m.BRANCH.total)})}}return{timestamp:new Date,format:"jacoco",language:"java",files:t,summary:fe(t)}}function Ho(c){let e={LINE:{covered:0,total:0},BRANCH:{covered:0,total:0},METHOD:{covered:0,total:0},INSTRUCTION:{covered:0,total:0}},t=/<counter\s+type="(\w+)"\s+missed="(\d+)"\s+covered="(\d+)"\s*\/>/g,n;for(;(n=t.exec(c))!==null;){let r=n[1],i=parseInt(n[2],10),s=parseInt(n[3],10);e[r]&&(e[r].covered+=s,e[r].total+=i+s)}return e}async function vs(c,e){let t=await K.readFile(c,"utf-8");return ws(t,e||M.dirname(c))}function ws(c,e){let t=new Map,n=new Map,r=/<File\s+Index="(\d+)"\s+Name="([^"]*)"\s*\/>/g,i;for(;(i=r.exec(c))!==null;)n.set(i[1],i[2]);let s=/<Statement\s+FileIndex="(\d+)"\s+Line="(\d+)"\s+Column="\d+"\s+EndLine="\d+"\s+EndColumn="\d+"\s+Covered="(\w+)"\s*\/>/g,a=new Map,o;for(;(o=s.exec(c))!==null;){let u=o[1],l=parseInt(o[2],10),d=o[3]==="True",m=n.get(u)||`file-${u}`;a.has(m)||a.set(m,{lineDetails:new Map,total:0,covered:0});let p=a.get(m);p.lineDetails.set(l,d?1:0),p.total++,d&&p.covered++}if(a.size===0){let l=/CoveredStatements="(\d+)"\s+TotalStatements="(\d+)"/.exec(c);if(l){let d=parseInt(l[1],10),m=parseInt(l[2],10),p=M.join(e,"aggregate");t.set(p,{path:p,relativePath:"aggregate",lines:{total:m,covered:d,percentage:m>0?d/m*100:0,details:new Map,uncoveredLines:[]},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:m,covered:d,percentage:m>0?d/m*100:0},coveragePercentage:m>0?d/m*100:0})}}for(let[u,l]of a.entries()){let d=Array.from(l.lineDetails.entries()).filter(([,m])=>m===0).map(([m])=>m).sort((m,p)=>m-p);t.set(u,{path:u,relativePath:M.relative(e,u),lines:{total:l.lineDetails.size,covered:Array.from(l.lineDetails.values()).filter(m=>m>0).length,percentage:l.lineDetails.size>0?Array.from(l.lineDetails.values()).filter(m=>m>0).length/l.lineDetails.size*100:0,details:l.lineDetails,uncoveredLines:d},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:l.total,covered:l.covered,percentage:l.total>0?l.covered/l.total*100:0},coveragePercentage:l.total>0?l.covered/l.total*100:0})}return{timestamp:new Date,format:"dotcover",language:"csharp",files:t,summary:fe(t)}}async function bs(c,e){let t=await K.readFile(c,"utf-8"),n=e||M.dirname(c);if(t.includes("SF:")&&t.includes("end_of_record")){let r=Es(t,n);return r.format="tarpaulin",r.language="rust",r}return Rs(t,n)}function Rs(c,e){let t=new Map,n=A(c);for(let r of n?.files||[]){let i=r.path||"",s=new Map,a=0,o=0;for(let l of r.traces||[]){let d=l.line,m=l.stats?.Line??l.stats?.line??0;typeof d=="number"&&(s.set(d,m),a++,m>0&&o++)}let u=Array.from(s.entries()).filter(([,l])=>l===0).map(([l])=>l).sort((l,d)=>l-d);t.set(i,{path:i,relativePath:M.relative(e,i),lines:{total:a,covered:o,percentage:a>0?o/a*100:0,details:s,uncoveredLines:u},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:a,covered:o,percentage:a>0?o/a*100:0},coveragePercentage:a>0?o/a*100:0})}return{timestamp:new Date,format:"tarpaulin",language:"rust",files:t,summary:fe(t)}}async function Cs(c,e){let t=await K.readFile(c,"utf-8");return Ps(t,e||M.dirname(c))}function Ps(c,e){let t=new Map,n=new Map,r=c.split(`
426
+ `);for(let i of r){let s=i.trim();if(!s||s.startsWith("mode:"))continue;let a=s.match(/^(.+):(\d+)\.\d+,(\d+)\.\d+\s+(\d+)\s+(\d+)$/);if(!a)continue;let o=a[1],u=parseInt(a[2],10),l=parseInt(a[3],10),d=parseInt(a[4],10),m=parseInt(a[5],10);n.has(o)||n.set(o,{lineDetails:new Map,stmtTotal:0,stmtCovered:0});let p=n.get(o);for(let g=u;g<=l;g++){let h=p.lineDetails.get(g)||0;p.lineDetails.set(g,h+m)}p.stmtTotal+=d,m>0&&(p.stmtCovered+=d)}for(let[i,s]of n.entries()){let a=s.lineDetails.size,o=Array.from(s.lineDetails.values()).filter(l=>l>0).length,u=Array.from(s.lineDetails.entries()).filter(([,l])=>l===0).map(([l])=>l).sort((l,d)=>l-d);t.set(i,{path:i,relativePath:M.relative(e,i),lines:{total:a,covered:o,percentage:a>0?o/a*100:0,details:s.lineDetails,uncoveredLines:u},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:s.stmtTotal,covered:s.stmtCovered,percentage:s.stmtTotal>0?s.stmtCovered/s.stmtTotal*100:0},coveragePercentage:s.stmtTotal>0?s.stmtCovered/s.stmtTotal*100:0})}return{timestamp:new Date,format:"gocover",language:"go",files:t,summary:fe(t)}}async function Ts(c,e){let t=await K.readFile(c,"utf-8"),n=Wt(t,e||M.dirname(c));return n.format="kover",n.language="kotlin",n}async function Ss(c,e){let t=await K.readFile(c,"utf-8");return xs(t,e||M.dirname(c))}function xs(c,e){let t=new Map,r=A(c)?.targets||[];for(let i of r)for(let s of i.files||[]){let a=s.path||"",o=s.executableLines||0,u=s.coveredLines||0,l=s.lineCoverage||0,d=[],m=0,p=0;for(let g of s.functions||[]){let h=g.coveredLines>0?1:0;d.push({name:g.name||"unknown",line:g.lineNumber||0,hits:h}),m++,h>0&&p++}t.set(a,{path:a,relativePath:M.relative(e,a),lines:{total:o,covered:u,percentage:l*100,details:new Map,uncoveredLines:[]},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:m,covered:p,percentage:m>0?p/m*100:0,details:d,uncoveredFunctions:d.filter(g=>g.hits===0).map(g=>g.name)},statements:{total:o,covered:u,percentage:l*100},coveragePercentage:l*100})}return{timestamp:new Date,format:"xcresult",language:"swift",files:t,summary:fe(t)}}var Vo={java:["jacoco","cobertura","lcov"],kotlin:["kover","jacoco"],csharp:["dotcover","cobertura"],rust:["tarpaulin","lcov"],go:["gocover"],swift:["xcresult"],dart:["lcov"],typescript:["lcov","json"],javascript:["lcov","json"],python:["lcov","cobertura","json"]};async function Ke(c,e,t,n){if(t)switch(t){case"lcov":return ur(c,e);case"json":return dr(c,e);case"jacoco":return ys(c,e);case"dotcover":return vs(c,e);case"tarpaulin":return bs(c,e);case"gocover":return Cs(c,e);case"kover":return Ts(c,e);case"xcresult":return Ss(c,e);default:break}let r=M.extname(c).toLowerCase(),i=M.basename(c).toLowerCase();if(r===".json"||i.includes("coverage-final"))return dr(c,e);if(i==="lcov.info"||r===".info"||i.includes("lcov"))return ur(c,e);if(i.includes("jacoco")&&r===".xml")return ys(c,e);if(i.includes("dotcover")&&r===".xml")return vs(c,e);if(i.includes("tarpaulin"))return bs(c,e);if(i.includes("kover")&&r===".xml")return Ts(c,e);if(i.includes("coverage")&&r===".out")return Cs(c,e);if(i.includes("xcresult")||i.includes("xccov"))return Ss(c,e);let s=await K.readFile(c,"utf-8"),a=s.trim();if(a.startsWith("{"))return a.includes('"files"')&&a.includes('"traces"')?Rs(s,e||M.dirname(c)):a.includes('"targets"')&&a.includes('"lineCoverage"')?xs(s,e||M.dirname(c)):dr(c,e);if(s.includes("SF:")&&s.includes("end_of_record"))return ur(c,e);if(a.startsWith("mode:"))return Ps(s,e||M.dirname(c));if(a.startsWith("<?xml")||a.startsWith("<")){if(s.includes('<counter type="')||s.includes("<report ")){if(n==="kotlin"){let o=Wt(s,e||M.dirname(c));return o.format="kover",o.language="kotlin",o}return Wt(s,e||M.dirname(c))}if(s.includes("CoveredStatements=")||s.includes("<Root"))return ws(s,e||M.dirname(c))}if(n){let o=n.toLowerCase(),u=Vo[o];if(u&&u.length>0)try{return await Ke(c,e,u[0])}catch{}}throw new Error(`Unknown coverage format: ${c}`)}async function mr(c,e){let t=e||c,n=[M.join(c,"coverage","lcov.info"),M.join(c,"coverage","coverage-final.json"),M.join(c,"lcov.info"),M.join(c,".nyc_output","coverage.json"),M.join(c,"target","site","jacoco","jacoco.xml"),M.join(c,"build","reports","jacoco","test","jacocoTestReport.xml"),M.join(c,"dotcover-report.xml"),M.join(c,"tarpaulin-report.json"),M.join(c,"cobertura.xml"),M.join(c,"coverage.out"),M.join(c,"cover.out"),M.join(c,"build","reports","kover","report.xml"),M.join(c,"coverage.json")];for(let r of n)try{return await K.access(r),Ke(r,t)}catch{}return null}function pr(c,e,t,n){let r=e>0?c/e*100:0,i=n>0?t/n*100:0;return n===0?r:r*.7+i*.3}function fe(c){let e=0,t=0,n=0,r=0,i=0,s=0,a=0,o=0;for(let u of c.values())e+=u.lines.total,t+=u.lines.covered,n+=u.branches.total,r+=u.branches.covered,i+=u.functions.total,s+=u.functions.covered,a+=u.statements.total,o+=u.statements.covered;return{totalFiles:c.size,lines:{total:e,covered:t,percentage:e>0?t/e*100:0},branches:{total:n,covered:r,percentage:n>0?r/n*100:0},functions:{total:i,covered:s,percentage:i>0?s/i*100:0},statements:{total:a,covered:o,percentage:a>0?o/a*100:0}}}k();function As(c){let e=0,t=0,n=0,r=0,i=0,s=0,a=0,o=0;for(let u of c)e+=u.lines.total,t+=u.lines.covered,n+=u.branches.total,r+=u.branches.covered,i+=u.functions.total,s+=u.functions.covered,a+=u.statements.total,o+=u.statements.covered;return{line:e>0?t/e*100:0,branch:n>0?r/n*100:0,function:i>0?s/i*100:0,statement:a>0?o/a*100:0,files:c.length}}function ks(c){let e=[];for(let[t,n]of c.files.entries())e.push({path:n.relativePath||t,lines:{covered:n.lines.covered,total:n.lines.total},branches:{covered:n.branches.covered,total:n.branches.total},functions:{covered:n.functions.covered,total:n.functions.total},statements:{covered:n.statements.covered,total:n.statements.total},uncoveredLines:n.lines.uncoveredLines,uncoveredBranches:n.branches.uncoveredBranches.map(r=>r.line)});return e}var Kt=class extends P{config={name:"qe/coverage/analyze",description:"Analyze code coverage using real LCOV/JSON parsing and compare against thresholds. Includes risk scoring and trend analysis.",domain:"coverage-analysis",schema:Qo,streaming:!0,timeout:18e4};analyzerService=null;async getService(e){if(!this.analyzerService){let t=e.memory??await F(),n=await B(e);this.analyzerService=new Gr({memory:t,llmRouter:n})}return this.analyzerService}async execute(e,t){let{target:n=".",coverageFile:r,thresholds:i={lines:80,branches:70,functions:80,statements:80},includeRisk:s=!1,includeRiskScoring:a=!1,dryRun:o=!1,coverageFormat:u,language:l}=e,d=s||a;try{if(this.emitStream(t,{status:"analyzing",message:`Analyzing coverage for ${n}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(this.isDemoMode(t)||o)return this.markAsDemoData(t,"Demo mode explicitly requested"),this.getDemoResult(n,i,d,t);let m=null;if(r)try{m=await Ke(r,n,u,l)}catch(x){return{success:!1,error:`Failed to parse coverage file '${r}': ${T(x)}`}}else m=await mr(n);if(!m||m.files.size===0)return{success:!1,error:`No coverage data found in '${n}'. Run your test suite with coverage enabled (e.g., 'npm test -- --coverage') and ensure coverage reports are generated (lcov.info, coverage-final.json, etc.)`};this.markAsRealData();let p=ks(m),h=await(await this.getService(t)).analyze({coverageData:{files:p,summary:As(p)},threshold:i.lines||80,includeFileDetails:!0});if(!h.success)return{success:!1,error:`Analysis failed: ${h.error?.message||"Unknown error"}`};let f=h.value,v={lines:{covered:m.summary.lines.covered,total:m.summary.lines.total,percentage:Math.round(m.summary.lines.percentage*100)/100},branches:{covered:m.summary.branches.covered,total:m.summary.branches.total,percentage:Math.round(m.summary.branches.percentage*100)/100},functions:{covered:m.summary.functions.covered,total:m.summary.functions.total,percentage:Math.round(m.summary.functions.percentage*100)/100},statements:{covered:m.summary.statements.covered,total:m.summary.statements.total,percentage:Math.round(m.summary.statements.percentage*100)/100}},y=p.map(x=>({file:x.path,lines:Math.round(x.lines.covered/(x.lines.total||1)*100),branches:Math.round(x.branches.covered/(x.branches.total||1)*100),functions:Math.round(x.functions.covered/(x.functions.total||1)*100),uncoveredLines:x.uncoveredLines.slice(0,20)})),C=v.lines.percentage>=(i.lines||0)&&v.branches.percentage>=(i.branches||0)&&v.functions.percentage>=(i.functions||0)&&v.statements.percentage>=(i.statements||0),b;if(d){let x=p.reduce((z,X)=>z+X.uncoveredLines.length,0),O=(v.lines.percentage+v.branches.percentage+v.functions.percentage)/3;b=Math.round((1-O/100+Math.min(x/1e3,.5))*100)/100}let w;f.delta&&(w={direction:f.delta.trend,delta:Math.round((f.delta.line+f.delta.branch+f.delta.function)/3*100)/100,history:[{date:new Date(Date.now()-10080*60*1e3).toISOString().split("T")[0],coverage:v.lines.percentage-(f.delta.line||0)},{date:new Date().toISOString().split("T")[0],coverage:v.lines.percentage}]}),this.emitStream(t,{status:"complete",message:`Coverage analysis complete: ${v.lines.percentage}% lines covered`,progress:100});let E=e.language||m.language,S=m.format;return{success:!0,data:{summary:v,byFile:y,thresholdsPassed:C,riskScore:b,trends:w,language:E,format:S}}}catch(m){return{success:!1,error:`Coverage analysis failed: ${T(m)}`}}}getDemoResult(e,t,n,r){let i={lines:{covered:850,total:1e3,percentage:85},branches:{covered:120,total:150,percentage:80},functions:{covered:90,total:100,percentage:90},statements:{covered:900,total:1050,percentage:85.71}},s=[{file:`${e}/service.ts`,lines:92,branches:85,functions:95,uncoveredLines:[45,67,89]},{file:`${e}/utils.ts`,lines:78,branches:70,functions:85,uncoveredLines:[12,34,56,78,90]},{file:`${e}/handler.ts`,lines:88,branches:82,functions:90,uncoveredLines:[23,45]}],a=i.lines.percentage>=(t.lines||0)&&i.branches.percentage>=(t.branches||0)&&i.functions.percentage>=(t.functions||0)&&i.statements.percentage>=(t.statements||0);return this.emitStream(r,{status:"complete",message:`Coverage analysis complete (sample data): ${i.lines.percentage}% lines covered`,progress:100}),{success:!0,data:{summary:i,byFile:s,thresholdsPassed:a,riskScore:n?.25:void 0,trends:{direction:"improving",delta:2.5,history:[{date:new Date(Date.now()-10080*60*1e3).toISOString().split("T")[0],coverage:82.5},{date:new Date().toISOString().split("T")[0],coverage:85}]}}}}resetInstanceCache(){this.analyzerService=null}},Xt=class extends P{config={name:"qe/coverage/gaps",description:"Find coverage gaps using O(log n) HNSW vector search. Prioritizes by risk, complexity, or ML confidence using real coverage data.",domain:"coverage-analysis",schema:Wo,streaming:!0,timeout:12e4};gapService=null;async getService(e){if(!this.gapService){let t=e.memory??await F(),n=await B(e);this.gapService=new $r({memory:t,llmRouter:n})}return this.gapService}async execute(e,t){let{target:n=".",coverageFile:r,minRisk:i=.3,limit:s=20,prioritization:a="complexity",coverageFormat:o,language:u}=e;try{if(this.emitStream(t,{status:"detecting",message:`Detecting coverage gaps in ${n} (O(log n) search)`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let l=null;if(r)try{l=await Ke(r,n,o,u)}catch(C){return{success:!1,error:`Failed to parse coverage file: ${T(C)}`}}else l=await mr(n);if(this.isDemoMode(t))return this.markAsDemoData(t,"Demo mode explicitly requested"),this.getDemoGapsResult(n,i,s,t);if(!l||l.files.size===0)return r?{success:!1,error:`Coverage file '${r}' contains no usable coverage data (parsed 0 files). Verify the file is a non-empty Istanbul/LCOV/JaCoCo/etc. report.`}:{success:!1,error:`No coverage data found by autodiscovery under target '${n}'. Run your test suite with coverage enabled, or pass coverageFile pointing to an existing report.`};this.markAsRealData();let d=ks(l),m=await this.getService(t),p=a==="change-frequency"?"recent-changes":"risk",g=await m.detectGaps({coverageData:{files:d,summary:As(d)},minCoverage:80,prioritize:p});if(!g.success)return{success:!1,error:`Gap detection failed: ${g.error?.message||"Unknown error"}`};let h=g.value,f=h.gaps.filter(C=>C.riskScore>=i).slice(0,s).map(C=>({file:C.file,lines:C.lines,type:C.branches.length>0?"uncovered-branch":"uncovered-line",severity:C.severity,riskScore:Math.round(C.riskScore*100)/100,reason:C.recommendation})),v=f.slice(0,5).map((C,b)=>({file:C.file.replace(/\.ts$/,".test.ts"),description:`Add tests for ${C.lines.length} uncovered lines in ${C.file}`,estimatedCoverageGain:Math.round(C.lines.length/(h.totalUncoveredLines||1)*100*100)/100,priority:b+1})),y;if(e.includeGhost)try{let b=t.kernel;if(b){let w=await b.getDomainAPIAsync("coverage-analysis");if(w?.analyzeGhostCoverage){let E=await w.analyzeGhostCoverage(d.map(S=>S.path),n);E?.success&&E.value&&(y=(E.value.gaps||[]).map(S=>({category:S.category,severity:S.severity,description:S.description,confidence:S.confidence})))}}}catch{}return this.emitStream(t,{status:"complete",message:`Found ${f.length} coverage gaps (${h.totalUncoveredLines} uncovered lines)`,progress:100}),{success:!0,data:{gaps:f,totalGaps:h.gaps.length,criticalGaps:f.filter(C=>C.severity==="critical").length,suggestedTests:v,...y?{ghostGaps:y}:{}}}}catch(l){return{success:!1,error:`Gap detection failed: ${T(l)}`}}}getDemoGapsResult(e,t,n,r){let s=[{file:`${e}/service.ts`,lines:[45,67,89,102,115],type:"uncovered-line",severity:"high",riskScore:.85,reason:"Core business logic with no test coverage"},{file:`${e}/utils.ts`,lines:[12,34,56],type:"uncovered-branch",severity:"medium",riskScore:.65,reason:"Utility functions missing edge case tests"},{file:`${e}/handler.ts`,lines:[23,45,67,89],type:"uncovered-function",severity:"critical",riskScore:.92,reason:"Error handling paths untested"},{file:`${e}/validator.ts`,lines:[10,20,30],type:"uncovered-line",severity:"low",riskScore:.35,reason:"Simple validation logic"}].filter(o=>o.riskScore>=t).slice(0,n),a=s.slice(0,5).map((o,u)=>({file:o.file.replace(/\.ts$/,".test.ts"),description:`Add tests for ${o.lines.length} uncovered lines in ${o.file}`,estimatedCoverageGain:Math.round(o.lines.length/50*100*100)/100,priority:u+1}));return this.emitStream(r,{status:"complete",message:`Found ${s.length} coverage gaps (sample data)`,progress:100}),{success:!0,data:{gaps:s,totalGaps:s.length,criticalGaps:s.filter(o=>o.severity==="critical").length,suggestedTests:a}}}resetInstanceCache(){this.gapService=null}},Qo={type:"object",properties:{target:{type:"string",description:"Target directory to analyze (searches for coverage files)",default:"."},coverageFile:{type:"string",description:"Path to coverage report file (lcov.info, coverage-final.json, etc.)"},thresholds:{type:"object",description:"Coverage thresholds",properties:{lines:{type:"number",description:"Line coverage threshold"},branches:{type:"number",description:"Branch coverage threshold"},functions:{type:"number",description:"Function coverage threshold"},statements:{type:"number",description:"Statement coverage threshold"}}},includeRisk:{type:"boolean",description:"Include risk score analysis",default:!1},mlPowered:{type:"boolean",description:"Use ML-powered analysis (vector similarity)",default:!1},language:{type:"string",description:"Source language hint (java, csharp, go, rust, kotlin, swift, dart, typescript, python)"},coverageFormat:{type:"string",description:"Coverage format hint",enum:["lcov","json","jacoco","dotcover","tarpaulin","gocover","kover","xcresult"]}}},Wo={type:"object",properties:{target:{type:"string",description:"Target directory to analyze",default:"."},coverageFile:{type:"string",description:"Path to coverage report file"},minRisk:{type:"number",description:"Minimum risk score to include (0-1)",minimum:0,maximum:1,default:.3},limit:{type:"number",description:"Maximum number of gaps to return",minimum:1,maximum:100,default:20},prioritization:{type:"string",description:"Gap prioritization strategy",enum:["complexity","criticality","change-frequency","ml-confidence"],default:"complexity"},includeGhost:{type:"boolean",description:"Include ADR-059 ghost intent coverage analysis (detect untested behavioral intents)",default:!1},language:{type:"string",description:"Source language filter (java, csharp, go, rust, kotlin, swift, dart)"},coverageFormat:{type:"string",description:"Coverage format hint",enum:["lcov","json","jacoco","dotcover","tarpaulin","gocover","kover","xcresult"]}}};k();var Yt=class extends P{config={name:"qe/quality/evaluate",description:"Evaluate quality gates and provide deployment recommendations. Analyzes coverage, bugs, complexity, and security.",domain:"quality-assessment",schema:Ko,streaming:!0,timeout:12e4};async execute(e,t){let{metrics:n=Xo(),gateName:r="default",thresholds:i=Yo(),includeAdvice:s=!0,riskTolerance:a="medium"}=e;try{if(this.emitStream(t,{status:"evaluating",message:`Evaluating quality gate: ${r}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let o=[];i.coverage&&n.coverage!==void 0&&o.push({name:"Coverage",passed:n.coverage>=i.coverage.min,value:n.coverage,threshold:i.coverage.min,severity:"high",message:n.coverage>=i.coverage.min?`Coverage ${n.coverage}% meets threshold`:`Coverage ${n.coverage}% below ${i.coverage.min}% threshold`}),i.testsPassing&&n.testsPassing!==void 0&&o.push({name:"Tests Passing",passed:n.testsPassing>=i.testsPassing.min,value:n.testsPassing,threshold:i.testsPassing.min,severity:"critical",message:n.testsPassing>=i.testsPassing.min?`${n.testsPassing}% tests passing`:`Only ${n.testsPassing}% tests passing`}),i.criticalBugs&&n.criticalBugs!==void 0&&o.push({name:"Critical Bugs",passed:n.criticalBugs<=i.criticalBugs.max,value:n.criticalBugs,threshold:i.criticalBugs.max,severity:"critical",message:n.criticalBugs<=i.criticalBugs.max?`${n.criticalBugs} critical bugs within threshold`:`${n.criticalBugs} critical bugs exceed threshold of ${i.criticalBugs.max}`}),i.securityVulnerabilities&&n.securityVulnerabilities!==void 0&&o.push({name:"Security Vulnerabilities",passed:n.securityVulnerabilities<=i.securityVulnerabilities.max,value:n.securityVulnerabilities,threshold:i.securityVulnerabilities.max,severity:"critical",message:n.securityVulnerabilities<=i.securityVulnerabilities.max?`${n.securityVulnerabilities} vulnerabilities within threshold`:`${n.securityVulnerabilities} vulnerabilities found`}),i.codeSmells&&n.codeSmells!==void 0&&o.push({name:"Code Smells",passed:n.codeSmells<=i.codeSmells.max,value:n.codeSmells,threshold:i.codeSmells.max,severity:"medium",message:n.codeSmells<=i.codeSmells.max?`${n.codeSmells} code smells within threshold`:`${n.codeSmells} code smells detected`});let u=o.filter(f=>f.passed).length,l=o.length,d=l>0?Math.round(u/l*100):100,m=Jo(d,o),p=o.every(f=>f.passed||f.severity!=="critical"),g=s?Zo(p,d,o,a):void 0,h=ec(o,n);return this.emitStream(t,{status:"complete",message:`Quality evaluation complete: ${m} (${d}%)`,progress:100}),{success:!0,data:{passed:p,score:d,grade:m,checks:o,deploymentAdvice:g,recommendations:h}}}catch(o){return{success:!1,error:`Quality evaluation failed: ${T(o)}`}}}},Ko={type:"object",properties:{metrics:{type:"object",description:"Quality metrics to evaluate",properties:{coverage:{type:"number",description:"Code coverage percentage"},testsPassing:{type:"number",description:"Percentage of passing tests"},criticalBugs:{type:"number",description:"Number of critical bugs"},codeSmells:{type:"number",description:"Number of code smells"},securityVulnerabilities:{type:"number",description:"Number of security vulnerabilities"},technicalDebt:{type:"number",description:"Technical debt in hours"},duplications:{type:"number",description:"Code duplication percentage"},complexity:{type:"number",description:"Cyclomatic complexity"}}},gateName:{type:"string",description:"Name of the quality gate",default:"default"},thresholds:{type:"object",description:"Quality gate thresholds"},includeAdvice:{type:"boolean",description:"Include deployment advice",default:!0},riskTolerance:{type:"string",description:"Risk tolerance level",enum:["low","medium","high"],default:"medium"}}};function Xo(){return{coverage:80,testsPassing:95,criticalBugs:0,codeSmells:15,securityVulnerabilities:0,technicalDebt:4,duplications:3,complexity:8}}function Yo(){return{coverage:{min:80},testsPassing:{min:95},criticalBugs:{max:0},securityVulnerabilities:{max:0},codeSmells:{max:50},technicalDebt:{max:8}}}function Jo(c,e){return e.some(n=>!n.passed&&n.severity==="critical")?"F":c>=90?"A":c>=80?"B":c>=70?"C":c>=60?"D":"F"}function Zo(c,e,t,n){let r=t.filter(d=>!d.passed&&d.severity==="critical"),i=t.filter(d=>!d.passed&&d.severity==="high"),s=r.length*.4+i.length*.2+(100-e)/100,a=Math.min(s,1),o,l={low:{block:.2,warn:.1},medium:{block:.4,warn:.2},high:{block:.6,warn:.4}}[n];return a>=l.block||r.length>0?o="blocked":a>=l.warn?o="warning":o="approved",{decision:o,confidence:Math.round((1-a)*100)/100,riskScore:Math.round(a*100)/100,reasons:[...r.map(d=>`Critical: ${d.name} - ${d.message}`),...i.map(d=>`High: ${d.name} - ${d.message}`)],conditions:o==="warning"?["Monitor closely after deployment","Prepare rollback plan"]:void 0,rollbackPlan:o!=="approved"?"Revert to previous version if issues detected":void 0}}function ec(c,e){let t=[],n=c.filter(r=>!r.passed);for(let r of n)t.push({type:r.severity==="critical"?"critical":r.severity==="high"?"warning":"improvement",title:`Fix ${r.name}`,description:r.message,impact:r.severity==="critical"||r.severity==="high"?"high":"medium",effort:"medium"});return(e.coverage||0)<90&&t.push({type:"improvement",title:"Increase test coverage",description:`Current coverage is ${e.coverage}%. Consider adding tests for critical paths.`,impact:"medium",effort:"medium"}),t}k();var Jt={codeComplexity:"High cyclomatic complexity increases defect probability",changeFrequency:"Frequently modified files are more prone to defects",bugHistory:"Previous defects in this area indicate higher risk",testCoverage:"Low test coverage increases undetected defect risk",developerExperience:"Code written by less experienced developers may have more issues",codeAge:"New code is more likely to have defects than mature, stable code",complexity:"High cyclomatic complexity increases defect probability",churn:"Frequently modified files are more prone to defects",history:"Previous defects in this area indicate higher risk",coverage:"Low test coverage increases undetected defect risk",coupling:"High coupling makes changes risky",age:"New code may have more defects than stable code"},Zt=class extends P{config={name:"qe/defects/predict",description:"Predict defect probability for files using ML models. Analyzes code complexity, change frequency, git history, and test coverage.",domain:"defect-intelligence",schema:tc,streaming:!0,timeout:18e4};predictorService=null;async getService(e){if(!this.predictorService){let t=e.memory??await F(),n=await B(e);this.predictorService=new zr({memory:t,llmRouter:n})}return this.predictorService}async execute(e,t){let{files:n=[],threshold:r=.5,minConfidence:i=.7,features:s=[{name:"codeComplexity",weight:.25},{name:"changeFrequency",weight:.2},{name:"developerExperience",weight:.15},{name:"testCoverage",weight:.2},{name:"codeAge",weight:.1},{name:"bugHistory",weight:.1}]}=e;try{if(this.emitStream(t,{status:"analyzing",message:`Analyzing ${n.length||"provided"} files using ML-based prediction`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(this.isDemoMode(t))return this.markAsDemoData(t,"Demo mode explicitly requested"),this.getDemoResult(n);let a=await this.getService(t),o=await a.predictDefects({files:n,features:s.map(g=>({name:g.name,weight:g.weight??.25})),threshold:r});if(!o.success)return{success:!1,error:`Defect prediction failed: ${o.error?.message||"Service unavailable"}. Ensure the defect-intelligence domain is properly initialized.`};this.markAsRealData();let d=o.value.predictions.filter(g=>g.probability>=1-i).map(g=>({file:g.file,probability:Math.round(g.probability*100)/100,riskLevel:nc(g.riskLevel),factors:g.factors.map(h=>({name:h.name,contribution:h.contribution,description:Jt[h.name]||`${h.name} contributes to defect risk`})),recommendations:g.recommendations}));d.sort((g,h)=>h.probability-g.probability);let m=rc(d),p=await a.getModelMetrics();return this.emitStream(t,{status:"complete",message:`Analyzed ${n.length} files, ${d.length} with elevated risk`,progress:100}),{success:!0,data:{predictions:d,modelConfidence:o.value.modelConfidence,topRiskFactors:m,recommendations:sc(d),modelMetrics:{accuracy:p.accuracy,precision:p.precision,recall:p.recall,f1Score:p.f1Score}}}}catch(a){return{success:!1,error:`Defect prediction failed: ${T(a)}`}}}getDemoResult(e){let n=(e.length>0?e:["src/service.ts","src/handler.ts","src/utils.ts"]).map((r,i)=>({file:r,probability:Math.max(.9-i*.15,.35),riskLevel:i===0?"high":i===1?"medium":"low",factors:[{name:"codeComplexity",contribution:.35,description:Jt.codeComplexity},{name:"changeFrequency",contribution:.25,description:Jt.changeFrequency},{name:"testCoverage",contribution:.2,description:Jt.testCoverage}],recommendations:[`Increase test coverage for ${r}`,"Consider refactoring complex functions","Review recent changes for potential issues"]}));return{success:!0,data:{predictions:n,modelConfidence:.85,topRiskFactors:[{name:"High Complexity",impact:.35,affectedFiles:n.length},{name:"Frequent Changes",impact:.25,affectedFiles:Math.ceil(n.length*.7)},{name:"Low Coverage",impact:.2,affectedFiles:Math.ceil(n.length*.5)}],recommendations:["Focus testing on files with highest defect probability","Increase test coverage in high-risk areas","Review recent changes to frequently-modified files","Consider refactoring complex modules"],modelMetrics:{accuracy:.82,precision:.78,recall:.85,f1Score:.81}}}}resetInstanceCache(){this.predictorService=null}},tc={type:"object",properties:{files:{type:"array",description:"Specific files to analyze",items:{type:"string",description:"File path"}},target:{type:"string",description:"Target directory to analyze",default:"."},lookback:{type:"number",description:"Days of history to consider",minimum:7,maximum:365,default:30},threshold:{type:"number",description:"Risk threshold for classification (0-1)",minimum:0,maximum:1,default:.5},minConfidence:{type:"number",description:"Minimum prediction confidence (0-1)",minimum:0,maximum:1,default:.7},features:{type:"array",description:"Features to use for prediction",items:{type:"object",description:"Prediction feature",properties:{name:{type:"string",description:"Feature name"},weight:{type:"number",description:"Feature weight"}}}}}};function nc(c){switch(c){case"critical":return"critical";case"high":return"high";case"medium":return"medium";default:return"low"}}function rc(c){let e=new Map;for(let n of c)for(let r of n.factors){let i=e.get(r.name)||{impact:0,count:0};i.impact+=r.contribution,i.count+=1,e.set(r.name,i)}let t=[];for(let[n,r]of e)t.push({name:ic(n),impact:Math.round(r.impact/r.count*100)/100,affectedFiles:r.count});return t.sort((n,r)=>r.impact-n.impact),t.slice(0,5)}function ic(c){return{codeComplexity:"High Complexity",changeFrequency:"Frequent Changes",bugHistory:"Bug History",testCoverage:"Low Coverage",developerExperience:"Developer Experience",codeAge:"Code Age"}[c]||c.replace(/([A-Z])/g," $1").trim()}function sc(c){let e=[],t=c.filter(i=>i.riskLevel==="critical").length,n=c.filter(i=>i.riskLevel==="high").length,r=c.length>0?c.reduce((i,s)=>i+s.probability,0)/c.length:0;return t>0&&(e.push(`CRITICAL: ${t} files require immediate attention`),e.push("Consider code review and comprehensive testing before deployment")),n>0&&(e.push(`High risk detected in ${n} files`),e.push("Increase test coverage in high-risk areas")),r>.5?(e.push("Overall defect risk is elevated - consider delaying release"),e.push("Run full regression test suite before deployment")):e.push("Focus testing on files with highest defect probability"),e.push("Review recent changes to frequently-modified files"),e.push("Consider refactoring complex modules"),[...new Set(e)]}k();var en=class extends P{config={name:"qe/requirements/validate",description:"Validate requirements for testability. Scores each requirement, detects ambiguity, and optionally generates BDD scenarios.",domain:"requirements-validation",schema:ac,streaming:!0,timeout:12e4};async execute(e,t){let{requirements:n,generateBDD:r=!1,checkAmbiguity:i=!0,minTestability:s=60}=e;try{if(this.emitStream(t,{status:"validating",message:`Validating ${n.length} requirements`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let a=[],o=[];for(let l of n){this.emitStream(t,{status:"processing",message:`Analyzing: ${l.title}`});let d=oc(l),m=cc(l,s,d),p=i?lc(l):void 0;a.push({requirementId:l.id,isValid:m.filter(g=>g.severity==="error").length===0,testabilityScore:d,errors:m,ambiguityReport:p}),r&&d.value>=s&&o.push(...dc(l))}let u={total:n.length,valid:a.filter(l=>l.isValid).length,invalid:a.filter(l=>!l.isValid).length,avgTestability:a.reduce((l,d)=>l+d.testabilityScore.value,0)/n.length,blockers:a.filter(l=>l.errors.some(d=>d.severity==="error")).length};return this.emitStream(t,{status:"complete",message:`Validation complete: ${u.valid}/${u.total} valid`,progress:100}),{success:!0,data:{validationResults:a,summary:u,bddScenarios:o.length>0?o:void 0,recommendations:mc(a)}}}catch(a){return{success:!1,error:`Validation failed: ${T(a)}`}}}},ac={type:"object",properties:{requirements:{type:"array",description:"Requirements to validate",items:{type:"object",description:"Requirement input",properties:{id:{type:"string",description:"Requirement ID"},title:{type:"string",description:"Requirement title"},description:{type:"string",description:"Requirement description"},acceptanceCriteria:{type:"array",description:"Acceptance criteria",items:{type:"string",description:"Criterion"}},type:{type:"string",description:"Requirement type",enum:["user-story","functional","non-functional","technical"]}},required:["id","title","description"]}},generateBDD:{type:"boolean",description:"Generate BDD scenarios from requirements",default:!1},checkAmbiguity:{type:"boolean",description:"Check for ambiguous language",default:!0},minTestability:{type:"number",description:"Minimum testability score (0-100)",minimum:0,maximum:100,default:60}},required:["requirements"]};function oc(c){let e=[],t=c.acceptanceCriteria&&c.acceptanceCriteria.length>0?90:40;e.push({name:"Acceptance Criteria",score:t,issues:t<70?["Missing or incomplete acceptance criteria"]:[]});let n=c.description.length,r=n>100?85:n>50?70:50;e.push({name:"Description Clarity",score:r,issues:r<70?["Description may be too brief"]:[]});let a=["should","must","when","then","verify","validate"].some(u=>c.description.toLowerCase().includes(u))?80:50;e.push({name:"Measurability",score:a,issues:a<70?["Requirement lacks measurable criteria"]:[]});let o=Math.round(e.reduce((u,l)=>u+l.score,0)/e.length);return{value:o,category:o>=80?"excellent":o>=70?"good":o>=50?"fair":"poor",factors:e}}function cc(c,e,t){let n=[];return t.value<e&&n.push({code:"LOW_TESTABILITY",message:`Testability score ${t.value} is below minimum ${e}`,severity:"error",suggestion:"Add clear acceptance criteria and measurable outcomes"}),(!c.acceptanceCriteria||c.acceptanceCriteria.length===0)&&n.push({code:"MISSING_AC",message:"No acceptance criteria defined",severity:"warning",suggestion:"Define specific, testable acceptance criteria"}),c.description.length<30&&n.push({code:"BRIEF_DESC",message:"Description is too brief",severity:"warning",suggestion:"Expand description with more context and details"}),n}function lc(c){let e=[],t=["some","few","many","fast","slow","good","better","appropriate"];for(let n of t)c.description.toLowerCase().includes(n)&&e.push({term:n,context:`Found in: "${c.description.substring(0,50)}..."`,alternatives:uc(n)});return{ambiguousTerms:e,overallScore:Math.max(0,100-e.length*15),suggestions:e.length>0?["Replace vague terms with specific, measurable criteria"]:["Requirement language is clear"]}}function uc(c){return{some:["exactly N","at least N","between N and M"],few:["1-3","less than 5"],many:["more than 10","at least N"],fast:["within X milliseconds","response time < Xs"],slow:["longer than X seconds"],good:["score >= 80%","passes all criteria"],better:["improves by X%","exceeds baseline by N"],appropriate:["meets requirement X","validates against schema"]}[c]||["Be more specific"]}function dc(c){let e=[];return e.push({id:`scenario-${c.id}-1`,feature:c.title,scenario:`Verify ${c.title}`,given:["the system is initialized","the user is authenticated"],when:["the user performs the action"],then:["the expected outcome is observed","the system state is updated"],tags:["@generated",`@${c.type||"functional"}`]}),c.acceptanceCriteria&&c.acceptanceCriteria.length>0&&c.acceptanceCriteria.forEach((t,n)=>{e.push({id:`scenario-${c.id}-ac${n+1}`,feature:c.title,scenario:`Acceptance Criteria: ${t.substring(0,50)}`,given:["the preconditions are met"],when:["the specified action is taken"],then:[t],tags:["@generated","@acceptance"]})}),e}function mc(c){let e=[],t=c.filter(r=>r.testabilityScore.value<60).length,n=c.filter(r=>r.errors.some(i=>i.code==="MISSING_AC")).length;return t>0&&e.push(`${t} requirements have low testability scores. Consider adding acceptance criteria.`),n>0&&e.push(`${n} requirements lack acceptance criteria. Define testable criteria for each.`),c.every(r=>r.isValid)&&e.push("All requirements are valid and testable."),e}import{existsSync as gr,readFileSync as Ms}from"fs";import{join as hr,dirname as pc}from"path";import{fileURLToPath as gc}from"url";var _e=["Capability","Reliability","Usability","Charisma","Security","Scalability","Compatibility","Performance","Installability","Development"],Fe=["Capability","Reliability","Security","Performance","Development"];var hc=gc(import.meta.url),fc=pc(hc),Xe=class{config;templateCache=null;constructor(e={}){this.config={enableSemanticAnalysis:e.enableSemanticAnalysis??!0,defaultOutputFormat:e.defaultOutputFormat??"html",templatePath:e.templatePath??this.findTemplatePath(),minimumCategories:e.minimumCategories??8}}findTemplatePath(){let e=[hr(process.cwd(),".claude/helpers/v3/quality-criteria/quality-criteria-reference-template.html"),hr(process.cwd(),"node_modules/agentic-qe/assets/agents/v3/helpers/quality-criteria/quality-criteria-reference-template.html"),hr(fc,"../../../../../assets/agents/v3/helpers/quality-criteria/quality-criteria-reference-template.html")];for(let t of e)if(gr(t))return t;return e[0]}analyze(e){let t=e.epicContent||"";if(e.epicPath&&gr(e.epicPath)&&(t=Ms(e.epicPath,"utf-8")),!t&&!e.epicPath)throw new Error("Either epicPath or epicContent is required for analysis");return{agentInvocation:{required:!0,agentType:"qe-quality-criteria-recommender",prompt:this.buildAgentPrompt({assessmentName:e.assessmentName,epicContent:t,epicPath:e.epicPath,sourcePaths:e.sourcePaths,outputFormat:e.outputFormat,outputPath:e.outputPath}),timeout:3e5,expectedOutput:"QualityCriteriaAnalysis",instructions:`Claude Code MUST spawn the qe-quality-criteria-recommender agent with this prompt. The agent will perform real semantic HTSM analysis using Claude's reasoning capabilities. Use: Task("HTSM Quality Criteria Analysis", { prompt: <this prompt> }, "qe-quality-criteria-recommender")`},message:"AGENT INVOCATION REQUIRED: This service cannot perform semantic HTSM analysis alone. Claude Code must spawn the qe-quality-criteria-recommender agent with the provided prompt."}}buildAgentPrompt(e){let{assessmentName:t,epicContent:n,epicPath:r,sourcePaths:i,outputFormat:s,outputPath:a}=e,o=i&&i.length>0?`
427
427
  ## Source Paths to Analyze
428
428
  ${i.map(l=>`- ${l}`).join(`
429
429
  `)}
@@ -496,7 +496,7 @@ Return a complete QualityCriteriaAnalysis object with:
496
496
  ${u}
497
497
  ## Begin Analysis
498
498
 
499
- Analyze the requirements above and return the complete QualityCriteriaAnalysis.`}validateEvidence(e){let t=[];for(let n of e)this.isValidSourceReference(n.sourceReference)||t.push(`Invalid source reference format: ${n.sourceReference}. Expected file:line format.`),["Direct","Inferred","Claimed"].includes(n.type)||t.push(`Invalid evidence type: ${n.type}. Must be Direct, Inferred, or Claimed.`),n.type==="Claimed"&&(!n.reasoning.includes("requires verification")&&!n.reasoning.includes("needs inspection")&&!n.reasoning.includes("needs code inspection")&&t.push(`Claimed evidence must state "requires verification": ${n.sourceReference}`),(n.reasoning.includes("could")||n.reasoning.includes("might"))&&t.push(`Claimed evidence must not speculate (no "could" or "might"): ${n.sourceReference}`)),n.reasoning.length<20&&t.push(`Reasoning too short for ${n.sourceReference}. Explain WHY it matters.`);return{valid:t.length===0,errors:t}}isValidSourceReference(e){if(e==="N/A (verified via Glob/Grep search)"||e==="Project search")return!0;let t=/^[\w\-./]+\.(ts|js|tsx|jsx|md|json|html|css|yaml|yml):\d+-\d+$/,n=/^[\w\-./]+\.(ts|js|tsx|jsx|md|json|html|css|yaml|yml)(\s*\(\d+\s*LOC\))?$/;return t.test(e)||n.test(e)}extractComponent(e){let t=e.match(/component:\s*["']?([^"'\n]+)["']?/i);if(t)return t[1].trim();let n=e.match(/^#\s+(.+)$/m);if(n)return n[1].trim()}generateHTML(e){if(!this.templateCache&&mr(this.config.templatePath)&&(this.templateCache=ws(this.config.templatePath,"utf-8")),!this.templateCache)return this.generateFallbackHTML(e);let t=this.templateCache;return t=t.replace(/\{EPIC_TITLE\}/g,e.epic),t=t.replace(/\{COMPONENT_NAME\}/g,e.component||"N/A"),t=t.replace(/\{DATE\}/g,e.timestamp.toISOString().split("T")[0]),t=t.replace(/\{COVERAGE_METRIC\}/g,e.coverageMetric),t}generateFallbackHTML(e){return`<!DOCTYPE html>
499
+ Analyze the requirements above and return the complete QualityCriteriaAnalysis.`}validateEvidence(e){let t=[];for(let n of e)this.isValidSourceReference(n.sourceReference)||t.push(`Invalid source reference format: ${n.sourceReference}. Expected file:line format.`),["Direct","Inferred","Claimed"].includes(n.type)||t.push(`Invalid evidence type: ${n.type}. Must be Direct, Inferred, or Claimed.`),n.type==="Claimed"&&(!n.reasoning.includes("requires verification")&&!n.reasoning.includes("needs inspection")&&!n.reasoning.includes("needs code inspection")&&t.push(`Claimed evidence must state "requires verification": ${n.sourceReference}`),(n.reasoning.includes("could")||n.reasoning.includes("might"))&&t.push(`Claimed evidence must not speculate (no "could" or "might"): ${n.sourceReference}`)),n.reasoning.length<20&&t.push(`Reasoning too short for ${n.sourceReference}. Explain WHY it matters.`);return{valid:t.length===0,errors:t}}isValidSourceReference(e){if(e==="N/A (verified via Glob/Grep search)"||e==="Project search")return!0;let t=/^[\w\-./]+\.(ts|js|tsx|jsx|md|json|html|css|yaml|yml):\d+-\d+$/,n=/^[\w\-./]+\.(ts|js|tsx|jsx|md|json|html|css|yaml|yml)(\s*\(\d+\s*LOC\))?$/;return t.test(e)||n.test(e)}extractComponent(e){let t=e.match(/component:\s*["']?([^"'\n]+)["']?/i);if(t)return t[1].trim();let n=e.match(/^#\s+(.+)$/m);if(n)return n[1].trim()}generateHTML(e){if(!this.templateCache&&gr(this.config.templatePath)&&(this.templateCache=Ms(this.config.templatePath,"utf-8")),!this.templateCache)return this.generateFallbackHTML(e);let t=this.templateCache;return t=t.replace(/\{EPIC_TITLE\}/g,e.epic),t=t.replace(/\{COMPONENT_NAME\}/g,e.component||"N/A"),t=t.replace(/\{DATE\}/g,e.timestamp.toISOString().split("T")[0]),t=t.replace(/\{COVERAGE_METRIC\}/g,e.coverageMetric),t}generateFallbackHTML(e){return`<!DOCTYPE html>
500
500
  <html lang="en">
501
501
  <head>
502
502
  <meta charset="UTF-8">
@@ -530,7 +530,7 @@ Analyze the requirements above and return the complete QualityCriteriaAnalysis.`
530
530
  </footer>
531
531
  </body>
532
532
  </html>`}generateMarkdown(e){let t=["# Quality Criteria Recommendations","",`**Epic:** ${e.epic}`,`**Component:** ${e.component||"N/A"}`,`**Date:** ${e.timestamp.toISOString().split("T")[0]}`,`**Coverage:** ${e.coverageMetric}`,"","## Executive Summary","",e.executiveSummary||"_Analysis pending. Run qe-quality-criteria-recommender agent for full semantic analysis._","","## Categories Analyzed","",...e.categoriesAnalyzed.map(n=>`- ${n}`),""];if(e.categoriesOmitted.length>0){t.push("## Categories Omitted"),t.push("");for(let n of e.categoriesOmitted)t.push(`- **${n.category}**: ${n.reason}`);t.push("")}if(e.recommendations.length>0){t.push("## Recommendations"),t.push("");for(let n of e.recommendations){t.push(`### ${n.category} (${n.priority})`),t.push(""),t.push(`**Why It Matters:** ${n.whyItMatters}`),t.push(""),t.push(`**Business Impact:** ${n.businessImpact}`),t.push(""),t.push("**Test Focus Areas:**");for(let r of n.testFocusAreas)t.push(`- ${r}`);t.push("")}}return t.push("---"),t.push(""),t.push("*Generated by Agentic QE \u2014 qe-quality-criteria-recommender*"),t.push("*Analysis Method: AI Semantic Understanding | Framework: James Bach's HTSM v6.3*"),t.join(`
533
- `)}};function en(c){return new Xe(c)}M();M();import{existsSync as mc,readFileSync as pc}from"fs";var Ye=class extends x{config={name:"qe/requirements/quality-criteria",description:'HTSM v6.3 Quality Criteria analysis tool. For "analyze" action: Returns an agentInvocation that MUST be executed to get real semantic analysis. For "validate-evidence": Validates evidence points programmatically. For "format": Formats a completed analysis into HTML/JSON/Markdown.',domain:"requirements-validation",schema:gc,streaming:!0,timeout:12e4};service=null;getService(){return this.service||(this.service=en()),this.service}async execute(e,t){let{assessmentName:n,epicPath:r,epicContent:i,sourcePaths:s,outputFormat:a="html",outputPath:o,evidencePoints:u,completedAnalysis:l,action:d="analyze"}=e;try{let m=this.getService();if(this.emitStream(t,{status:"starting",message:`Quality Criteria: ${d} - ${n}`,action:d}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(d==="validate-evidence"){if(!u||u.length===0)return{success:!1,error:"validate-evidence action requires evidencePoints array"};this.emitStream(t,{status:"validating",message:`Validating ${u.length} evidence points`});let f=m.validateEvidence(u);return{success:!0,data:{evidenceValidation:f,message:f.valid?`All ${u.length} evidence points are valid`:`Validation failed with ${f.errors.length} errors`}}}if(d==="format"){if(!l)return{success:!1,error:"format action requires completedAnalysis object"};this.emitStream(t,{status:"formatting",message:`Formatting analysis as ${a}`});let f,v,y;switch(a){case"html":f=m.generateHTML(l);break;case"json":v=JSON.stringify(l,null,2);break;case"markdown":y=m.generateMarkdown(l);break}return{success:!0,data:{html:f,json:v,markdown:y,message:`Analysis formatted as ${a}`}}}this.emitStream(t,{status:"preparing",message:"Preparing agent invocation for semantic HTSM analysis"});let p=i||"";if(r&&mc(r)&&(p=pc(r,"utf-8")),!p&&!r)return{success:!1,error:"Either epicPath or epicContent is required for analysis"};let h={required:!0,agentType:"qe-quality-criteria-recommender",prompt:this.buildAgentPrompt({assessmentName:n,epicContent:p,epicPath:r,sourcePaths:s,outputFormat:a,outputPath:o}),timeout:3e5,expectedOutput:"QualityCriteriaAnalysis",instructions:`Claude Code MUST spawn the qe-quality-criteria-recommender agent with this prompt. The agent will perform real semantic HTSM analysis using Claude's reasoning capabilities. Use: Task("HTSM Quality Criteria Analysis", { prompt: <this prompt> }, "qe-quality-criteria-recommender")`};return this.emitStream(t,{status:"agent-required",message:"Agent invocation prepared. Claude Code must spawn qe-quality-criteria-recommender agent.",agentType:"qe-quality-criteria-recommender"}),{success:!0,data:{agentInvocation:h,message:"AGENT INVOCATION REQUIRED: This tool cannot perform semantic HTSM analysis alone. Claude Code must spawn the qe-quality-criteria-recommender agent with the provided prompt."}}}catch(m){return{success:!1,error:`Quality Criteria tool failed: ${E(m)}`}}}buildAgentPrompt(e){let{assessmentName:t,epicContent:n,epicPath:r,sourcePaths:i,outputFormat:s,outputPath:a}=e,o=i&&i.length>0?`
533
+ `)}};function tn(c){return new Xe(c)}k();k();import{existsSync as vc,readFileSync as bc}from"fs";var Ye=class extends P{config={name:"qe/requirements/quality-criteria",description:'HTSM v6.3 Quality Criteria analysis tool. For "analyze" action: Returns an agentInvocation that MUST be executed to get real semantic analysis. For "validate-evidence": Validates evidence points programmatically. For "format": Formats a completed analysis into HTML/JSON/Markdown.',domain:"requirements-validation",schema:Cc,streaming:!0,timeout:12e4};service=null;getService(){return this.service||(this.service=tn()),this.service}async execute(e,t){let{assessmentName:n,epicPath:r,epicContent:i,sourcePaths:s,outputFormat:a="html",outputPath:o,evidencePoints:u,completedAnalysis:l,action:d="analyze"}=e;try{let m=this.getService();if(this.emitStream(t,{status:"starting",message:`Quality Criteria: ${d} - ${n}`,action:d}),this.isAborted(t))return{success:!1,error:"Operation aborted"};if(d==="validate-evidence"){if(!u||u.length===0)return{success:!1,error:"validate-evidence action requires evidencePoints array"};this.emitStream(t,{status:"validating",message:`Validating ${u.length} evidence points`});let f=m.validateEvidence(u);return{success:!0,data:{evidenceValidation:f,message:f.valid?`All ${u.length} evidence points are valid`:`Validation failed with ${f.errors.length} errors`}}}if(d==="format"){if(!l)return{success:!1,error:"format action requires completedAnalysis object"};this.emitStream(t,{status:"formatting",message:`Formatting analysis as ${a}`});let f,v,y;switch(a){case"html":f=m.generateHTML(l);break;case"json":v=JSON.stringify(l,null,2);break;case"markdown":y=m.generateMarkdown(l);break}return{success:!0,data:{html:f,json:v,markdown:y,message:`Analysis formatted as ${a}`}}}this.emitStream(t,{status:"preparing",message:"Preparing agent invocation for semantic HTSM analysis"});let p=i||"";if(r&&vc(r)&&(p=bc(r,"utf-8")),!p&&!r)return{success:!1,error:"Either epicPath or epicContent is required for analysis"};let h={required:!0,agentType:"qe-quality-criteria-recommender",prompt:this.buildAgentPrompt({assessmentName:n,epicContent:p,epicPath:r,sourcePaths:s,outputFormat:a,outputPath:o}),timeout:3e5,expectedOutput:"QualityCriteriaAnalysis",instructions:`Claude Code MUST spawn the qe-quality-criteria-recommender agent with this prompt. The agent will perform real semantic HTSM analysis using Claude's reasoning capabilities. Use: Task("HTSM Quality Criteria Analysis", { prompt: <this prompt> }, "qe-quality-criteria-recommender")`};return this.emitStream(t,{status:"agent-required",message:"Agent invocation prepared. Claude Code must spawn qe-quality-criteria-recommender agent.",agentType:"qe-quality-criteria-recommender"}),{success:!0,data:{agentInvocation:h,message:"AGENT INVOCATION REQUIRED: This tool cannot perform semantic HTSM analysis alone. Claude Code must spawn the qe-quality-criteria-recommender agent with the provided prompt."}}}catch(m){return{success:!1,error:`Quality Criteria tool failed: ${T(m)}`}}}buildAgentPrompt(e){let{assessmentName:t,epicContent:n,epicPath:r,sourcePaths:i,outputFormat:s,outputPath:a}=e,o=i&&i.length>0?`
534
534
  ## Source Paths to Analyze
535
535
  ${i.map(l=>`- ${l}`).join(`
536
536
  `)}
@@ -604,16 +604,16 @@ Return a complete QualityCriteriaAnalysis object with:
604
604
  ${u}
605
605
  ## Begin Analysis
606
606
 
607
- Analyze the requirements above and return the complete QualityCriteriaAnalysis.`}resetInstanceCache(){this.service=null}},gc={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"]},mf=new Ye;M();import*as gr from"fs";import*as pe from"path";var tn=class extends x{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:hc,streaming:!0,timeout:3e5};knowledgeGraph=null;semanticAnalyzer=null;impactAnalyzer=null;async getKnowledgeGraph(e){if(!this.knowledgeGraph){let t=e.memory??await L(),n=await B(e);this.knowledgeGraph=new qr({memory:t,llmRouter:n})}return this.knowledgeGraph}async getSemanticAnalyzer(e){if(!this.semanticAnalyzer){let t=e.memory;this.semanticAnalyzer=new Gr(t||await L())}return this.semanticAnalyzer}async getImpactAnalyzer(e){if(!this.impactAnalyzer){let t=e.memory,n=await this.getKnowledgeGraph(e);this.impactAnalyzer=new $r(t||await L(),n)}return this.impactAnalyzer}async execute(e,t){let{action:n,paths:r=["."],query:i,changedFiles:s=[],depth:a=3,incremental:o=!1}=e;try{if(this.emitStream(t,{status:"processing",message:`Executing ${n} action`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let u={action:n};switch(n){case"index":u.indexResult=await this.executeIndex(r,o,t);break;case"search":if(!i)return{success:!1,error:"Query is required for search action"};u.searchResult=await this.executeSearch(i,r,t);break;case"impact":if(s.length===0)return{success:!1,error:"changedFiles is required for impact action"};u.impactResult=await this.executeImpact(s,a,t);break;case"dependencies":u.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:u}}catch(u){return{success:!1,error:`Code analysis failed: ${E(u)}`}}}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 u=Date.now()-r;return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoSearchResult(e,u)}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(u=>({file:u.file,line:u.line,snippet:u.snippet.substring(0,200)+(u.snippet.length>200?"...":""),score:u.score,highlights:fc(u.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,o=a.nodes.map(l=>({id:l.id,path:l.path,type:l.type,inDegree:l.inDegree,outDegree:l.outDegree})),u=a.edges.map(l=>({source:l.source,target:l.target,type:l.type}));return{nodes:o,edges:u,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 gr.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){let t=[],n=[".ts",".tsx",".js",".jsx"],r=["node_modules",".git","dist","build","coverage"];try{let i=await gr.promises.readdir(e,{withFileTypes:!0});for(let s of i){let a=pe.join(e,s.name);if(s.isDirectory()){if(!r.includes(s.name)){let o=await this.findSourceFiles(a);t.push(...o)}}else if(s.isFile()){let o=pe.extname(s.name);n.includes(o)&&t.push(a)}}}catch{}return t}},hc={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 fc(c,e){let t=[],n=e.toLowerCase().split(/\s+/),r=c.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),o=Math.min(c.length,s+i.length+20),u=c.substring(a,o);if(t.includes(u)||t.push(u),s+=i.length,t.length>=3)break}if(t.length>=3)break}return t}M();H();var Rs=[{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"}],nn=class extends x{config={name:"qe/security/scan",description:"Comprehensive security scanning including SAST, DAST, dependency analysis, and compliance validation.",domain:"security-compliance",schema:yc,streaming:!0,timeout:6e5};async execute(e,t){let{target:n=".",scanType:r=["sast","dependency"],compliance:i=[],dastUrl:s,depth:a="standard",failOnSeverity:o="critical"}=e,u=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 l=await Cc(n,a);this.emitStream(t,{status:"discovered",message:`Found ${l.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 Tc(l,r);d.push(...y)}if(r.includes("dependency")){this.emitStream(t,{status:"dependency",message:"Scanning dependencies"});let y=await Sc(n);d.push(...y)}r.includes("dast")&&s&&(this.emitStream(t,{status:"dast",message:`Scanning ${s}`}),d.push(...kc(s)));let m=i.map(y=>Mc(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:l.length,scanDurationMs:Date.now()-u},g=["critical","high","medium","low","informational"],h=g.indexOf(o),v=(d.length>0?Math.min(...d.map(y=>g.indexOf(y.severity))):g.length)>h;return this.emitStream(t,{status:"complete",message:`Scan complete: ${d.length} vulnerabilities found in ${l.length} files`,progress:100}),{success:!0,data:{scanId:t.requestId,summary:p,vulnerabilities:d,complianceResults:m.length>0?m:void 0,recommendations:Dc(d,p),passed:v}}}catch(l){return{success:!1,error:`Security scan failed: ${E(l)}`}}}},yc={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"}}},vc=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"]),bc=new Set(["node_modules",".git","__pycache__",".venv","venv","dist","build",".next",".nuxt","coverage",".tox"]);async function Cc(c,e){let t=await import("fs"),n=await import("path"),r=n.resolve(c),i=[],s=e==="quick"?50:e==="standard"?500:2e3,a=e==="quick"?3:e==="standard"?8:20;function o(u,l){if(i.length>=s||l>a)return;let d;try{d=t.readdirSync(u,{withFileTypes:!0})}catch{return}for(let m of d){if(i.length>=s)break;let p=n.join(u,m.name);if(m.isDirectory()){let g=new Set([".github",".docker",".aws",".circleci",".gitlab"]);bc.has(m.name)||m.name.startsWith(".")&&!g.has(m.name)||o(p,l+1)}else if(m.isFile()){let g=n.extname(m.name).toLowerCase();(vc.has(g)||m.name==="Dockerfile"||m.name==="Makefile"||m.name.startsWith(".env"))&&i.push(p)}}}try{t.statSync(r).isFile()?i.push(r):o(r,0)}catch{}return i}async function Tc(c,e){let t=await import("fs"),n=await import("path"),r=[],i=0,s=[];if(e.includes("sast")){for(let a of Hr)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 Rs)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 Ur)s.some(o=>o.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 Rs)s.some(o=>o.id===a.id)||s.push({...a,category:"sensitive-data"})}for(let a of c){let o;try{o=t.readFileSync(a,"utf-8")}catch{continue}if(o.includes("\0")||o.length>1e6)continue;let u=o.split(`
607
+ Analyze the requirements above and return the complete QualityCriteriaAnalysis.`}resetInstanceCache(){this.service=null}},Cc={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"]},bf=new Ye;k();import*as fr from"fs";import*as pe from"path";var nn=class extends P{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:Tc,streaming:!0,timeout:3e5};knowledgeGraph=null;semanticAnalyzer=null;impactAnalyzer=null;async getKnowledgeGraph(e){if(!this.knowledgeGraph){let t=e.memory??await F(),n=await B(e);this.knowledgeGraph=new Tt({memory:t,llmRouter:n})}return this.knowledgeGraph}async getSemanticAnalyzer(e){if(!this.semanticAnalyzer){let t=e.memory;this.semanticAnalyzer=new Hr(t||await F())}return this.semanticAnalyzer}async getImpactAnalyzer(e){if(!this.impactAnalyzer){let t=e.memory,n=await this.getKnowledgeGraph(e);this.impactAnalyzer=new Vr(t||await F(),n)}return this.impactAnalyzer}async execute(e,t){let{action:n,paths:r=["."],query:i,changedFiles:s=[],depth:a=3,incremental:o=!1}=e;try{if(this.emitStream(t,{status:"processing",message:`Executing ${n} action`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let u={action:n};switch(n){case"index":u.indexResult=await this.executeIndex(r,o,t);break;case"search":if(!i)return{success:!1,error:"Query is required for search action"};u.searchResult=await this.executeSearch(i,r,t);break;case"impact":if(s.length===0)return{success:!1,error:"changedFiles is required for impact action"};u.impactResult=await this.executeImpact(s,a,t);break;case"dependencies":u.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:u}}catch(u){return{success:!1,error:`Code analysis failed: ${T(u)}`}}}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 u=Date.now()-r;return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoSearchResult(e,u)}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(u=>({file:u.file,line:u.line,snippet:u.snippet.substring(0,200)+(u.snippet.length>200?"...":""),score:u.score,highlights:Sc(u.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,o=a.nodes.map(l=>({id:l.id,path:l.path,type:l.type,inDegree:l.inDegree,outDegree:l.outDegree})),u=a.edges.map(l=>({source:l.source,target:l.target,type:l.type}));return{nodes:o,edges:u,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 fr.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){let t=[],n=[".ts",".tsx",".js",".jsx"],r=["node_modules",".git","dist","build","coverage"];try{let i=await fr.promises.readdir(e,{withFileTypes:!0});for(let s of i){let a=pe.join(e,s.name);if(s.isDirectory()){if(!r.includes(s.name)){let o=await this.findSourceFiles(a);t.push(...o)}}else if(s.isFile()){let o=pe.extname(s.name);n.includes(o)&&t.push(a)}}}catch{}return t}},Tc={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 Sc(c,e){let t=[],n=e.toLowerCase().split(/\s+/),r=c.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),o=Math.min(c.length,s+i.length+20),u=c.substring(a,o);if(t.includes(u)||t.push(u),s+=i.length,t.length>=3)break}if(t.length>=3)break}return t}k();var yr=(c,e)=>c==="all"||c===e,rn=class extends P{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:Ec,streaming:!1,timeout:3e5};bridge=null;searchService=null;async getBridge(e){if(!this.bridge){let t=e.memory??await F();this.bridge=new jr(new Mr,t,{publishEvents:!1,enableC4Embeddings:!0,relationshipResolver:Ur(n=>new Tt(t,{basePath:n}))})}return this.bridge}async getSearchService(e){if(!this.searchService){let t=e.memory??await F();this.searchService=new Br(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 o={action:n};switch(n){case"generate":{let l=await(await this.getBridge(t)).requestC4Diagrams({projectPath:r,includeContext:yr(i,"context"),includeContainer:yr(i,"container"),includeComponent:yr(i,"component"),includeDependency:i==="all",analyzeComponents:!0,detectExternalSystems:!0,analyzeCoupling:!0});if(!l.success)return{success:!1,error:T(l.error)};let d=l.value;o.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 l=await(await this.getSearchService(t)).searchDiagrams(s,a);if(!l.success)return{success:!1,error:T(l.error)};o.searchResult={results:l.value.map(d=>({key:d.key,type:d.type,title:d.title,score:d.score,preview:d.preview})),total:l.value.length};break}default:return{success:!1,error:`Unknown action: ${n}`}}return{success:!0,data:o}}catch(o){return{success:!1,error:T(o)}}}},Ec={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();H();var Ds=[{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"}],sn=class extends P{config={name:"qe/security/scan",description:"Comprehensive security scanning including SAST, DAST, dependency analysis, and compliance validation.",domain:"security-compliance",schema:wc,streaming:!0,timeout:6e5};async execute(e,t){let{target:n=".",scanType:r=["sast","dependency"],compliance:i=[],dastUrl:s,depth:a="standard",failOnSeverity:o="critical"}=e,u=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 l=await xc(n,a);this.emitStream(t,{status:"discovered",message:`Found ${l.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 Ac(l,r);d.push(...y)}if(r.includes("dependency")){this.emitStream(t,{status:"dependency",message:"Scanning dependencies"});let y=await kc(n);d.push(...y)}r.includes("dast")&&s&&(this.emitStream(t,{status:"dast",message:`Scanning ${s}`}),d.push(...Lc(s)));let m=i.map(y=>Nc(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:l.length,scanDurationMs:Date.now()-u},g=["critical","high","medium","low","informational"],h=g.indexOf(o),v=(d.length>0?Math.min(...d.map(y=>g.indexOf(y.severity))):g.length)>h;return this.emitStream(t,{status:"complete",message:`Scan complete: ${d.length} vulnerabilities found in ${l.length} files`,progress:100}),{success:!0,data:{scanId:t.requestId,summary:p,vulnerabilities:d,complianceResults:m.length>0?m:void 0,recommendations:qc(d,p),passed:v}}}catch(l){return{success:!1,error:`Security scan failed: ${T(l)}`}}}},wc={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"}}},Rc=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"]),Pc=new Set(["node_modules",".git","__pycache__",".venv","venv","dist","build",".next",".nuxt","coverage",".tox"]);async function xc(c,e){let t=await import("fs"),n=await import("path"),r=n.resolve(c),i=[],s=e==="quick"?50:e==="standard"?500:2e3,a=e==="quick"?3:e==="standard"?8:20;function o(u,l){if(i.length>=s||l>a)return;let d;try{d=t.readdirSync(u,{withFileTypes:!0})}catch{return}for(let m of d){if(i.length>=s)break;let p=n.join(u,m.name);if(m.isDirectory()){let g=new Set([".github",".docker",".aws",".circleci",".gitlab"]);Pc.has(m.name)||m.name.startsWith(".")&&!g.has(m.name)||o(p,l+1)}else if(m.isFile()){let g=n.extname(m.name).toLowerCase();(Rc.has(g)||m.name==="Dockerfile"||m.name==="Makefile"||m.name.startsWith(".env"))&&i.push(p)}}}try{t.statSync(r).isFile()?i.push(r):o(r,0)}catch{}return i}async function Ac(c,e){let t=await import("fs"),n=await import("path"),r=[],i=0,s=[];if(e.includes("sast")){for(let a of Yr)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 Ds)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 Xr)s.some(o=>o.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 Ds)s.some(o=>o.id===a.id)||s.push({...a,category:"sensitive-data"})}for(let a of c){let o;try{o=t.readFileSync(a,"utf-8")}catch{continue}if(o.includes("\0")||o.length>1e6)continue;let u=o.split(`
608
608
  `),l=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(o))!==null;){i++;let g=o.substring(0,p.index).split(`
609
- `).length,h=u[g-1]||"",f=h.trim().length>100?h.trim().substring(0,100)+"...":h.trim();if(r.push({id:`${d.id}-${i}`,title:d.title,severity:d.severity,category:d.category||"security-misconfiguration",location:{file:l,line:g,snippet:f},description:d.description,remediation:d.remediation,cweId:d.cweId,references:[]}),i>200)break}}}return r}async function Sc(c){let e=await import("fs"),t=await import("path"),n=[],r=t.resolve(c),i=t.join(r,"package.json");if(e.existsSync(i))try{let o=A(e.readFileSync(i,"utf-8")),u={...o.dependencies,...o.devDependencies};n.push(...wc(u,"package.json"))}catch{}let s=t.join(r,"pyproject.toml");if(e.existsSync(s))try{let o=e.readFileSync(s,"utf-8"),u=Pc(o);n.push(...Ps(u,"pyproject.toml"))}catch{}let a=t.join(r,"requirements.txt");if(e.existsSync(a))try{let o=e.readFileSync(a,"utf-8"),u=xc(o);n.push(...Ps(u,"requirements.txt"))}catch{}if(n.length===0){let o=[i,s,a].filter(u=>e.existsSync(u));o.length>0&&n.push({id:"DEP-INFO-001",title:"Dependency audit recommended",severity:"informational",category:"vulnerable-components",location:{file:t.relative(process.cwd(),o[0])},description:`Found ${t.basename(o[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 Ec={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 wc(c,e){let t=[];for(let[n,r]of Object.entries(c)){let i=Ec[n];if(i){let s=r.replace(/^[\^~>=<]+/,"");Ac(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 Rc={"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 Pc(c){let e=[],t=c.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 xc(c){return c.split(`
610
- `).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")).map(e=>e.split(/[>=<!~\[]/)[0].trim().toLowerCase()).filter(Boolean)}function Ps(c,e){let t=[];for(let n of c){let r=Rc[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 Ac(c,e){let t=c.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 kc(c){return[{id:"DAST-INFO-001",title:"DAST scan target noted",severity:"informational",category:"security-misconfiguration",location:{file:c},description:`DAST target ${c} 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 Mc(c,e){let t=e.filter(n=>c==="owasp"?!0:c==="pci-dss"?n.category==="injection"||n.category==="sensitive-data":c==="gdpr"?n.category==="sensitive-data":!1);return{standard:c,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 Dc(c,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"),c.some(n=>n.category==="injection")&&t.push("Review input validation across the application"),c.some(n=>n.category==="sensitive-data")&&t.push("Implement proper secrets management"),c.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}H();M();function xs(c){try{let e=new URL(c);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: ${c}`}}}var rn=class extends x{config={name:"qe/contracts/validate",description:"Validate API contracts, detect breaking changes, and verify provider-consumer compatibility.",domain:"contract-testing",schema:Ic,streaming:!0,timeout:18e4};contractValidator=null;apiCompatibility=null;async getServices(e){if(!this.contractValidator||!this.apiCompatibility){let t=e.memory||await L(),n=await B(e);this.contractValidator=new Vr({memory:t,llmRouter:n}),this.apiCompatibility=new Qr(t)}return{contractValidator:this.contractValidator,apiCompatibility:this.apiCompatibility}}async execute(e,t){let{contractPath:n,contractContent:r,providerUrl:i,consumerName:s,baselineVersion:a,baselineContent:o,checkBreakingChanges:u=!0,format:l="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 ${l} contract`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let p=r||n||"",g=[],h,f,v;if(l==="openapi"){let b=await d.validateOpenAPI(p);if(b.success){let w=b.value;for(let S of w.errors)g.push({path:S.path,message:S.message,code:S.code,severity:"error"});for(let S of w.warnings)g.push({path:"",message:S,code:"WARNING",severity:"warning"});this.emitStream(t,{status:"analyzed",message:`Found ${w.endpointCount} endpoints, ${w.schemaCount} schemas`})}}else{let b=this.buildContractFromContent(p,l,s),w=await d.validateContract(b);if(w.success){let S=w.value;for(let T of S.errors)g.push(this.convertValidationError(T));for(let T of S.warnings)g.push({path:"",message:T,code:"WARNING",severity:"warning"})}}if(u&&(a||o)){this.emitStream(t,{status:"comparing",message:"Detecting breaking changes"});let b=this.buildContractFromContent(p,l,s),w=this.buildContractFromContent(o||p,l,s,a),S=await m.compareVersions(w,b);S.success?(h=S.value.breakingChanges.map(T=>this.convertBreakingChange(T)),v={isBackwardCompatible:S.value.isCompatible,breakingChangeCount:S.value.breakingChanges.length,nonBreakingChangeCount:S.value.nonBreakingChanges.length,deprecations:S.value.deprecations.map(T=>this.convertDeprecation(T))}):v=this.generateDefaultCompatibility(g,h)}else v=this.generateDefaultCompatibility(g,h);i&&(this.emitStream(t,{status:"verifying",message:"Verifying against provider"}),f=await this.verifyAgainstProvider(i,s||"default",p,l,d));let y=g.filter(b=>b.severity==="error").length===0,C=this.generateRecommendations(g,h,f);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:h,verificationResult:f,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=jr.parse(r||"1.0.0"),a=[],o=[];if(t==="openapi")try{let u=A(e),d=u.components?.schemas||{};for(let[p,g]of Object.entries(d))a.push({id:p,name:p,type:"openapi",content:JSON.stringify(g)});let m=u.paths||{};for(let[p,g]of Object.entries(m))if(typeof g=="object"&&g!==null){let h=g,f=["get","post","put","patch","delete","head","options"];for(let v of f)v in h&&o.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 l=A(e).interactions||[];for(let d of l){let m=d.request;m&&o.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:o,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=[],o=xs(e);if(!o.valid)return{provider:e,consumer:t,passed:!1,failures:[{endpoint:e,type:"validation-error",expected:"Valid HTTP/HTTPS URL",actual:o.error||"Invalid URL",message:`Provider URL validation failed: ${o.error}`}],warnings:[]};let u=this.buildContractFromContent(n,r,t);for(let l of u.endpoints)try{let d=`${e}${l.path}`,m=xs(d);if(!m.valid){s.push({endpoint:`${l.method} ${l.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:l.method==="GET"?"GET":"OPTIONS",headers:{Accept:"application/json"}});if(!p.ok&&p.status!==405&&(p.status===404?s.push({endpoint:`${l.method} ${l.path}`,type:"missing-endpoint",expected:"Endpoint should exist",actual:`Got ${p.status}`,message:"Endpoint not found at provider"}):a.push({endpoint:`${l.method} ${l.path}`,message:`Unexpected status ${p.status}`,severity:"medium"})),l.responseSchema&&p.ok){let g=await p.json(),h=u.schemas.find(f=>f.id===l.responseSchema);if(h){let f=await i.validateResponse(g,h);if(f.success&&!f.value.isValid)for(let v of f.value.errors)s.push({endpoint:`${l.method} ${l.path}`,type:"schema-mismatch",expected:`Schema ${l.responseSchema}`,actual:v.message,message:`Response does not match schema: ${v.message}`})}}}catch(d){a.push({endpoint:`${l.method} ${l.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(o=>o.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(u=>u.type==="missing-endpoint").length>0&&r.push("Ensure all contract endpoints are implemented in the provider"),n.failures.filter(u=>u.type==="schema-mismatch").length>0&&r.push("Update provider responses to match the contract schema")),n.warnings.length>0&&n.warnings.filter(o=>o.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}},Ic={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"}}};M();var sn=class extends x{config={name:"qe/visual/compare",description:"Visual regression testing with screenshot comparison, diff detection, and baseline management.",domain:"visual-accessibility",schema:Oc,streaming:!0,timeout:3e5};visualTester=null;async getService(e){if(!this.visualTester){let t=e.memory??await L(),n=await B(e);this.visualTester=Wr({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 o=await this.getService(t),u=[],l=[];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},h=await o.captureScreenshot(m,{viewport:g,fullPage:a});if(!h.success){u.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let f=h.value,v=await o.getBaseline(m,g);if(!v)await o.setBaseline(f),l.push(f.path.value),u.push({url:m,viewport:p,status:"new",diffPercentage:0,diffPixels:0,screenshotPath:f.path.value});else{let y=await o.compare(f,v.id);if(!y.success){u.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let C=y.value,b=C.diffPercentage<=s;u.push({url:m,viewport:p,status:b?"passed":"failed",diffPercentage:C.diffPercentage,diffPixels:C.diffPixels,screenshotPath:f.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:u.length,passed:u.filter(m=>m.status==="passed").length,failed:u.filter(m=>m.status==="failed").length,new:u.filter(m=>m.status==="new").length,avgDiffPercentage:u.length>0?u.reduce((m,p)=>m+p.diffPercentage,0)/u.length:0};return this.emitStream(t,{status:"complete",message:`Visual comparison complete: ${d.passed}/${d.total} passed`,progress:100}),{success:!0,data:{comparisons:u,summary:d,newBaselines:l,recommendations:Lc(u,d)}}}catch(o){return{success:!1,error:`Visual comparison failed: ${E(o)}`}}}},an=class extends x{config={name:"qe/a11y/audit",description:"WCAG accessibility auditing with violation detection, contrast checking, and keyboard navigation testing.",domain:"visual-accessibility",schema:_c,streaming:!0,timeout:18e4};accessibilityTester=null;async getService(e){if(!this.accessibilityTester){let t=e.memory;this.accessibilityTester=new Kr(t||await L(),{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 o=await this.getService(t),u=[],l=Fc(r);for(let g of n){this.emitStream(t,{status:"scanning",message:`Scanning ${g}`});let h=await o.audit(g,{wcagLevel:l,includeWarnings:i});if(!h.success){u.push({url:g,score:0,passed:!1,violations:[],warnings:[],passedRules:0});continue}let f=h.value,v=[];if(s){let S=await o.checkContrast(g);if(S.success){let T=S.value.filter(P=>!P.passes);T.length>0&&(v=T.map(P=>({id:"color-contrast",impact:"serious",description:"Elements must have sufficient color contrast",help:`Element ${P.element} has contrast ratio ${P.ratio}:1 but requires ${P.requiredRatio}:1`,helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum",wcagCriteria:["1.4.3"],nodes:[{selector:P.element,html:`<${P.element.replace(".",' class="')}>...</${P.element.split(".")[0]}>`,failureSummary:`Contrast ratio ${P.ratio}:1 is below required ${P.requiredRatio}:1`,fixSuggestion:`Change foreground color to achieve at least ${P.requiredRatio}:1 contrast`}]})))}}let y=[];if(a){let S=await o.checkKeyboardNavigation(g);if(S.success){let T=S.value;for(let P of T.issues)y.push({id:P.type,impact:P.type==="no-focus-indicator"?"serious":"moderate",description:P.description,help:"Ensure keyboard navigation is fully supported",helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/focus-visible",wcagCriteria:["2.4.7"],nodes:[{selector:P.selector,html:`<element>${P.selector}</element>`,failureSummary:P.description,fixSuggestion:"Add visible focus styles with :focus or :focus-visible"}]});for(let P of T.traps)y.push({id:"keyboard-trap",impact:"critical",description:P.description,help:P.escapePath||"No escape path available",helpUrl:"https://www.w3.org/WAI/WCAG22/Understanding/no-keyboard-trap",wcagCriteria:["2.1.2"],nodes:[{selector:P.selector,html:`<element>${P.selector}</element>`,failureSummary:P.description,fixSuggestion:P.escapePath}]})}}let C=[...f.violations.map(S=>({id:S.id,impact:S.impact,description:S.description,help:S.help,helpUrl:S.helpUrl,wcagCriteria:S.wcagCriteria.map(T=>T.id),nodes:S.nodes.map(T=>({selector:T.selector,html:T.html,failureSummary:T.failureSummary,fixSuggestion:T.fixSuggestion}))})),...v,...y],b=f.incomplete.map(S=>({id:S.id,description:S.description,nodes:S.nodes.length})),w=C.some(S=>S.impact==="critical"||S.impact==="serious");u.push({url:g,score:f.score,passed:!w,violations:C,warnings:b,passedRules:f.passes.length})}let d={totalUrls:u.length,passingUrls:u.filter(g=>g.passed).length,avgScore:u.length>0?Math.round(u.reduce((g,h)=>g+h.score,0)/u.length):0,criticalViolations:u.reduce((g,h)=>g+h.violations.filter(f=>f.impact==="critical").length,0),seriousViolations:u.reduce((g,h)=>g+h.violations.filter(f=>f.impact==="serious").length,0),totalViolations:u.reduce((g,h)=>g+h.violations.length,0)},m=Nc(u),p=qc(m);return this.emitStream(t,{status:"complete",message:`Audit complete: avg score ${d.avgScore}%`,progress:100}),{success:!0,data:{audits:u,summary:d,topIssues:m,remediationPlan:p}}}catch(o){return{success:!1,error:`Accessibility audit failed: ${E(o)}`}}}},Oc={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"]},_c={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 Fc(c){return c==="wcag21-aaa"?"AAA":"AA"}function Lc(c,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 Nc(c){let e=new Map;for(let t of c)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 qc(c){return c.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}))}M();var on=class extends x{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:Gc,streaming:!0,timeout:3e5};chaosEngineer=null;async getService(e){if(!this.chaosEngineer){let t=e.memory||await L(),n=await B(e);this.chaosEngineer=new Xr({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:o,rollbackOnFailure:u=!0}=e,l=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||N(),m=this.buildExperiment(d,n,r,i,s,o,u);this.emitStream(t,{status:"verifying",message:"Verifying steady state"});let p=await l.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 h=await l.createExperiment(m);if(!h.success)return{success:!1,error:`Failed to create experiment: ${h.error.message}`};this.emitStream(t,{status:"injecting",message:a?`[DRY RUN] Simulating ${n} fault`:`Injecting ${n} fault`});let f=!1,v,y="pending",C=[],b={faultDuration:i,targetAffected:!a};if(a)f=!1,y="completed",b=this.simulateMetrics(n,i,s),o&&(v=this.validateHypothesisText(o,b,C));else{let T=await l.runExperiment(d);if(T.success){let P=T.value;f=P.faultResults.some(O=>O.injected),v=P.hypothesisValidated,y=P.status;for(let O of P.incidents)C.push(this.convertIncident(O));b=this.extractMetrics(P,n,i)}else y="failed",C.push({type:"error",severity:"critical",message:T.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(T=>T.severity==="critical"&&!T.resolved)&&(y=u?"rolled-back":"failed");let S=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:f,hypothesisValidated:v,steadyStateVerified:g,metrics:b,incidents:C,recommendations:S}}}catch(d){return{success:!1,error:`Chaos injection failed: ${E(d)}`}}}buildExperiment(e,t,n,r,i,s,a=!0){let o={id:`fault-${e}`,type:t,target:{type:"service",selector:n},duration:r,parameters:this.buildFaultParameters(t,i)},u={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}]},l=s||`System should remain stable under ${t} fault`;return{id:e,name:`${t}-experiment-${Date.now()}`,description:`Chaos experiment: ${t} on ${n}`,hypothesis:{statement:l,metrics:[{metric:t==="latency"?"response_time":"error_rate",operator:"lt",value:t==="latency"?5e3:50}],tolerances:[{metric:"availability",maxDeviation:20,unit:"percent"}]},steadyState:u,faults:[o],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:o.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(o=>o.injected&&o.affectedTargets>0)},i=e.metrics;e.endTime&&e.startTime&&(r.recoveryTime=e.endTime.getTime()-e.startTime.getTime());let s=i.find(o=>o.name.includes("latency")||o.name.includes("response"));s&&(r.latencyP99=s.value);let a=i.find(o=>o.name.includes("error")||o.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}},Gc={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"]};M();je();var Je=class extends x{config={name:"qe/learning/optimize",description:"Cross-domain learning, pattern recognition, strategy optimization, and knowledge transfer.",domain:"learning-optimization",schema:$c,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 L(),n=await B(e);this.learningCoordinator=new Yr({memory:t,llmRouter:n}),this.metricsOptimizer=new Zr(t),this.transferSpecialist=new Jr(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 o={action:n};switch(n){case"learn":o.learnResult=await this.executeLearn(r,i,t);break;case"optimize":if(!a)return{success:!1,error:"Objective is required for optimize action"};o.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"};o.transferResult=await this.executeTransfer(r,s,t);break;case"patterns":o.patternResult=await this.executePatterns(r,t);break;case"dashboard":o.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:o}}catch(o){return{success:!1,error:`Learning optimization failed: ${E(o)}`}}}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=Ue.lastNDays(7),a=await i.mineExperiences(r,s),o=[],u=0,l=0;if(a.success){u=a.value.experienceCount;for(let d of a.value.patterns)o.push({id:d.id,type:d.type,name:d.name,description:d.description,confidence:d.confidence,usageCount:d.usageCount,successRate:d.successRate});l=a.value.successRate>.5?(a.value.successRate-.5)*20:0}return t&&t.length>0&&(u=t.length),o.length===0?(this.markAsRealData(),{experiencesProcessed:u,patternsLearned:0,newPatterns:[],improvement:0}):(this.markAsRealData(),{experiencesProcessed:u,patternsLearned:o.length,newPatterns:o,improvement:l})}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=Ue.lastNDays(30),o=await r.mineExperiences(s,a),u=[];if(o.success&&o.value.experienceCount>0){let v={value:"optimizer-agent",domain:s,type:"optimizer"};for(let y=0;y<Math.min(o.value.experienceCount,20);y++)u.push({id:`exp-${y}`,agentId:v,domain:s,action:"optimize",state:{context:{},metrics:{}},result:{success:te()>.3,outcome:{[t.metric]:ne(70,100)},duration:ne(1e3,6e3)},reward:o.value.avgReward,timestamp:new Date})}let l={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=l,g=0,h=.5,f=[];if(u.length>=20){let v=await i.optimizeStrategy(l,m,u);v.success&&(p={name:v.value.optimizedStrategy.name,parameters:v.value.optimizedStrategy.parameters,expectedOutcome:v.value.optimizedStrategy.expectedOutcome},g=v.value.improvement*100,h=v.value.confidence,f=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:u.length>0?Math.min(u.length,12):1,bestStrategy:p,improvement:g,confidence:h,validationResults:f}}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,o=0,u=0;if(i.success){s=i.value.length;for(let d of i.value){let m=await r.transferKnowledge(d,t);m.success&&(a++,u+=m.value.relevanceScore,Math.abs(m.value.relevanceScore-d.relevanceScore)>.1&&o++)}}let l=s>0?a/s:0;return{sourcePatterns:s,transferredPatterns:a,adaptedPatterns:o,successRate:l,targetDomainUpdated:a>0}}async executePatterns(e,t){let{learningCoordinator:n}=await this.getServices(t);this.emitStream(t,{status:"analyzing",message:`Analyzing patterns${e?` for ${e}`:""}`});let r=await n.getPatternStats(e);if(!r.success)return{totalPatterns:0,byType:{},byDomain:{},topPatterns:[],avgConfidence:0,avgSuccessRate:0};let i=r.value,s=i.topPatterns.map(a=>({id:a.id,type:a.type,name:a.name,description:a.description,confidence:a.confidence,usageCount:a.usageCount,successRate:a.successRate}));return{totalPatterns:i.totalPatterns,byType:i.byType,byDomain:i.byDomain,topPatterns:s,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}async executeDashboard(e){let{learningCoordinator:t,transferSpecialist:n}=await this.getServices(e);this.emitStream(e,{status:"aggregating",message:"Aggregating learning metrics"});let r=await t.getPatternStats(),i=await n.queryKnowledge({minRelevance:0,limit:1e3}),s=Ue.lastNDays(1),a=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","learning-optimization"],o=0,u=[];for(let v of a){let y=await t.mineExperiences(v,s);y.success&&(o+=y.value.experienceCount,y.value.experienceCount>0&&u.push({domain:v,successRate:y.value.successRate}))}u.sort((v,y)=>y.successRate-v.successRate);let l=u.slice(0,3).map(v=>v.domain),d=r.success?r.value.totalPatterns:0,m=r.success?r.value.avgSuccessRate:0,p=m,g=[],h=new Date;for(let v=6;v>=0;v--){let y=new Date(h.getTime()-v*24*60*60*1e3),C=new Date(y.getTime()+1440*60*1e3),b=Ue.create(y,C),w=0;for(let S of a.slice(0,3)){let T=await t.mineExperiences(S,b);T.success&&(w+=T.value.patterns.length)}g.push({timestamp:y.toISOString(),metric:"patterns-learned",value:w})}let f=[];return d>=100&&f.push({name:`Reached ${Math.floor(d/50)*50} patterns`,achievedAt:new Date(h.getTime()-2880*60*1e3).toISOString(),domain:"learning-optimization"}),m>=.8&&f.push({name:`${Math.round(m*100)}% pattern success rate`,achievedAt:new Date(h.getTime()-7200*60*1e3).toISOString(),domain:l[0]||"learning-optimization"}),{overallLearningRate:p,totalPatterns:d,totalKnowledge:i.success?i.value.length:0,experiencesLast24h:o,topPerformingDomains:l.length>0?l:["test-generation"],learningTrend:g,recentMilestones:f}}},$c={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"]};M();var zc={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"]},Ze=class extends x{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:zc,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=Dr(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 L(),n=bt(t);await n.initialize();try{let{getSharedRvfDualWriter:a}=await import("./shared-rvf-dual-writer-DBQJHG42.js"),o=await a();o&&n.setRvfDualWriter(o)}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 l=await this.loadPatternsFromReasoningBank(s);this.logger.info(`Loaded ${l} patterns from ReasoningBank`)}let a=await s.dream(n),o={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},u=a.insights.map(l=>({id:l.id,type:l.type,description:l.description,noveltyScore:l.noveltyScore,confidenceScore:l.confidenceScore,actionable:l.actionable,applied:l.applied||!1,suggestedAction:l.suggestedAction,createdAt:l.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:o,insights:u}}}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 n=await this.getEngine(),i=(await n.getPendingInsights(100)).find(m=>m.id===e.insightId);if(!i)return{success:!1,error:`Insight not found or already applied: ${e.insightId}`,data:{action:"apply",success:!1,error:`Insight not found or already applied: ${e.insightId}`}};if(!i.actionable)return{success:!1,error:"Insight is not actionable",data:{action:"apply",success:!1,error:"Insight is not actionable"}};let s=await L(),a=bt(s);await a.initialize();try{let{getSharedRvfDualWriter:m}=await import("./shared-rvf-dual-writer-DBQJHG42.js"),p=await m();p&&a.setRvfDualWriter(p)}catch(m){process.env.DEBUG&&this.logger.info("RVF wiring skipped",{error:String(m)})}let o=this.mapInsightTypeToPatternType(i.type),u=await a.storePattern({patternType:o,name:`Dream Insight: ${i.type}`,description:`${i.description} (confidence: ${i.confidenceScore.toFixed(2)})`,template:{type:"workflow",content:i.suggestedAction||i.description,variables:[]},context:{tags:["dream-generated",i.type,...i.sourceConcepts.slice(0,3)],complexity:"medium"}});if(!u.success){let m=u.error?.message||"Unknown error";return{success:!1,error:`Failed to create pattern: ${m}`,data:{action:"apply",success:!1,error:`Failed to create pattern: ${m}`}}}let l=u.value.id;return await n.applyInsight(e.insightId),this.logger.info(`Applied insight ${e.insightId} \u2192 REAL pattern ${l} in ReasoningBank`),{success:!0,data:{action:"apply",success:!0,applyResult:{insightId:e.insightId,success:!0,patternId:l}}}}catch(n){let r=E(n);return{success:!1,error:r,data:{action:"apply",success:!1,error:r}}}}mapInsightTypeToPatternType(e){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[e]||"test-template"}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),o=s.reduce((d,m)=>d+m.insightsGenerated,0),u=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:o,pendingInsights:a.length,lastDreamTime:u?.startTime.toISOString()}}}}resetInstanceCache(){this.engine&&(this.engine.close().catch(console.error),this.engine=null)}};M();var cn=class extends x{config={name:"qe/analysis/token_usage",description:"Analyze token consumption patterns and identify optimization opportunities across agents and domains.",domain:"learning-optimization",schema:Bc,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:[Mr()]}}};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=J.getSessionSummary(e),n={};for(let[i,s]of t.byAgent)n[i]={tokens:s.totalTokens,cost:U(s.totalCost),tasks:s.tasksExecuted};let r={};for(let[i,s]of t.byDomain)r[i]={tokens:s.totalTokens,cost:U(s.estimatedCostUsd||0)};return{operation:"session",timeframe:e||"all",summary:{totalTokens:t.totalUsage.totalTokens,totalCost:U(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=J.getAgentMetrics(e,t),r=J.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:U(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:U(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,o=0,u=0,l=0;for(let d of i)s[d.agentId]={tokens:d.totalTokens,cost:U(d.totalCost),tasks:d.tasksExecuted},a+=d.totalTokens,o+=d.totalCost,u+=d.estimatedTokensSaved,l+=d.patternsReused;return{operation:"agent",timeframe:t||"all",summary:{totalTokens:a,totalCost:U(o),tokensSaved:u,savingsPercentage:this.calculateSavingsPercentage(a,u)},breakdown:{byAgent:Object.keys(s).length>0?s:void 0},optimization:{patternsReused:l,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateMultiAgentRecommendations(i)}}}getDomainUsage(e,t){let n=J.getDomainMetrics(e,t),r=J.getSessionSummary(t);if(e&&!(n instanceof Map)){let u=n;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:u.totalTokens,totalCost:U(u.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,u)},details:{domainMetrics:{domain:e,inputTokens:u.inputTokens,outputTokens:u.outputTokens,totalTokens:u.totalTokens,cost:U(u.estimatedCostUsd||0)}}}}let i=n instanceof Map?n:new Map,s={},a=0,o=0;for(let[u,l]of i)s[u]={tokens:l.totalTokens,cost:U(l.estimatedCostUsd||0)},a+=l.totalTokens,o+=l.estimatedCostUsd||0;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:a,totalCost:U(o),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=J.getTaskMetrics(e),n=J.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:U(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:U(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=J.getEfficiencyReport(e),n=J.getSessionSummary(e);return{operation:"efficiency",timeframe:e||"all",summary:{totalTokens:t.totalTokensUsed,totalCost:U(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}},Bc={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"]};M();var et={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 jc=[{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"},{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"},{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"},{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"},{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"},{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"}],Uc=[{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"},{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"},{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"},{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"},{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"},{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"},{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"}],Hc=[{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"},{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"},{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"},{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"},{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"}],Vc=[{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"},{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"},{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"},{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"},{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"}],Qc=[{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:"code-intelligence"},{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"},{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"},{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"},{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"}],Wc=[{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"},{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"},{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"},{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"},{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"}],Kc=[{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"},{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"},{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"},{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"},{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"}],Xc=[{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"},{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"}],As=[...jc,...Uc,...Hc,...Vc,...Qc,...Wc,...Kc,...Xc];function Yc(c){return`action-${c}`}function ks(c){return{...c,id:Yc(c.name),executionCount:0}}function tt(){return As.map(ks)}var ln=[{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"}];H();import{randomUUID as ye}from"crypto";var fr=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}}},Jc=new Set(["__proto__","constructor","prototype"]),un=class{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=kr(),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(),await this.loadActions(),this.initialized=!0,console.log(`[GOAPPlanner] Initialized: ${this.persistence.getDbPath()}`)}seedDefaultActions(){let e=tt(),t=this.ensureDb(),n=t.prepare(`
609
+ `).length,h=u[g-1]||"",f=h.trim().length>100?h.trim().substring(0,100)+"...":h.trim();if(r.push({id:`${d.id}-${i}`,title:d.title,severity:d.severity,category:d.category||"security-misconfiguration",location:{file:l,line:g,snippet:f},description:d.description,remediation:d.remediation,cweId:d.cweId,references:[]}),i>200)break}}}return r}async function kc(c){let e=await import("fs"),t=await import("path"),n=[],r=t.resolve(c),i=t.join(r,"package.json");if(e.existsSync(i))try{let o=A(e.readFileSync(i,"utf-8")),u={...o.dependencies,...o.devDependencies};n.push(...Dc(u,"package.json"))}catch{}let s=t.join(r,"pyproject.toml");if(e.existsSync(s))try{let o=e.readFileSync(s,"utf-8"),u=Oc(o);n.push(...Is(u,"pyproject.toml"))}catch{}let a=t.join(r,"requirements.txt");if(e.existsSync(a))try{let o=e.readFileSync(a,"utf-8"),u=_c(o);n.push(...Is(u,"requirements.txt"))}catch{}if(n.length===0){let o=[i,s,a].filter(u=>e.existsSync(u));o.length>0&&n.push({id:"DEP-INFO-001",title:"Dependency audit recommended",severity:"informational",category:"vulnerable-components",location:{file:t.relative(process.cwd(),o[0])},description:`Found ${t.basename(o[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 Mc={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 Dc(c,e){let t=[];for(let[n,r]of Object.entries(c)){let i=Mc[n];if(i){let s=r.replace(/^[\^~>=<]+/,"");Fc(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 Ic={"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 Oc(c){let e=[],t=c.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 _c(c){return c.split(`
610
+ `).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")).map(e=>e.split(/[>=<!~\[]/)[0].trim().toLowerCase()).filter(Boolean)}function Is(c,e){let t=[];for(let n of c){let r=Ic[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 Fc(c,e){let t=c.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 Lc(c){return[{id:"DAST-INFO-001",title:"DAST scan target noted",severity:"informational",category:"security-misconfiguration",location:{file:c},description:`DAST target ${c} 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 Nc(c,e){let t=e.filter(n=>c==="owasp"?!0:c==="pci-dss"?n.category==="injection"||n.category==="sensitive-data":c==="gdpr"?n.category==="sensitive-data":!1);return{standard:c,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 qc(c,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"),c.some(n=>n.category==="injection")&&t.push("Review input validation across the application"),c.some(n=>n.category==="sensitive-data")&&t.push("Implement proper secrets management"),c.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}H();k();function Os(c){try{let e=new URL(c);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: ${c}`}}}var an=class extends P{config={name:"qe/contracts/validate",description:"Validate API contracts, detect breaking changes, and verify provider-consumer compatibility.",domain:"contract-testing",schema:Gc,streaming:!0,timeout:18e4};contractValidator=null;apiCompatibility=null;async getServices(e){if(!this.contractValidator||!this.apiCompatibility){let t=e.memory||await F(),n=await B(e);this.contractValidator=new Jr({memory:t,llmRouter:n}),this.apiCompatibility=new Zr(t)}return{contractValidator:this.contractValidator,apiCompatibility:this.apiCompatibility}}async execute(e,t){let{contractPath:n,contractContent:r,providerUrl:i,consumerName:s,baselineVersion:a,baselineContent:o,checkBreakingChanges:u=!0,format:l="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 ${l} contract`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let p=r||n||"",g=[],h,f,v;if(l==="openapi"){let b=await d.validateOpenAPI(p);if(b.success){let w=b.value;for(let E of w.errors)g.push({path:E.path,message:E.message,code:E.code,severity:"error"});for(let E of w.warnings)g.push({path:"",message:E,code:"WARNING",severity:"warning"});this.emitStream(t,{status:"analyzed",message:`Found ${w.endpointCount} endpoints, ${w.schemaCount} schemas`})}}else{let b=this.buildContractFromContent(p,l,s),w=await d.validateContract(b);if(w.success){let E=w.value;for(let S of E.errors)g.push(this.convertValidationError(S));for(let S of E.warnings)g.push({path:"",message:S,code:"WARNING",severity:"warning"})}}if(u&&(a||o)){this.emitStream(t,{status:"comparing",message:"Detecting breaking changes"});let b=this.buildContractFromContent(p,l,s),w=this.buildContractFromContent(o||p,l,s,a),E=await m.compareVersions(w,b);E.success?(h=E.value.breakingChanges.map(S=>this.convertBreakingChange(S)),v={isBackwardCompatible:E.value.isCompatible,breakingChangeCount:E.value.breakingChanges.length,nonBreakingChangeCount:E.value.nonBreakingChanges.length,deprecations:E.value.deprecations.map(S=>this.convertDeprecation(S))}):v=this.generateDefaultCompatibility(g,h)}else v=this.generateDefaultCompatibility(g,h);i&&(this.emitStream(t,{status:"verifying",message:"Verifying against provider"}),f=await this.verifyAgainstProvider(i,s||"default",p,l,d));let y=g.filter(b=>b.severity==="error").length===0,C=this.generateRecommendations(g,h,f);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:h,verificationResult:f,compatibility:v,recommendations:C}}}catch(p){return{success:!1,error:`Contract validation failed: ${T(p)}`}}}buildContractFromContent(e,t,n,r){let i=`contract-${Date.now()}`,s=Kr.parse(r||"1.0.0"),a=[],o=[];if(t==="openapi")try{let u=A(e),d=u.components?.schemas||{};for(let[p,g]of Object.entries(d))a.push({id:p,name:p,type:"openapi",content:JSON.stringify(g)});let m=u.paths||{};for(let[p,g]of Object.entries(m))if(typeof g=="object"&&g!==null){let h=g,f=["get","post","put","patch","delete","head","options"];for(let v of f)v in h&&o.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 l=A(e).interactions||[];for(let d of l){let m=d.request;m&&o.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:o,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=[],o=Os(e);if(!o.valid)return{provider:e,consumer:t,passed:!1,failures:[{endpoint:e,type:"validation-error",expected:"Valid HTTP/HTTPS URL",actual:o.error||"Invalid URL",message:`Provider URL validation failed: ${o.error}`}],warnings:[]};let u=this.buildContractFromContent(n,r,t);for(let l of u.endpoints)try{let d=`${e}${l.path}`,m=Os(d);if(!m.valid){s.push({endpoint:`${l.method} ${l.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:l.method==="GET"?"GET":"OPTIONS",headers:{Accept:"application/json"}});if(!p.ok&&p.status!==405&&(p.status===404?s.push({endpoint:`${l.method} ${l.path}`,type:"missing-endpoint",expected:"Endpoint should exist",actual:`Got ${p.status}`,message:"Endpoint not found at provider"}):a.push({endpoint:`${l.method} ${l.path}`,message:`Unexpected status ${p.status}`,severity:"medium"})),l.responseSchema&&p.ok){let g=await p.json(),h=u.schemas.find(f=>f.id===l.responseSchema);if(h){let f=await i.validateResponse(g,h);if(f.success&&!f.value.isValid)for(let v of f.value.errors)s.push({endpoint:`${l.method} ${l.path}`,type:"schema-mismatch",expected:`Schema ${l.responseSchema}`,actual:v.message,message:`Response does not match schema: ${v.message}`})}}}catch(d){a.push({endpoint:`${l.method} ${l.path}`,message:`Failed to verify: ${T(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(o=>o.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(u=>u.type==="missing-endpoint").length>0&&r.push("Ensure all contract endpoints are implemented in the provider"),n.failures.filter(u=>u.type==="schema-mismatch").length>0&&r.push("Update provider responses to match the contract schema")),n.warnings.length>0&&n.warnings.filter(o=>o.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}},Gc={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 on=class extends P{config={name:"qe/visual/compare",description:"Visual regression testing with screenshot comparison, diff detection, and baseline management.",domain:"visual-accessibility",schema:$c,streaming:!0,timeout:3e5};visualTester=null;async getService(e){if(!this.visualTester){let t=e.memory??await F(),n=await B(e);this.visualTester=ei({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 o=await this.getService(t),u=[],l=[];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},h=await o.captureScreenshot(m,{viewport:g,fullPage:a});if(!h.success){u.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let f=h.value,v=await o.getBaseline(m,g);if(!v)await o.setBaseline(f),l.push(f.path.value),u.push({url:m,viewport:p,status:"new",diffPercentage:0,diffPixels:0,screenshotPath:f.path.value});else{let y=await o.compare(f,v.id);if(!y.success){u.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let C=y.value,b=C.diffPercentage<=s;u.push({url:m,viewport:p,status:b?"passed":"failed",diffPercentage:C.diffPercentage,diffPixels:C.diffPixels,screenshotPath:f.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:u.length,passed:u.filter(m=>m.status==="passed").length,failed:u.filter(m=>m.status==="failed").length,new:u.filter(m=>m.status==="new").length,avgDiffPercentage:u.length>0?u.reduce((m,p)=>m+p.diffPercentage,0)/u.length:0};return this.emitStream(t,{status:"complete",message:`Visual comparison complete: ${d.passed}/${d.total} passed`,progress:100}),{success:!0,data:{comparisons:u,summary:d,newBaselines:l,recommendations:jc(u,d)}}}catch(o){return{success:!1,error:`Visual comparison failed: ${T(o)}`}}}},cn=class extends P{config={name:"qe/a11y/audit",description:"WCAG accessibility auditing with violation detection, contrast checking, and keyboard navigation testing.",domain:"visual-accessibility",schema:zc,streaming:!0,timeout:18e4};accessibilityTester=null;async getService(e){if(!this.accessibilityTester){let t=e.memory;this.accessibilityTester=new ti(t||await F(),{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 o=await this.getService(t),u=[],l=Bc(r);for(let g of n){this.emitStream(t,{status:"scanning",message:`Scanning ${g}`});let h=await o.audit(g,{wcagLevel:l,includeWarnings:i});if(!h.success){u.push({url:g,score:0,passed:!1,violations:[],warnings:[],passedRules:0});continue}let f=h.value,v=[];if(s){let E=await o.checkContrast(g);if(E.success){let S=E.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 E=await o.checkKeyboardNavigation(g);if(E.success){let S=E.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=[...f.violations.map(E=>({id:E.id,impact:E.impact,description:E.description,help:E.help,helpUrl:E.helpUrl,wcagCriteria:E.wcagCriteria.map(S=>S.id),nodes:E.nodes.map(S=>({selector:S.selector,html:S.html,failureSummary:S.failureSummary,fixSuggestion:S.fixSuggestion}))})),...v,...y],b=f.incomplete.map(E=>({id:E.id,description:E.description,nodes:E.nodes.length})),w=C.some(E=>E.impact==="critical"||E.impact==="serious");u.push({url:g,score:f.score,passed:!w,violations:C,warnings:b,passedRules:f.passes.length})}let d={totalUrls:u.length,passingUrls:u.filter(g=>g.passed).length,avgScore:u.length>0?Math.round(u.reduce((g,h)=>g+h.score,0)/u.length):0,criticalViolations:u.reduce((g,h)=>g+h.violations.filter(f=>f.impact==="critical").length,0),seriousViolations:u.reduce((g,h)=>g+h.violations.filter(f=>f.impact==="serious").length,0),totalViolations:u.reduce((g,h)=>g+h.violations.length,0)},m=Uc(u),p=Hc(m);return this.emitStream(t,{status:"complete",message:`Audit complete: avg score ${d.avgScore}%`,progress:100}),{success:!0,data:{audits:u,summary:d,topIssues:m,remediationPlan:p}}}catch(o){return{success:!1,error:`Accessibility audit failed: ${T(o)}`}}}},$c={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"]},zc={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 Bc(c){return c==="wcag21-aaa"?"AAA":"AA"}function jc(c,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 Uc(c){let e=new Map;for(let t of c)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 Hc(c){return c.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 ln=class extends P{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:Vc,streaming:!0,timeout:3e5};chaosEngineer=null;async getService(e){if(!this.chaosEngineer){let t=e.memory||await F(),n=await B(e);this.chaosEngineer=new ni({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:o,rollbackOnFailure:u=!0}=e,l=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||N(),m=this.buildExperiment(d,n,r,i,s,o,u);this.emitStream(t,{status:"verifying",message:"Verifying steady state"});let p=await l.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 h=await l.createExperiment(m);if(!h.success)return{success:!1,error:`Failed to create experiment: ${h.error.message}`};this.emitStream(t,{status:"injecting",message:a?`[DRY RUN] Simulating ${n} fault`:`Injecting ${n} fault`});let f=!1,v,y="pending",C=[],b={faultDuration:i,targetAffected:!a};if(a)f=!1,y="completed",b=this.simulateMetrics(n,i,s),o&&(v=this.validateHypothesisText(o,b,C));else{let S=await l.runExperiment(d);if(S.success){let x=S.value;f=x.faultResults.some(O=>O.injected),v=x.hypothesisValidated,y=x.status;for(let O of x.incidents)C.push(this.convertIncident(O));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=u?"rolled-back":"failed");let E=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:f,hypothesisValidated:v,steadyStateVerified:g,metrics:b,incidents:C,recommendations:E}}}catch(d){return{success:!1,error:`Chaos injection failed: ${T(d)}`}}}buildExperiment(e,t,n,r,i,s,a=!0){let o={id:`fault-${e}`,type:t,target:{type:"service",selector:n},duration:r,parameters:this.buildFaultParameters(t,i)},u={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}]},l=s||`System should remain stable under ${t} fault`;return{id:e,name:`${t}-experiment-${Date.now()}`,description:`Chaos experiment: ${t} on ${n}`,hypothesis:{statement:l,metrics:[{metric:t==="latency"?"response_time":"error_rate",operator:"lt",value:t==="latency"?5e3:50}],tolerances:[{metric:"availability",maxDeviation:20,unit:"percent"}]},steadyState:u,faults:[o],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:o.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(o=>o.injected&&o.affectedTargets>0)},i=e.metrics;e.endTime&&e.startTime&&(r.recoveryTime=e.endTime.getTime()-e.startTime.getTime());let s=i.find(o=>o.name.includes("latency")||o.name.includes("response"));s&&(r.latencyP99=s.value);let a=i.find(o=>o.name.includes("error")||o.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}},Vc={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();je();var Je=class extends P{config={name:"qe/learning/optimize",description:"Cross-domain learning, pattern recognition, strategy optimization, and knowledge transfer.",domain:"learning-optimization",schema:Qc,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 F(),n=await B(e);this.learningCoordinator=new ri({memory:t,llmRouter:n}),this.metricsOptimizer=new si(t),this.transferSpecialist=new ii(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 o={action:n};switch(n){case"learn":o.learnResult=await this.executeLearn(r,i,t);break;case"optimize":if(!a)return{success:!1,error:"Objective is required for optimize action"};o.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"};o.transferResult=await this.executeTransfer(r,s,t);break;case"patterns":o.patternResult=await this.executePatterns(r,t);break;case"dashboard":o.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:o}}catch(o){return{success:!1,error:`Learning optimization failed: ${T(o)}`}}}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=Ue.lastNDays(7),a=await i.mineExperiences(r,s),o=[],u=0,l=0;if(a.success){u=a.value.experienceCount;for(let d of a.value.patterns)o.push({id:d.id,type:d.type,name:d.name,description:d.description,confidence:d.confidence,usageCount:d.usageCount,successRate:d.successRate});l=a.value.successRate>.5?(a.value.successRate-.5)*20:0}return t&&t.length>0&&(u=t.length),o.length===0?(this.markAsRealData(),{experiencesProcessed:u,patternsLearned:0,newPatterns:[],improvement:0}):(this.markAsRealData(),{experiencesProcessed:u,patternsLearned:o.length,newPatterns:o,improvement:l})}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=Ue.lastNDays(30),o=await r.mineExperiences(s,a),u=[];if(o.success&&o.value.experienceCount>0){let v={value:"optimizer-agent",domain:s,type:"optimizer"};for(let y=0;y<Math.min(o.value.experienceCount,20);y++)u.push({id:`exp-${y}`,agentId:v,domain:s,action:"optimize",state:{context:{},metrics:{}},result:{success:te()>.3,outcome:{[t.metric]:ne(70,100)},duration:ne(1e3,6e3)},reward:o.value.avgReward,timestamp:new Date})}let l={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=l,g=0,h=.5,f=[];if(u.length>=20){let v=await i.optimizeStrategy(l,m,u);v.success&&(p={name:v.value.optimizedStrategy.name,parameters:v.value.optimizedStrategy.parameters,expectedOutcome:v.value.optimizedStrategy.expectedOutcome},g=v.value.improvement*100,h=v.value.confidence,f=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:u.length>0?Math.min(u.length,12):1,bestStrategy:p,improvement:g,confidence:h,validationResults:f}}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,o=0,u=0;if(i.success){s=i.value.length;for(let d of i.value){let m=await r.transferKnowledge(d,t);m.success&&(a++,u+=m.value.relevanceScore,Math.abs(m.value.relevanceScore-d.relevanceScore)>.1&&o++)}}let l=s>0?a/s:0;return{sourcePatterns:s,transferredPatterns:a,adaptedPatterns:o,successRate:l,targetDomainUpdated:a>0}}async executePatterns(e,t){let{learningCoordinator:n}=await this.getServices(t);this.emitStream(t,{status:"analyzing",message:`Analyzing patterns${e?` for ${e}`:""}`});let r=await n.getPatternStats(e);if(!r.success)return{totalPatterns:0,byType:{},byDomain:{},topPatterns:[],avgConfidence:0,avgSuccessRate:0};let i=r.value,s=i.topPatterns.map(a=>({id:a.id,type:a.type,name:a.name,description:a.description,confidence:a.confidence,usageCount:a.usageCount,successRate:a.successRate}));return{totalPatterns:i.totalPatterns,byType:i.byType,byDomain:i.byDomain,topPatterns:s,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}async executeDashboard(e){let{learningCoordinator:t,transferSpecialist:n}=await this.getServices(e);this.emitStream(e,{status:"aggregating",message:"Aggregating learning metrics"});let r=await t.getPatternStats(),i=await n.queryKnowledge({minRelevance:0,limit:1e3}),s=Ue.lastNDays(1),a=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","learning-optimization"],o=0,u=[];for(let v of a){let y=await t.mineExperiences(v,s);y.success&&(o+=y.value.experienceCount,y.value.experienceCount>0&&u.push({domain:v,successRate:y.value.successRate}))}u.sort((v,y)=>y.successRate-v.successRate);let l=u.slice(0,3).map(v=>v.domain),d=r.success?r.value.totalPatterns:0,m=r.success?r.value.avgSuccessRate:0,p=m,g=[],h=new Date;for(let v=6;v>=0;v--){let y=new Date(h.getTime()-v*24*60*60*1e3),C=new Date(y.getTime()+1440*60*1e3),b=Ue.create(y,C),w=0;for(let E of a.slice(0,3)){let S=await t.mineExperiences(E,b);S.success&&(w+=S.value.patterns.length)}g.push({timestamp:y.toISOString(),metric:"patterns-learned",value:w})}let f=[];return d>=100&&f.push({name:`Reached ${Math.floor(d/50)*50} patterns`,achievedAt:new Date(h.getTime()-2880*60*1e3).toISOString(),domain:"learning-optimization"}),m>=.8&&f.push({name:`${Math.round(m*100)}% pattern success rate`,achievedAt:new Date(h.getTime()-7200*60*1e3).toISOString(),domain:l[0]||"learning-optimization"}),{overallLearningRate:p,totalPatterns:d,totalKnowledge:i.success?i.value.length:0,experiencesLast24h:o,topPerformingDomains:l.length>0?l:["test-generation"],learningTrend:g,recentMilestones:f}}},Qc={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 Wc={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"]},Ze=class extends P{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:Wc,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=Fr(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 F(),n=bt(t);await n.initialize();try{let{getSharedRvfDualWriter:a}=await import("./shared-rvf-dual-writer-INQDY5WE.js"),o=await a();o&&n.setRvfDualWriter(o)}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=T(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 l=await this.loadPatternsFromReasoningBank(s);this.logger.info(`Loaded ${l} patterns from ReasoningBank`)}let a=await s.dream(n),o={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},u=a.insights.map(l=>({id:l.id,type:l.type,description:l.description,noveltyScore:l.noveltyScore,confidenceScore:l.confidenceScore,actionable:l.actionable,applied:l.applied||!1,suggestedAction:l.suggestedAction,createdAt:l.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:o,insights:u}}}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 n=await this.getEngine(),i=(await n.getPendingInsights(100)).find(m=>m.id===e.insightId);if(!i)return{success:!1,error:`Insight not found or already applied: ${e.insightId}`,data:{action:"apply",success:!1,error:`Insight not found or already applied: ${e.insightId}`}};if(!i.actionable)return{success:!1,error:"Insight is not actionable",data:{action:"apply",success:!1,error:"Insight is not actionable"}};let s=await F(),a=bt(s);await a.initialize();try{let{getSharedRvfDualWriter:m}=await import("./shared-rvf-dual-writer-INQDY5WE.js"),p=await m();p&&a.setRvfDualWriter(p)}catch(m){process.env.DEBUG&&this.logger.info("RVF wiring skipped",{error:String(m)})}let o=this.mapInsightTypeToPatternType(i.type),u=await a.storePattern({patternType:o,name:`Dream Insight: ${i.type}`,description:`${i.description} (confidence: ${i.confidenceScore.toFixed(2)})`,template:{type:"workflow",content:i.suggestedAction||i.description,variables:[]},context:{tags:["dream-generated",i.type,...i.sourceConcepts.slice(0,3)],complexity:"medium"}});if(!u.success){let m=u.error?.message||"Unknown error";return{success:!1,error:`Failed to create pattern: ${m}`,data:{action:"apply",success:!1,error:`Failed to create pattern: ${m}`}}}let l=u.value.id;return await n.applyInsight(e.insightId),this.logger.info(`Applied insight ${e.insightId} \u2192 REAL pattern ${l} in ReasoningBank`),{success:!0,data:{action:"apply",success:!0,applyResult:{insightId:e.insightId,success:!0,patternId:l}}}}catch(n){let r=T(n);return{success:!1,error:r,data:{action:"apply",success:!1,error:r}}}}mapInsightTypeToPatternType(e){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[e]||"test-template"}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),o=s.reduce((d,m)=>d+m.insightsGenerated,0),u=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:o,pendingInsights:a.length,lastDreamTime:u?.startTime.toISOString()}}}}resetInstanceCache(){this.engine&&(this.engine.close().catch(console.error),this.engine=null)}};k();var un=class extends P{config={name:"qe/analysis/token_usage",description:"Analyze token consumption patterns and identify optimization opportunities across agents and domains.",domain:"learning-optimization",schema:Kc,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:[_r()]}}};default:return{success:!1,error:`Unknown operation: ${n}`}}return{success:!0,data:a}}catch(a){return{success:!1,error:`Token usage analysis failed: ${T(a)}`}}}getSessionUsage(e){let t=J.getSessionSummary(e),n={};for(let[i,s]of t.byAgent)n[i]={tokens:s.totalTokens,cost:U(s.totalCost),tasks:s.tasksExecuted};let r={};for(let[i,s]of t.byDomain)r[i]={tokens:s.totalTokens,cost:U(s.estimatedCostUsd||0)};return{operation:"session",timeframe:e||"all",summary:{totalTokens:t.totalUsage.totalTokens,totalCost:U(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=J.getAgentMetrics(e,t),r=J.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:U(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:U(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,o=0,u=0,l=0;for(let d of i)s[d.agentId]={tokens:d.totalTokens,cost:U(d.totalCost),tasks:d.tasksExecuted},a+=d.totalTokens,o+=d.totalCost,u+=d.estimatedTokensSaved,l+=d.patternsReused;return{operation:"agent",timeframe:t||"all",summary:{totalTokens:a,totalCost:U(o),tokensSaved:u,savingsPercentage:this.calculateSavingsPercentage(a,u)},breakdown:{byAgent:Object.keys(s).length>0?s:void 0},optimization:{patternsReused:l,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateMultiAgentRecommendations(i)}}}getDomainUsage(e,t){let n=J.getDomainMetrics(e,t),r=J.getSessionSummary(t);if(e&&!(n instanceof Map)){let u=n;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:u.totalTokens,totalCost:U(u.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,u)},details:{domainMetrics:{domain:e,inputTokens:u.inputTokens,outputTokens:u.outputTokens,totalTokens:u.totalTokens,cost:U(u.estimatedCostUsd||0)}}}}let i=n instanceof Map?n:new Map,s={},a=0,o=0;for(let[u,l]of i)s[u]={tokens:l.totalTokens,cost:U(l.estimatedCostUsd||0)},a+=l.totalTokens,o+=l.estimatedCostUsd||0;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:a,totalCost:U(o),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=J.getTaskMetrics(e),n=J.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:U(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:U(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=J.getEfficiencyReport(e),n=J.getSessionSummary(e);return{operation:"efficiency",timeframe:e||"all",summary:{totalTokens:t.totalTokensUsed,totalCost:U(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}},Kc={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();var et={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 Xc=[{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"},{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"},{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"},{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"},{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"},{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"}],Yc=[{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"},{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"},{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"},{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"},{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"},{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"},{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"}],Jc=[{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"},{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"},{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"},{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"},{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"}],Zc=[{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"},{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"},{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"},{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"},{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"}],el=[{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:"code-intelligence"},{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"},{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"},{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"},{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"}],tl=[{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"},{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"},{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"},{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"},{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"}],nl=[{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"},{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"},{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"},{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"},{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"}],rl=[{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"},{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"}],_s=[...Xc,...Yc,...Jc,...Zc,...el,...tl,...nl,...rl];function il(c){return`action-${c}`}function Fs(c){return{...c,id:il(c.name),executionCount:0}}function tt(){return _s.map(Fs)}var dn=[{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"}];H();import{randomUUID as ye}from"crypto";var br=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}}},sl=new Set(["__proto__","constructor","prototype"]),mn=class{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=Or(),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(),await this.loadActions(),this.initialized=!0,console.log(`[GOAPPlanner] Initialized: ${this.persistence.getDbPath()}`)}seedDefaultActions(){let e=tt(),t=this.ensureDb(),n=t.prepare(`
611
611
  INSERT INTO goap_actions (id, name, description, category, preconditions, effects, cost, qe_domain, agent_type)
612
612
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
613
613
  `);for(let i of e){let s=`action-${Date.now()}-${ye().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)}let r=t.prepare(`
614
614
  INSERT INTO goap_goals (id, name, description, conditions, priority, qe_domain)
615
615
  VALUES (?, ?, ?, ?, ?, ?)
616
- `);for(let i of ln){let s=`goal-${Date.now()}-${ye().slice(0,8)}`;r.run(s,i.name,i.description,JSON.stringify(i.conditions),i.priority,i.qeDomain??null)}console.log(`[GOAPPlanner] Seeded ${e.length} actions and ${ln.length} goals`)}async findPlan(e,t,n){await this.initialize();let r=Date.now();if(this.enablePlanReuse){let u=await this.findSimilarPlan(t,.75);if(u&&this.validatePlanForState(u,e))return this.recordPlanReuse(u.id,!0),{...u,id:`plan-${Date.now()}-${ye().slice(0,8)}`,initialState:this.cloneState(e),reusedFrom:u.id,status:"pending"}}let i=this.getAvailableActions(n),s=this.aStarSearch(e,t,i,n);if(!s)return null;let a={id:`plan-${Date.now()}-${ye().slice(0,8)}`,initialState:this.cloneState(e),goalState:t,actions:s,totalCost:s.reduce((u,l)=>u+l.cost,0),estimatedDurationMs:s.reduce((u,l)=>u+(l.estimatedDurationMs??0),0),status:"pending"};await this.storePlanSignature(a);let o=Date.now()-r;return o>500&&console.warn(`[GOAPPlanner] Plan finding took ${o}ms (target: <500ms)`),a}aStarSearch(e,t,n,r){if(!this.canAnyActionAffectGoal(n,t))return null;let i=new fr((g,h)=>g.f-h.f),s=new Set,a=new Map,o={state:this.cloneState(e),action:null,parent:null,g:0,h:this.calculateHeuristic(e,t),f:0,depth:0};o.f=o.g+o.h,i.push(o),a.set(this.hashState(e),0);let u=1e4,l=20,d=r?.maxCost??1/0,m=r?.maxDurationMs??1/0,p=0;for(;i.length>0&&p<u;){p++;let g=i.pop();if(this.meetsConditions(g.state,t))return this.reconstructPlan(g);let h=this.hashState(g.state);if(!s.has(h)&&(s.add(h),a.delete(h),!(g.depth>=l)))for(let f of n){if(!this.meetsConditions(g.state,f.preconditions))continue;let v=this.applyAction(g.state,f),y=this.hashState(v);if(s.has(y))continue;let C=g.g+this.getActionCost(f,g.state),b=this.calculateHeuristic(v,t),w=C+b;if(C>d||g.depth*1e3+(f.estimatedDurationMs??0)>m)continue;let T=a.get(y);T!==void 0&&C>=T||(a.set(y,C),i.push({state:v,action:f,parent:g,g:C,h:b,f:w,depth:g.depth+1}))}}return null}canAnyActionAffectGoal(e,t){let n=Object.keys(t);for(let r of e)for(let i of Object.keys(r.effects))for(let s of n)if(i===s||i.startsWith(s)||s.startsWith(i))return!0;return!1}reconstructPlan(e){let t=[],n=e;for(;n&&n.action;)t.unshift(n.action),n=n.parent;return t}applyAction(e,t){let n=this.cloneState(e);for(let[r,i]of Object.entries(t.effects))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)}}}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))}calculateHeuristic(e,t){let n=0;for(let[r,i]of Object.entries(t)){let s=this.getStateValue(e,r);if(typeof i=="object"&&i!==null&&"min"in i){let a=i.min;typeof s=="number"&&s<a&&(n+=(a-s)/100)}if(typeof i=="object"&&i!==null&&"max"in i){let a=i.max;typeof s=="number"&&s>a&&(n+=(s-a)/100)}typeof i=="object"&&i!==null&&"eq"in i&&s!==i.eq&&(n+=1),(typeof i=="string"||typeof i=="number"||typeof i=="boolean")&&s!==i&&(n+=1)}return n}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(".");for(let a of r)if(Jc.has(a)){console.warn(`[GOAPPlanner] Blocked prototype pollution attempt: ${t}`);return}let i=e;for(let a=0;a<r.length-1;a++){let o=r[a];Object.hasOwn(i,o)||Object.defineProperty(i,o,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0});let u=Object.getOwnPropertyDescriptor(i,o);if(!u)return;i=u.value}let s=r[r.length-1];Object.defineProperty(i,s,{value:n,writable:!0,enumerable:!0,configurable:!0})}hashState(e){let t={coverageLine:Math.round(e.coverage.line),coverageBranch:Math.round(e.coverage.branch),coverageFunc:Math.round(e.coverage.function),coverageMeasured:e.coverage.measured,testsPassing:Math.round(e.quality.testsPassing),securityScore:Math.round(e.quality.securityScore),performanceScore:Math.round(e.quality.performanceScore),activeAgents:e.fleet.activeAgents,availableAgents:[...e.fleet.availableAgents].sort().join(","),timeRemaining:Math.floor(e.resources.timeRemaining/60),parallelSlots:e.resources.parallelSlots,environment:e.context.environment,riskLevel:e.context.riskLevel};return JSON.stringify(t)}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}}}getActionCost(e,t){let n=e.cost;return e.successRate<1&&(n=n/e.successRate),t.context.riskLevel==="high"&&(e.category==="performance"||e.category==="fleet")&&(n*=1.5),n}async loadActions(){let e=this.ensureDb().prepare("SELECT * FROM goap_actions ORDER BY category, cost").all();this.actions.clear();for(let t of e){let n={id:t.id,name:t.name,description:t.description??void 0,agentType:t.agent_type,preconditions:A(t.preconditions),effects:A(t.effects),cost:t.cost,estimatedDurationMs:t.estimated_duration_ms??void 0,successRate:t.success_rate,executionCount:t.execution_count,category:t.category,qeDomain:t.qe_domain};this.actions.set(n.id,n)}}async addAction(e){await this.initialize();let t=`action-${Date.now()}-${ye().slice(0,8)}`;this.ensureDb().prepare(`
616
+ `);for(let i of dn){let s=`goal-${Date.now()}-${ye().slice(0,8)}`;r.run(s,i.name,i.description,JSON.stringify(i.conditions),i.priority,i.qeDomain??null)}console.log(`[GOAPPlanner] Seeded ${e.length} actions and ${dn.length} goals`)}async findPlan(e,t,n){await this.initialize();let r=Date.now();if(this.enablePlanReuse){let u=await this.findSimilarPlan(t,.75);if(u&&this.validatePlanForState(u,e))return this.recordPlanReuse(u.id,!0),{...u,id:`plan-${Date.now()}-${ye().slice(0,8)}`,initialState:this.cloneState(e),reusedFrom:u.id,status:"pending"}}let i=this.getAvailableActions(n),s=this.aStarSearch(e,t,i,n);if(!s)return null;let a={id:`plan-${Date.now()}-${ye().slice(0,8)}`,initialState:this.cloneState(e),goalState:t,actions:s,totalCost:s.reduce((u,l)=>u+l.cost,0),estimatedDurationMs:s.reduce((u,l)=>u+(l.estimatedDurationMs??0),0),status:"pending"};await this.storePlanSignature(a);let o=Date.now()-r;return o>500&&console.warn(`[GOAPPlanner] Plan finding took ${o}ms (target: <500ms)`),a}aStarSearch(e,t,n,r){if(!this.canAnyActionAffectGoal(n,t))return null;let i=new br((g,h)=>g.f-h.f),s=new Set,a=new Map,o={state:this.cloneState(e),action:null,parent:null,g:0,h:this.calculateHeuristic(e,t),f:0,depth:0};o.f=o.g+o.h,i.push(o),a.set(this.hashState(e),0);let u=1e4,l=20,d=r?.maxCost??1/0,m=r?.maxDurationMs??1/0,p=0;for(;i.length>0&&p<u;){p++;let g=i.pop();if(this.meetsConditions(g.state,t))return this.reconstructPlan(g);let h=this.hashState(g.state);if(!s.has(h)&&(s.add(h),a.delete(h),!(g.depth>=l)))for(let f of n){if(!this.meetsConditions(g.state,f.preconditions))continue;let v=this.applyAction(g.state,f),y=this.hashState(v);if(s.has(y))continue;let C=g.g+this.getActionCost(f,g.state),b=this.calculateHeuristic(v,t),w=C+b;if(C>d||g.depth*1e3+(f.estimatedDurationMs??0)>m)continue;let S=a.get(y);S!==void 0&&C>=S||(a.set(y,C),i.push({state:v,action:f,parent:g,g:C,h:b,f:w,depth:g.depth+1}))}}return null}canAnyActionAffectGoal(e,t){let n=Object.keys(t);for(let r of e)for(let i of Object.keys(r.effects))for(let s of n)if(i===s||i.startsWith(s)||s.startsWith(i))return!0;return!1}reconstructPlan(e){let t=[],n=e;for(;n&&n.action;)t.unshift(n.action),n=n.parent;return t}applyAction(e,t){let n=this.cloneState(e);for(let[r,i]of Object.entries(t.effects))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)}}}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))}calculateHeuristic(e,t){let n=0;for(let[r,i]of Object.entries(t)){let s=this.getStateValue(e,r);if(typeof i=="object"&&i!==null&&"min"in i){let a=i.min;typeof s=="number"&&s<a&&(n+=(a-s)/100)}if(typeof i=="object"&&i!==null&&"max"in i){let a=i.max;typeof s=="number"&&s>a&&(n+=(s-a)/100)}typeof i=="object"&&i!==null&&"eq"in i&&s!==i.eq&&(n+=1),(typeof i=="string"||typeof i=="number"||typeof i=="boolean")&&s!==i&&(n+=1)}return n}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(".");for(let a of r)if(sl.has(a)){console.warn(`[GOAPPlanner] Blocked prototype pollution attempt: ${t}`);return}let i=e;for(let a=0;a<r.length-1;a++){let o=r[a];Object.hasOwn(i,o)||Object.defineProperty(i,o,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0});let u=Object.getOwnPropertyDescriptor(i,o);if(!u)return;i=u.value}let s=r[r.length-1];Object.defineProperty(i,s,{value:n,writable:!0,enumerable:!0,configurable:!0})}hashState(e){let t={coverageLine:Math.round(e.coverage.line),coverageBranch:Math.round(e.coverage.branch),coverageFunc:Math.round(e.coverage.function),coverageMeasured:e.coverage.measured,testsPassing:Math.round(e.quality.testsPassing),securityScore:Math.round(e.quality.securityScore),performanceScore:Math.round(e.quality.performanceScore),activeAgents:e.fleet.activeAgents,availableAgents:[...e.fleet.availableAgents].sort().join(","),timeRemaining:Math.floor(e.resources.timeRemaining/60),parallelSlots:e.resources.parallelSlots,environment:e.context.environment,riskLevel:e.context.riskLevel};return JSON.stringify(t)}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}}}getActionCost(e,t){let n=e.cost;return e.successRate<1&&(n=n/e.successRate),t.context.riskLevel==="high"&&(e.category==="performance"||e.category==="fleet")&&(n*=1.5),n}async loadActions(){let e=this.ensureDb().prepare("SELECT * FROM goap_actions ORDER BY category, cost").all();this.actions.clear();for(let t of e){let n={id:t.id,name:t.name,description:t.description??void 0,agentType:t.agent_type,preconditions:A(t.preconditions),effects:A(t.effects),cost:t.cost,estimatedDurationMs:t.estimated_duration_ms??void 0,successRate:t.success_rate,executionCount:t.execution_count,category:t.category,qeDomain:t.qe_domain};this.actions.set(n.id,n)}}async addAction(e){await this.initialize();let t=`action-${Date.now()}-${ye().slice(0,8)}`;this.ensureDb().prepare(`
617
617
  INSERT INTO goap_actions (
618
618
  id, name, description, agent_type, preconditions, effects,
619
619
  cost, estimated_duration_ms, success_rate, execution_count, category, qe_domain
@@ -643,7 +643,7 @@ Analyze the requirements above and return the complete QualityCriteriaAnalysis.`
643
643
  `).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}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()}-${ye().slice(0,8)}`;return this.ensureDb().prepare(`
644
644
  INSERT INTO goap_goals (id, name, description, conditions, priority, qe_domain)
645
645
  VALUES (?, ?, ?, ?, ?, ?)
646
- `).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:A(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}},hr=null;function ve(){return hr||(hr=new un),hr}$s();je();ie();M();H();import{randomUUID as yr}from"crypto";var Zc={maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,parallelExecution:!1,recordWorldState:!0,useUnified:!0},dn=class{db;planner;spawner;config;currentExecution=null;initialized=!1;unifiedMemory=null;constructor(e,t,n,r){this.planner=e,this.spawner=t,this.config={...Zc,...r},this.config.useUnified||(this.db=Ar(n??":memory:",{walMode:!1}),this.db.pragma("journal_mode = WAL"))}async initialize(){if(!this.initialized){if(this.config.useUnified)try{this.unifiedMemory=j(),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-MJNUEPYB.js")).default(":memory:"),this.db.pragma("journal_mode = WAL"),this.unifiedMemory=null,this.createTables()}else this.createTables();this.initialized=!0}}createTables(){this.db.exec(`
646
+ `).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:A(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}},vr=null;function ve(){return vr||(vr=new mn),vr}Vs();je();ie();k();H();import{randomUUID as Cr}from"crypto";var al={maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,parallelExecution:!1,recordWorldState:!0,useUnified:!0},pn=class{db;planner;spawner;config;currentExecution=null;initialized=!1;unifiedMemory=null;constructor(e,t,n,r){this.planner=e,this.spawner=t,this.config={...al,...r},this.config.useUnified||(this.db=Ir(n??":memory:",{walMode:!1}),this.db.pragma("journal_mode = WAL"))}async initialize(){if(!this.initialized){if(this.config.useUnified)try{this.unifiedMemory=j(),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-5JTP47LA.js")).default(":memory:"),this.db.pragma("journal_mode = WAL"),this.unifiedMemory=null,this.createTables()}else this.createTables();this.initialized=!0}}createTables(){this.db.exec(`
647
647
  CREATE TABLE IF NOT EXISTS execution_results (
648
648
  id TEXT PRIMARY KEY,
649
649
  plan_id TEXT NOT NULL,
@@ -678,7 +678,7 @@ Analyze the requirements above and return the complete QualityCriteriaAnalysis.`
678
678
  CREATE INDEX IF NOT EXISTS idx_exec_results_plan ON execution_results(plan_id);
679
679
  CREATE INDEX IF NOT EXISTS idx_exec_steps_execution ON executed_steps(execution_id);
680
680
  CREATE INDEX IF NOT EXISTS idx_exec_steps_action ON executed_steps(action_id);
681
- `)}async execute(e,t){return await this.initialize(),this.executeWithCallbacks(e,()=>{},()=>{},t)}async executeWithCallbacks(e,t,n,r){await this.initialize();let i=Date.now(),s=`exec-${Date.now()}-${yr().slice(0,8)}`;this.currentExecution={planId:e.id,cancelled:!1};let a={planId:e.id,status:"completed",stepsCompleted:0,stepsFailed:0,totalDurationMs:0,steps:[]},o=r?this.cloneState(r):this.cloneState(e.initialState),u=e.actions.map((l,d)=>({id:`step-${Date.now()}-${yr().slice(0,8)}`,planId:e.id,action:l,stepOrder:d,status:"pending"}));try{for(let l of u){if(this.currentExecution?.cancelled){a.status="cancelled",a.error="Execution was cancelled";break}this.config.recordWorldState&&(l.worldStateBefore=this.cloneState(o)),t(l);let d=!1,m,p=0,g,h,f=Date.now();for(let y=0;y<=this.config.maxRetries;y++){let C=await this.executeStep(l,o);if(C.success){d=!0,o=C.newState,g=C.output,h=C.agentId;break}m=C.error,p=y,y<this.config.maxRetries&&await this.delay(Math.min(1e3*Math.pow(2,y),5e3))}let v={...l,status:d?"completed":"failed",retries:p,startedAt:new Date(f),completedAt:new Date,durationMs:Date.now()-f,agentId:h,agentOutput:g,worldStateAfter:this.config.recordWorldState?this.cloneState(o):void 0,error:m};if(a.steps.push(v),n(v),d)a.stepsCompleted++,await this.updateActionStats(l.action.id,!0,v.durationMs??0);else if(a.stepsFailed++,await this.updateActionStats(l.action.id,!1,0),this.config.replanOnFailure){let y=await this.replanFromFailure(e,l.stepOrder,o);if(y){let C=await this.executeWithCallbacks(y,t,n,o);a.steps.push(...C.steps),a.stepsCompleted+=C.stepsCompleted,a.stepsFailed+=C.stepsFailed,C.status==="completed"&&C.finalWorldState?o=C.finalWorldState:(a.status="partial",a.error=`Replanning partially succeeded: ${C.error||"unknown error"}`)}else{a.status="failed",a.error=`Step ${l.stepOrder} failed and replanning unsuccessful: ${m}`;break}}else{a.status="failed",a.error=`Step ${l.stepOrder} failed: ${m}`;break}}return a.finalWorldState=o,a.totalDurationMs=Date.now()-i,await this.persistExecutionResult(s,a),a}finally{this.currentExecution=null}}async executeStep(e,t){let n=e.action;if(!this.meetsConditions(t,n.preconditions))return{success:!1,newState:t,error:`Preconditions not met for action: ${n.name}`};let r=this.buildTaskDescription(n);try{let i=new Promise((o,u)=>setTimeout(()=>u(new Error(`Step timeout after ${this.config.stepTimeoutMs}ms`)),this.config.stepTimeoutMs)),s=this.spawner.spawn(n.agentType,r),a=await Promise.race([s,i]);return a.success?{success:!0,newState:this.applyEffects(t,n.effects),output:a.output,agentId:a.agentId}:{success:!1,newState:t,agentId:a.agentId,error:a.error||"Agent execution failed"}}catch(i){return{success:!1,newState:t,error:E(i)}}}buildTaskDescription(e){let t=`Execute action: ${e.name}`;e.description&&(t+=`
681
+ `)}async execute(e,t){return await this.initialize(),this.executeWithCallbacks(e,()=>{},()=>{},t)}async executeWithCallbacks(e,t,n,r){await this.initialize();let i=Date.now(),s=`exec-${Date.now()}-${Cr().slice(0,8)}`;this.currentExecution={planId:e.id,cancelled:!1};let a={planId:e.id,status:"completed",stepsCompleted:0,stepsFailed:0,totalDurationMs:0,steps:[]},o=r?this.cloneState(r):this.cloneState(e.initialState),u=e.actions.map((l,d)=>({id:`step-${Date.now()}-${Cr().slice(0,8)}`,planId:e.id,action:l,stepOrder:d,status:"pending"}));try{for(let l of u){if(this.currentExecution?.cancelled){a.status="cancelled",a.error="Execution was cancelled";break}this.config.recordWorldState&&(l.worldStateBefore=this.cloneState(o)),t(l);let d=!1,m,p=0,g,h,f=Date.now();for(let y=0;y<=this.config.maxRetries;y++){let C=await this.executeStep(l,o);if(C.success){d=!0,o=C.newState,g=C.output,h=C.agentId;break}m=C.error,p=y,y<this.config.maxRetries&&await this.delay(Math.min(1e3*Math.pow(2,y),5e3))}let v={...l,status:d?"completed":"failed",retries:p,startedAt:new Date(f),completedAt:new Date,durationMs:Date.now()-f,agentId:h,agentOutput:g,worldStateAfter:this.config.recordWorldState?this.cloneState(o):void 0,error:m};if(a.steps.push(v),n(v),d)a.stepsCompleted++,await this.updateActionStats(l.action.id,!0,v.durationMs??0);else if(a.stepsFailed++,await this.updateActionStats(l.action.id,!1,0),this.config.replanOnFailure){let y=await this.replanFromFailure(e,l.stepOrder,o);if(y){let C=await this.executeWithCallbacks(y,t,n,o);a.steps.push(...C.steps),a.stepsCompleted+=C.stepsCompleted,a.stepsFailed+=C.stepsFailed,C.status==="completed"&&C.finalWorldState?o=C.finalWorldState:(a.status="partial",a.error=`Replanning partially succeeded: ${C.error||"unknown error"}`)}else{a.status="failed",a.error=`Step ${l.stepOrder} failed and replanning unsuccessful: ${m}`;break}}else{a.status="failed",a.error=`Step ${l.stepOrder} failed: ${m}`;break}}return a.finalWorldState=o,a.totalDurationMs=Date.now()-i,await this.persistExecutionResult(s,a),a}finally{this.currentExecution=null}}async executeStep(e,t){let n=e.action;if(!this.meetsConditions(t,n.preconditions))return{success:!1,newState:t,error:`Preconditions not met for action: ${n.name}`};let r=this.buildTaskDescription(n);try{let i=new Promise((o,u)=>setTimeout(()=>u(new Error(`Step timeout after ${this.config.stepTimeoutMs}ms`)),this.config.stepTimeoutMs)),s=this.spawner.spawn(n.agentType,r),a=await Promise.race([s,i]);return a.success?{success:!0,newState:this.applyEffects(t,n.effects),output:a.output,agentId:a.agentId}:{success:!1,newState:t,agentId:a.agentId,error:a.error||"Agent execution failed"}}catch(i){return{success:!1,newState:t,error:T(i)}}}buildTaskDescription(e){let t=`Execute action: ${e.name}`;e.description&&(t+=`
682
682
 
683
683
  Description: ${e.description}`),t+=`
684
684
 
@@ -696,4 +696,4 @@ Expected effects:`;for(let[n,r]of Object.entries(e.effects))typeof r=="object"&&
696
696
  retries, started_at, completed_at, duration_ms, agent_id,
697
697
  agent_output, world_state_before, world_state_after, error_message
698
698
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
699
- `);for(let r of t.steps)n.run(r.id,e,r.planId,r.action.id,r.stepOrder,r.status,r.retries,r.startedAt.toISOString(),r.completedAt?.toISOString()??null,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)}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 o of r)if(i.has(o)){console.warn(`[PlanExecutor] Blocked prototype pollution attempt: ${t}`);return}let s=e;for(let o=0;o<r.length-1;o++){let u=r[o];Object.hasOwn(s,u)||Object.defineProperty(s,u,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0});let l=Object.getOwnPropertyDescriptor(s,u);if(!l)return;s=l.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}},mn=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=te()<this.successRate,r=`mock-agent-${yr().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 nt(c,e){let t=new mn({successRate:e?.successRate??1});return new dn(c,t,e?.dbPath,e?.config)}var rt=class extends x{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"},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=ve(),await this.planner.initialize()),this.planner}resetInstanceCache(){this.planner=null}async execute(e,t){try{let n=await this.getPlanner(),r,i;if(typeof e.goal=="string"){let u=await n.getGoals(),l=u.find(d=>d.name===e.goal);if(!l){let d=u.map(m=>m.name).join(", ");return{success:!1,error:`Unknown goal: ${e.goal}. Available goals: ${d||"none (seed actions first)"}`}}r=l.conditions,i=l.name}else r=e.goal,i="custom";let s=e.currentState||await this.detectCurrentState(),a=e.constraints?{maxCost:e.constraints.maxCost,maxDurationMs:e.constraints.maxDurationMs,requiredAgentTypes:e.constraints.requiredAgentTypes,excludedActions:e.constraints.excludedActions}:void 0,o=await n.findPlan(s,r,a);return o?(this.markAsRealData(),{success:!0,data:{planId:o.id,goal:e.goal,actions:o.actions.map(u=>({name:u.name,agentType:u.agentType,cost:u.cost,category:u.category,description:u.description})),totalCost:o.totalCost,estimatedDurationMs:o.estimatedDurationMs,stepCount:o.actions.length,reusedFrom:o.reusedFrom,similarityScore:o.similarityScore}}):{success:!1,error:"No valid plan found for the given goal and constraints. Try relaxing constraints or seeding more actions."}}catch(n){return{success:!1,error:E(n)}}}async detectCurrentState(){return{...et}}};M();var it=class extends x{planner=null;executor=null;config={name:"qe/planning/goap_execute",description:"Execute a GOAP plan, spawning agents to perform each action step. Supports dry-run mode to simulate execution without actual agent spawning.",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=ve(),await this.planner.initialize()),this.planner}async getExecutor(){if(!this.executor){let e=await this.getPlanner();this.executor=nt(e,{successRate:.95,config:{maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,parallelExecution:!1,recordWorldState:!0}}),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((a,o)=>({action:a.name,status:"would-execute",retries:0,durationMs:a.estimatedDurationMs}))}};let i=await this.getExecutor();if(i.isExecuting())return{success:!1,error:"Another plan is currently executing. Wait for completion or cancel it."};let s=await i.execute(r,r.initialState);return this.markAsRealData(),{success:s.status==="completed",data:{planId:s.planId,mode:"execution",status:s.status,stepsCompleted:s.stepsCompleted,stepsFailed:s.stepsFailed,totalDurationMs:s.totalDurationMs,steps:s.steps.map(a=>({action:a.action.name,status:a.status,retries:a.retries,durationMs:a.durationMs,error:a.error})),error:s.error},error:s.status!=="completed"?s.error:void 0}}catch(n){return{success:!1,error:E(n)}}}};M();var st=class extends x{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)"},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=ve(),await this.planner.initialize()),this.planner}async getExecutor(){if(!this.executor){let e=await this.getPlanner();this.executor=nt(e),await this.executor.initialize()}return this.executor}resetInstanceCache(){this.planner=null,this.executor=null}async execute(e,t){try{switch(e.type){case"world":return this.getWorldState();case"goals":return this.getGoals();case"actions":return this.getActions(e.filter?.category,e.filter?.limit);case"plans":return this.getPlans(e.filter?.status,e.filter?.limit);case"execution":return this.getExecutionStatus();default:return{success:!1,error:`Unknown status type: ${e.type}`}}}catch(n){return{success:!1,error:E(n)}}}async getWorldState(){let e={...et};return this.markAsRealData(),{success:!0,data:{type:"world",data:{coverage:{line:e.coverage.line,branch:e.coverage.branch,function:e.coverage.function,measured:e.coverage.measured},quality:{testsPassing:e.quality.testsPassing,securityScore:e.quality.securityScore,performanceScore:e.quality.performanceScore},fleet:{activeAgents:e.fleet.activeAgents,maxAgents:e.fleet.maxAgents},resources:{timeRemaining:e.resources.timeRemaining,parallelSlots:e.resources.parallelSlots}}}}}async getGoals(){let t=await(await this.getPlanner()).getGoals();return this.markAsRealData(),{success:!0,data:{type:"goals",data:{goals:t.map(n=>({id:n.id,name:n.name,description:n.description,priority:n.priority,conditionCount:Object.keys(n.conditions).length})),count:t.length}}}}async getActions(e,t=50){let n=await this.getPlanner(),r=[],i=tt(),s=e?i.filter(o=>o.category===e):i;r=s.slice(0,t).map((o,u)=>({id:`action-${u}`,name:o.name,category:o.category,agentType:o.agentType,cost:o.cost,successRate:o.successRate}));let a={};for(let o of i)a[o.category]=(a[o.category]||0)+1;return this.markAsRealData(),{success:!0,data:{type:"actions",data:{actions:r,count:s.length,byCategory:a}}}}async getPlans(e,t=20){let r=await(await this.getPlanner()).getPlanReuseStats();return this.markAsRealData(),{success:!0,data:{type:"plans",data:{plans:[],count:0,reuseStats:{totalPlans:r.totalPlans,reusedPlans:r.reusedPlans,reuseRate:r.reuseRate,avgSuccessRate:r.avgSuccessRate}}}}}async getExecutionStatus(){let t=(await this.getExecutor()).isExecuting();return this.markAsRealData(),{success:!0,data:{type:"execution",data:{isExecuting:t,message:t?"Plan execution in progress":"No active execution"}}}}};M();je();ie();M();M();je();var at={HEALTH:"qe/mincut/health",ANALYZE:"qe/mincut/analyze",STRENGTHEN:"qe/mincut/strengthen"};function Tr(){return En()}function al(){return wn()}var vr=class extends x{config={name:at.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=Tr(),r=al(),i=ce();if(e.agents)for(let u of e.agents)n.hasVertex(u.id)||n.addVertex({id:u.id,type:"agent",domain:u.domain,weight:u.weight??1,createdAt:new Date});if(e.edges)for(let u of e.edges)n.hasVertex(u.source)&&n.hasVertex(u.target)&&(n.hasEdge(u.source,u.target)||n.addEdge({source:u.source,target:u.target,weight:u.weight??1,type:"coordination",bidirectional:!0}));let s=r.checkHealth(),a=e.includeWeakVertices!==!1?i.findWeakVertices(n):[],o={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&&(o.weakVertices=a.map(u=>({id:u.vertexId,domain:u.vertex?.domain,weightedDegree:u.weightedDegree,riskScore:u.riskScore,reason:u.reason}))),e.includeHistory&&(o.history=s.history.map(u=>({timestamp:u.timestamp,value:u.value}))),this.markAsRealData(),{success:!0,data:o,metadata:this.createMetadata(t.startTime,t.requestId)}}},br=class extends x{config={name:at.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=Tr(),r=ce(),i=r.getMinCutValue(n),s=r.getMinDegreeVertex(n),a=r.findWeakVertices(n,e.weaknessThreshold),o=r.suggestEdgeAdditions(n,2),u={minCutValue:i,minDegreeVertex:s,weakVertices:a.map(l=>({id:l.vertexId,weightedDegree:l.weightedDegree,riskScore:l.riskScore,reason:l.reason,suggestions:l.suggestions.map(d=>({type:d.type,priority:d.priority,estimatedImprovement:d.estimatedImprovement}))})),suggestedEdges:o.map(l=>({source:l.source,target:l.target,weight:l.weight}))};return e.includePartitioningPoints&&(u.partitioningPoints=r.findPartitioningPoints(n)),this.markAsRealData(),{success:!0,data:u,metadata:this.createMetadata(t.startTime,t.requestId)}}},Cr=class extends x{config={name:at.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=Tr(),r=ce(),i=r.getMinCutValue(n),s=e.targetImprovement??1,a=r.suggestEdgeAdditions(n,s),o=[];if(e.apply)for(let l of a)n.addEdge({source:l.source,target:l.target,weight:l.weight,type:"coordination",bidirectional:!0}),o.push({type:"add_edge",source:l.source,target:l.target,weight:l.weight});else for(let l of a)o.push({type:"add_edge",source:l.source,target:l.target,weight:l.weight});let u=r.getMinCutValue(n);return this.markAsRealData(),{success:!0,data:{beforeMinCut:i,afterMinCut:e.apply?u:i+s,improvement:e.apply?u-i:s,actionsApplied:o,applied:e.apply??!1},metadata:this.createMetadata(t.startTime,t.requestId)}}},Is=[new vr,new br,new Cr];M();var Sr=null,pn=null;async function ot(){return Sr||pn||(pn=(async()=>{let c=Dt({embedding:{model:"all-MiniLM-L6-v2",cacheSize:1e3,normalize:!0,hyperbolic:!1,curvature:-1},autoInitialize:!1});return await c.initialize(),Sr=c,console.error("[EmbeddingTool] ONNX adapter initialized"),c})(),pn)}var Le=class extends x{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 ot(),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)}`}}}},Ne=class extends x{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 ot(),i=e.metric||"cosine",s=i==="cosine"?"cosine":i==="euclidean"?"euclidean":"poincare",a=await r.compareSimilarity(e.text1,e.text2,s),o=performance.now()-n;return this.markAsRealData(),{success:!0,data:{similarity:a,metric:i,isSimilar:a>.7,latencyMs:o}}}catch(r){return{success:!1,error:`Similarity comparison failed: ${E(r)}`}}}},qe=class extends x{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 ot()).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)}`}}}},Ge=class extends x{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 ot(),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)}`}}}},$e=class extends x{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 ot(),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)}`}}}},ol=new Le,cl=new Ne,ll=new qe,ul=new Ge,dl=new $e;M();var ml={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"]},ct=class extends x{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:ml,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await le(ue)),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})),o=await s.checkCoherence(a),u=[...o.recommendations,...this.generateAdditionalRecommendations(o,i)],l=o.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:o.isCoherent,energy:o.energy,lane:o.lane,contradictions:l,recommendations:u,nodeCount:r.length,executionTimeMs:d,usedFallback:o.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}};xr();M();var D0=ft.create("qe-unified-memory");var pl={"test-suites":{dimensions:de.DIMENSIONS,M:8,efConstruction:100,efSearch:50,metric:"cosine",namespace:"test-suites-hnsw",maxElements:1e5},coverage:{dimensions:de.DIMENSIONS,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},defects:{dimensions:de.DIMENSIONS,M:32,efConstruction:400,efSearch:200,metric:"cosine",namespace:"defects-hnsw",maxElements:1e5},quality:{dimensions:de.DIMENSIONS,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"quality-hnsw",maxElements:1e5},learning:{dimensions:de.DIMENSIONS,M:24,efConstruction:300,efSearch:150,metric:"cosine",namespace:"learning-hnsw",maxElements:1e5},coordination:{dimensions:de.DIMENSIONS,M:8,efConstruction:100,efSearch:50,metric:"cosine",namespace:"coordination-hnsw",maxElements:5e4}},gl={enableHNSW:{"test-suites":!0,coverage:!0,defects:!0,quality:!0,learning:!0,coordination:!0},defaultNamespace:"qe-unified",enableCrossDomainSearch:!0,embeddingDimension:de.DIMENSIONS};xr();M();import{randomUUID as hl}from"crypto";var Er=ft.create("MemoryAuditor"),wr={batchSize:50,energyThreshold:.4,hotspotThreshold:.6,maxRecommendations:10},gn=class{constructor(e,t,n=wr){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 h=this.patternsToNodes(g),f=await this.coherenceService.checkCoherence(h);s+=f.energy,i+=f.contradictions.length,f.energy>this.config.hotspotThreshold&&r.push({domain:p,patternIds:g.map(v=>v.id),energy:f.energy,description:this.describeHotspot(f,p)})}let a=Object.keys(n).length,o=a>0?s/a:0,u=await this.identifyHotspots(e),l=await this.generateRecommendations(u,e),d=Date.now()-t,m={totalPatterns:e.length,scannedPatterns:e.length,contradictionCount:i,globalEnergy:o,hotspots:u,recommendations:l,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){Er.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(o=>o.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(l=>r.get(l)).filter(l=>l!==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 o=this.findOutdated(s);o.length>0&&n.push({type:"remove",patternIds:o,reason:`Found ${o.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 u=this.findBroadPatterns(s);u.length>0&&n.push({type:"split",patternIds:u,reason:`Found ${u.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){Er.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()}-${hl().split("-")[0]}`,type:e,source:"learning-optimization",timestamp:new Date,payload:t})}catch(n){Er.warn("Failed to emit event",{eventType:e,error:E(n)})}}};function Rr(c,e,t){return new gn(c,e,{...wr,...t})}M();var fl={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:[]},lt=class extends x{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:fl,streaming:!1,timeout:6e4};coherenceService=null;auditor=null;async getService(){return this.coherenceService||(this.coherenceService=await le(ue)),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=Rr(s,void 0,{energyThreshold:i,hotspotThreshold:i+.2,maxRecommendations:10}));let a=await L(),o=Sn(a,{namespace:n,embeddingDimension:384});await o.initialize();let u=await o.search("",{limit:r,useVectorSearch:!1}),l=u.success?u.value.map(p=>p.pattern):[],d;l.length>0?d=await this.auditor.auditPatterns(l):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))}};M();var yl={type:"object",properties:{votes:{type:"array",description:"Array of agent votes to verify for consensus"},confidenceThreshold:{type:"number",description:"Minimum confidence threshold (0-1, default: 0.5)",default:.5,minimum:0,maximum:1}},required:["votes"]},ut=class extends x{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:yl,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await le(ue)),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"};try{let s=await this.getService(),a=r.map(m=>({agentId:m.agentId,agentType:m.agentType||"worker",verdict:m.verdict,confidence:m.confidence,reasoning:m.reasoning,timestamp:new Date})),o=await s.verifyConsensus(a),u=o.recommendation,l=r.reduce((m,p)=>m+p.confidence,0)/r.length;l<i&&(u=`Low average confidence (${(l*100).toFixed(1)}%) - consider gathering more evidence. `+u);let d=Date.now()-n;return this.markAsRealData(),{success:!0,data:{isValid:o.isValid,isFalseConsensus:o.isFalseConsensus,confidence:o.confidence,fiedlerValue:o.fiedlerValue,collapseRisk:o.collapseRisk,recommendation:u,usedFallback:o.usedFallback,executionTimeMs:d}}}catch(s){if(s instanceof Error&&s.message.includes("WASM")){let a=this.simpleMajorityAnalysis(r);return this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{...a,recommendation:"Running in fallback mode (simple analysis). Install prime-radiant-advanced-wasm for spectral consensus analysis.",usedFallback:!0,executionTimeMs:Date.now()-n}}}return{success:!1,error:E(s)}}}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}}};M();var vl={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"]},dt=class extends x{config={name:"qe/coherence/collapse",description:"Predict swarm collapse risk using spectral analysis. Identifies vulnerable vertices and provides mitigation recommendations.",domain:"learning-optimization",schema:vl,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await le(ue)),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},o=await s.predictCollapse(a),u=Number.isFinite(o.risk)?o.risk:0,l=this.categorizeRisk(u),d=[...o.recommendations,...this.generateAdditionalRecommendations(o,r)],m=Date.now()-n;this.markAsRealData();let p=l==="high"||l==="critical"||l==="medium"&&u>=i;return{success:!0,data:{risk:u,isAtRisk:p,riskLevel:l,fiedlerValue:o.fiedlerValue,collapseImminent:o.collapseImminent,weakVertices:o.weakVertices,recommendations:d,executionTimeMs:m,usedFallback:o.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,o=Number.isFinite(e.pendingTasks)?e.pendingTasks:0,u=Number.isFinite(e.activeTasks)?e.activeTasks:0,l=e.agents.map(h=>Number.isFinite(h.health)?h.health:1),d=l.length>0?l.reduce((h,f)=>h+f,0)/l.length:1;n+=(1-d)*.3,n+=Math.min(.25,s*2.5),a>.7&&(n+=(a-.7)*.5);let m=o/Math.max(1,u);m>1&&(n+=Math.min(.2,(m-1)*.1)),e.agents.forEach((h,f)=>{(l[f]<.5||(h.errorCount??0)>5)&&i.push(h.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 Os=[new ct,new lt,new ut,new dt],_s={COHERENCE_CHECK:"qe/coherence/check",COHERENCE_AUDIT:"qe/coherence/audit",COHERENCE_CONSENSUS:"qe/coherence/consensus",COHERENCE_COLLAPSE:"qe/coherence/collapse"};var mt=(T=>(T.PROBLEM_UNDERSTANDING="H1.1-problem-understanding",T.RULE_OF_THREE="H1.2-rule-of-three",T.PROBLEM_COMPLEXITY="H1.3-problem-complexity",T.USER_NEEDS_IDENTIFICATION="H2.1-user-needs-identification",T.USER_NEEDS_SUITABILITY="H2.2-user-needs-suitability",T.USER_NEEDS_VALIDATION="H2.3-user-needs-validation",T.BUSINESS_NEEDS_IDENTIFICATION="H3.1-business-needs-identification",T.USER_VS_BUSINESS_BALANCE="H3.2-user-vs-business-balance",T.KPI_IMPACT_ANALYSIS="H3.3-kpi-impact-analysis",T.ORACLE_PROBLEM_DETECTION="H4.1-oracle-problem-detection",T.WHAT_MUST_NOT_CHANGE="H4.2-what-must-not-change",T.SUPPORTING_DATA_ANALYSIS="H4.3-supporting-data-analysis",T.GUI_FLOW_IMPACT="H5.1-gui-flow-impact",T.USER_FEELINGS_IMPACT="H5.2-user-feelings-impact",T.CROSS_FUNCTIONAL_IMPACT="H5.3-cross-functional-impact",T.DATA_DEPENDENT_IMPACT="H5.4-data-dependent-impact",T.COMPETITIVE_ANALYSIS="H6.1-competitive-analysis",T.DOMAIN_INSPIRATION="H6.2-domain-inspiration",T.INNOVATIVE_SOLUTIONS="H6.3-innovative-solutions",T.EXACTNESS_AND_CLARITY="H7.1-exactness-and-clarity",T.INTUITIVE_DESIGN="H7.2-intuitive-design",T.COUNTER_INTUITIVE_DESIGN="H7.3-counter-intuitive-design",T.CONSISTENCY_ANALYSIS="H7.4-consistency-analysis",T))(mt||{});var hn=class{enabledHeuristics;minConfidence;constructor(e={}){this.enabledHeuristics=e.enabledHeuristics||Object.values(mt),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=[],o=[],u=[],l=75;switch(e){case"H7.4-consistency-analysis":t.domMetrics?.semanticStructure?.hasHeader&&t.domMetrics?.semanticStructure?.hasFooter?(l=85,a.push("Consistent page structure with header and footer")):(l=60,u.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?(l=82,a.push("Intuitive navigation and interaction design")):(l=55,o.push({description:"Navigation or interaction patterns unclear",severity:"medium"}));break}case"H7.1-exactness-and-clarity":{l=70;let d=t.domMetrics?.semanticStructure,m=[d?.hasHeader,d?.hasMain,d?.hasNav,d?.hasFooter].filter(Boolean).length;l=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"),u.push("Add more semantic HTML5 elements for clarity")):(o.push({description:"Weak visual hierarchy - missing semantic structure",severity:"high"}),u.push("Implement semantic HTML5: header, nav, main, footer")),t.metadata?.description&&t.metadata.description.length>20&&(l+=10,a.push("Page has descriptive metadata"));break}case"H7.3-counter-intuitive-design":{l=85;let d=!t.domMetrics?.semanticStructure?.hasNav&&(t.domMetrics?.interactiveElements||0)>10,m=!t.domMetrics?.semanticStructure?.hasHeader&&!t.domMetrics?.semanticStructure?.hasFooter;d&&(l=45,o.push({description:"Navigation structure may be counter-intuitive",severity:"high"}),u.push("Add semantic navigation elements")),m&&(l-=15,o.push({description:"Page structure lacks expected header/footer",severity:"medium"})),l>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;l=60,d>=90?(l+=20,a.push("Excellent accessibility (90%+ alt coverage) creates inclusive, positive experience")):d>=70?(l+=12,a.push("Good accessibility creates generally positive user feelings")):d<50&&(l-=15,o.push({description:"Poor accessibility (<50% alt coverage) frustrates users with disabilities",severity:"high"}),u.push("Improve alt text coverage to at least 80% for better accessibility")),p>5&&(l+=8,a.push("Strong ARIA labeling enhances screen reader experience")),m<1500?(l+=15,a.push("Very fast load time (<1.5s) delights users")):m<2500?(l+=8,a.push("Fast load time enhances user satisfaction")):m>4e3?(l-=20,o.push({description:"Very slow load time (>4s) causes significant frustration",severity:"critical"}),u.push("Optimize page load time - target under 2.5 seconds")):m>3e3&&(l-=12,o.push({description:"Slow load time causes user frustration",severity:"high"})),t.errorIndicators?.hasErrorMessages&&(l-=12,o.push({description:"Visible errors reduce user confidence and satisfaction",severity:"high"}),u.push("Review and fix visible error messages")),g>20?(l+=5,a.push("Rich interactive elements provide user control and engagement")):g<5&&(l-=8,o.push({description:"Limited interactivity may feel restrictive",severity:"medium"})),l=Math.max(20,Math.min(100,l));break}case"H5.1-gui-flow-impact":{let d=t.domMetrics?.interactiveElements||0,m=t.domMetrics?.forms||0;d>20&&(l=75,a.push(`${d} interactive elements provide user control`)),m>0&&(a.push(`${m} forms impact user input flows`),l=Math.min(100,l+10)),d===0&&(l=30,o.push({description:"Limited user interaction capability",severity:"high"}));break}case"H5.3-cross-functional-impact":l=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"),l=70+a.length*5;break;case"H5.4-data-dependent-impact":t.domMetrics?.forms&&t.domMetrics.forms>0?(l=75,a.push(`${t.domMetrics.forms} forms depend on backend data processing`)):(l=50,a.push("Limited data-dependent features"));break;case"H1.1-problem-understanding":l=n.clarityScore,n.clarityScore>80?a.push("Problem is well-defined"):o.push({description:"Problem clarity needs improvement",severity:"medium"}),a.push(...n.breakdown);break;case"H1.2-rule-of-three":l=n.potentialFailures.length>=3?85:60,a.push(`${n.potentialFailures.length} potential failure modes identified`),n.potentialFailures.length<3&&u.push("Identify at least 3 potential failure modes (Rule of Three)");break;case"H1.3-problem-complexity":l=n.complexity==="simple"?90:n.complexity==="moderate"?75:60,a.push(`Problem complexity: ${n.complexity}`);break;case"H2.1-user-needs-identification":{l=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&&o.push({description:`${r.challenges.length} user need challenges found`,severity:"medium"});break}case"H2.2-user-needs-suitability":l=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;l=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":l=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);l=d,d>80?a.push("Good balance between user and business needs"):(o.push({description:"Imbalance between user and business priorities",severity:"medium"}),u.push("Align user and business objectives more closely"));break}case"H3.3-kpi-impact-analysis":l=i.impactsKPIs?85:50,a.push(`KPIs impacted: ${i.kpisAffected.join(", ")}`),i.compromisesUX&&(o.push({description:"Business ease compromises user experience",severity:"high"}),l-=20);break;case"H4.1-oracle-problem-detection":l=75,a.push("Oracle problem detection capability active");break;case"H4.2-what-must-not-change":l=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":{l=75,(t.domMetrics?.forms||0)>0||(t.domMetrics?.interactiveElements||0)>20?(l=82,a.push("Sufficient data points for informed decision-making")):(l=60,o.push({description:"Limited data for comprehensive analysis",severity:"medium"}),u.push("Collect more user interaction data"));break}case"H6.1-competitive-analysis":l=70,a.push("Competitive analysis capability available"),t.domMetrics?.semanticStructure?.hasNav&&t.domMetrics?.interactiveElements&&t.domMetrics.interactiveElements>15?(l=78,a.push("Navigation and interaction patterns follow industry standards")):u.push("Compare interaction patterns with leading competitors");break;case"H6.2-domain-inspiration":{l=72,t.accessibility&&(t.accessibility.ariaLabelsCount||0)>0?(l=80,a.push("Modern accessibility patterns show domain inspiration")):u.push("Research domain-specific design patterns and best practices");break}case"H6.3-innovative-solutions":{l=65,(t.accessibility?.landmarkRoles||0)>3?(l=75,a.push("Advanced accessibility features show innovative thinking")):u.push("Explore innovative UX patterns to differentiate experience");break}default:s==="user-needs"?l=r.alignmentScore:s==="business-needs"?l=i.alignmentScore:s==="problem"&&(l=n.clarityScore);break}return{id:e,name:this.getHeuristicName(e),category:s,applied:!0,score:Math.min(100,Math.max(0,l)),findings:a,issues:o,recommendations:u}}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 fn=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 yn=class c{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),o=this.analyzeImmutableRequirements(e,t),u=this.calculateVisibleScore(n,i),l=this.calculateInvisibleScore(s,a),d=Math.round((u+l)/2);return{visible:{guiFlow:{forEndUser:n,forInternalUser:r},userFeelings:i,score:u},invisible:{performance:s,security:a,score:l},immutableRequirements:o,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 c.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 c.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 c.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))}};M();var bl={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"]},pt=class extends x{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:bl,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:o=!0,includeDesign:u=!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 l=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,l);this.emitStream(t,{status:"analyzing",phase:"business-needs"});let m=this.analyzeBusinessNeeds(r,l);this.emitStream(t,{status:"analyzing",phase:"creativity"});let p=o?this.analyzeCreativity(r,l):this.createMinimalCreativityAnalysis();this.emitStream(t,{status:"analyzing",phase:"design"});let g=u?this.analyzeDesign(r):this.createMinimalDesignAnalysis();this.emitStream(t,{status:"analyzing",phase:"oracle-detection"});let f=new fn(a).detect(r,d,m);this.emitStream(t,{status:"analyzing",phase:"impact-analysis"});let y=new yn().analyze(r,l);this.emitStream(t,{status:"analyzing",phase:"heuristics",count:23});let b=await new hn({enabledHeuristics:s||Object.values(mt)}).applyAll(r,l,d,m);this.emitStream(t,{status:"analyzing",phase:"recommendations"});let w=this.generateRecommendations(l,d,m,f,y,b),S=this.calculateOverallScore(l,d,m,p,g,y,b),T=this.scoreToGrade(S),P={overallScore:S,grade:T,timestamp:new Date().toISOString(),target:n,problemAnalysis:l,userNeeds:d,businessNeeds:m,creativityAnalysis:p,designAnalysis:g,oracleProblems:f,impactAnalysis:y,heuristics:b,recommendations:w,context:r};return this.emitStream(t,{status:"complete",score:S,grade:T,heuristicsApplied:b.length,oracleProblemsFound:f.length}),{success:!0,data:P,metadata:this.createMetadata(t.startTime,t.requestId)}}catch(l){return{success:!1,error:`QX analysis failed: ${E(l)}`}}}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,o=e.domMetrics?.forms||0,u;s>500||a>50||o>3?u="complex":s>200||a>20||o>1?u="moderate":u="simple";let l=[];e.domMetrics?.semanticStructure?.hasNav&&l.push("Navigation structure"),o>0&&l.push(`Form interactions (${o} forms)`),a>0&&l.push(`User interactions (${a} elements)`),e.accessibility&&l.push("Accessibility compliance"),e.performance&&l.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;)u==="complex"?d.push({description:"Complex interaction flows may confuse first-time users",severity:"medium",likelihood:"possible"}):u==="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),l.length>=3&&(p+=10),e.domMetrics?.semanticStructure?.hasMain&&(p+=10),p=Math.min(100,p),{problemStatement:i,complexity:u,breakdown:l,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,o=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}),o>0&&n.push({description:"Form interactions for user input",priority:"nice-to-have",addressed:!0});let u=n.filter(m=>m.priority==="must-have"&&m.addressed).length,l;r.length===0&&u>=3?l="excellent":r.length<=1&&u>=2?l="good":r.length<=2&&u>=2?l="adequate":l="poor";let d=40;return d+=u*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:l,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,o=[];n>2?(a="business-ease",o=["Form completion rate","Lead generation","User sign-ups"]):r>30?(a="user-experience",o=["Time on site","Click-through rate","User engagement"]):(a="balanced",o=["Content consumption","Bounce rate","Page views"]);let u=(e.title||"").toLowerCase();(u.includes("health")||u.includes("care"))&&o.push("Patient satisfaction","Appointment completion rate","Information accessibility");let l=[];n>0&&(l.push({team:"Marketing",impactType:"positive",description:"Form conversion optimization needed"}),l.push({team:"Development",impactType:"neutral",description:"Form validation and submission handling"})),e.accessibility&&(e.accessibility.altTextsCoverage||0)<100&&l.push({team:"Content",impactType:"negative",description:"Image alt text creation required"}),i&&(i.loadTime||0)>2e3&&l.push({team:"Engineering",impactType:"negative",description:"Performance optimization needed"}),t.complexity==="complex"&&l.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 o.length>0&&(m+=15),l.length>0&&(m+=10),d||(m+=20),m=Math.min(100,m),{primaryGoal:a,kpisAffected:o,crossTeamImpact:l,compromisesUX:d,impactsKPIs:o.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",o=[],u=[],l=!0;e.domMetrics?.semanticStructure?.hasNav&&o.push("Standard navigation placement"),e.domMetrics?.semanticStructure?.hasHeader&&o.push("Header follows common layout conventions"),!e.domMetrics?.semanticStructure?.hasNav&&i>10&&(l=!1,u.push("Non-standard navigation pattern may confuse users from different regions"));let d=50+o.length*15;l||(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:l,intuitivePatterns:o,culturalIssues:u,score:d},counterIntuitive:{deviations:[],innovativeJustification:!1,freshEyesPerspective:!0,issuesCount:0},overallDesignScore:m}}generateRecommendations(e,t,n,r,i,s){let a=[],o=1;for(let u of s){for(let l of u.issues)(l.severity==="critical"||l.severity==="high")&&a.push({principle:u.name,recommendation:l.description,severity:l.severity,impact:l.severity==="critical"?90:75,effort:"medium",priority:o++,category:"qx"});for(let l of u.recommendations)a.push({principle:u.name,recommendation:l,severity:"medium",impact:60,effort:"medium",priority:o++,category:"qx"})}for(let u of r)a.push({principle:`Oracle: ${u.type}`,recommendation:u.description,severity:u.severity,impact:u.severity==="critical"?95:u.severity==="high"?80:60,effort:"high",priority:o++,category:"process",evidence:u.resolutionApproach});for(let u of t.challenges)a.push({principle:"User Needs",recommendation:u,severity:"medium",impact:65,effort:"medium",priority:o++,category:"ux"});return a.sort((u,l)=>{let d={critical:0,high:1,medium:2,low:3},m=d[u.severity]-d[l.severity];return m!==0?m:l.impact-u.impact}).slice(0,15)}calculateOverallScore(e,t,n,r,i,s,a){let o=a.reduce((l,d)=>l+d.score,0)/a.length||0,u=e.clarityScore*.1+t.alignmentScore*.2+n.alignmentScore*.15+r.creativityScore*.1+i.overallDesignScore*.15+(100-s.overallImpactScore)*.1+o*.2;return Math.round(Math.max(0,Math.min(100,u)))}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}}},ew=new pt;var Rw={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",DEFECT_PREDICT:"qe/defects/predict",REQUIREMENTS_VALIDATE:"qe/requirements/validate",QUALITY_CRITERIA:"qe/requirements/quality-criteria",CODE_ANALYZE:"qe/code/analyze",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",...at,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",..._s,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"},Cl=[new Ht,new Vt,new Wt,new Kt,new Xt,new Jt,new Zt,new Ye,new tn,new nn,new rn,new sn,new an,new on,new Je,new Ze,new cn,new rt,new it,new st,...Is,new Le,new Ne,new qe,new Ge,new $e,...Os,new pt,new ci,new li,new ui,new di];function Fs(){for(let c of Cl)c.resetInstanceCache()}M();var Ls=Cn.filter(c=>c!=="coordination"),R={fleetId:null,kernel:null,queen:null,router:null,workflowOrchestrator:null,initialized:!1,initTime:null,topology:"hierarchical",agentLevels:new Map};function We(){return R}function Oe(){return R.initialized&&R.kernel!==null&&R.queen!==null}function $w(c){return Oe()||(R.fleetId=`fleet-${N().slice(0,8)}`,R.kernel=c.kernel,R.queen=c.queen,R.router=c.router??null,R.workflowOrchestrator=c.workflowOrchestrator??null,R.initialized=!0,R.initTime=new Date,R.topology=c.topology??"hierarchical",R.agentLevels.clear()),R.fleetId}function zw(){return R.topology}function Bw(c,e){if(R.topology!=="hierarchical"){let i={agentId:c,domain:e,level:"worker",spawnedAt:new Date};return R.agentLevels.set(c,i),"worker"}let n=Array.from(R.agentLevels.values()).find(i=>i.domain===e&&i.level==="lead")?"worker":"lead",r={agentId:c,domain:e,level:n,spawnedAt:new Date};return R.agentLevels.set(c,r),n}function jw(c){return R.agentLevels.get(c)}function Uw(){return R.agentLevels}async function Hw(c){try{if(R.initialized&&R.kernel&&R.queen)return{success:!0,data:{fleetId:R.fleetId,topology:c.topology||"hierarchical",maxAgents:c.maxAgents||15,enabledDomains:c.enabledDomains||Ls,status:"ready"}};R.fleetId=`fleet-${N().slice(0,8)}`;let e=c.enabledDomains||[...Cn],t=e.filter(u=>u!=="coordination"),n=process.env.AQE_MEMORY_BACKEND==="memory"?"memory":c.memoryBackend||"hybrid";R.kernel=new ti({maxConcurrentAgents:c.maxAgents||15,memoryBackend:n,hnswEnabled:!0,lazyLoading:c.lazyLoading!==!1,enabledDomains:e}),await R.kernel.initialize(),R.router=new ni(R.kernel.eventBus),await R.router.initialize();let r=u=>R.kernel.getDomainAPI(u),i=new ri(R.kernel.eventBus,R.kernel.memory,r),s=R.kernel.plugins;await s.loadAll();let a=new Map;for(let u of s.getLoaded()){let l=s.getPlugin(u);l&&a.set(u,l)}try{let{getDaemon:u}=await import("./daemon-IVWUMQKL.js"),l=u().getWorkerManager();l.setKernel(R.kernel),l.setMemory(R.kernel.memory)}catch(u){console.warn(`[fleet_init] Daemon worker manager wiring skipped: ${E(u)}`)}R.queen=ii(R.kernel,R.router,i,void 0,a),await R.queen.initialize(),R.workflowOrchestrator=new ei(R.kernel.eventBus,R.kernel.memory,R.kernel.coordinator),await R.workflowOrchestrator.initialize(),Tl(R.kernel,R.workflowOrchestrator);let{subscribeTrajectoryEvents:o}=await import("./task-handlers-GDHNJV2E.js");return o(R.router),R.initialized=!0,R.initTime=new Date,R.topology=c.topology||"hierarchical",R.agentLevels.clear(),{success:!0,data:{fleetId:R.fleetId,topology:R.topology,maxAgents:c.maxAgents||15,enabledDomains:t,status:"initialized"}}}catch(e){return{success:!1,error:`Failed to initialize fleet: ${E(e)}`}}}async function Vw(c){if(!Oe())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(c.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 o of i)s+=1+o.teammateIds.length,r.getTeamHealth(o.domain)?.healthy&&a++;n.teams={active:i.length,totalAgentsInTeams:s,healthyCount:a}}c.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-MQA72NLP.js"),s=i();if(s.isInitialized()){let a=u=>{try{return s.queryCount(u)}catch{return 0}},o=await s.vectorCount();n.learning={totalPatterns:a("qe_patterns"),totalExperiences:a("captured_experiences"),totalTrajectories:a("qe_trajectories"),vectorCount:o,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 Qw(c){if(!Oe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{if(c.domain){let n=R.queen.getDomainHealth(c.domain);return n?{success:!0,data:{domain:c.domain,status:n.status,agents:n.agents,errors:n.errors,lastActivity:n.lastActivity?.toISOString()}}:{success:!1,error:`Domain not found: ${c.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(c.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-B2GHENWX.js"),r=new n,i=[];for(let[o]of e.domainHealth){let u=R.queen.getAgentsByDomain(o);for(let l of u)i.push({id:l.id,name:l.name,domain:l.domain})}let s=i.map(o=>({id:o.id,name:o.name,domain:o.domain,capabilities:[o.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 Ww(){if(_i(),us(),Fs(),R.workflowOrchestrator&&(await R.workflowOrchestrator.dispose(),R.workflowOrchestrator=null),R.queen&&(await R.queen.dispose(),R.queen=null),R.router){try{let{unsubscribeTrajectoryEvents:c}=await import("./task-handlers-GDHNJV2E.js");c(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 Kw(){let c=performance.now();try{let e=Oe(),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 l=R.kernel.memory;try{n.connected=!0;let d=await l.count("default"),m=await l.count("learning"),p=await l.count("patterns");n.totalEntries=d+m+p;let g=0;for(let h of["default","learning","patterns","mcp-tools","coordination"])await l.count(h)>0&&g++;n.namespaces=g}catch{}try{let d=process.env.AQE_V3_HNSW_ENABLED==="true";r.enabled=d;let m=l;d&&typeof m.vectorCount=="function"&&(r.vectorCount=await m.vectorCount())}catch{}try{i=(await l.search("pattern:*",1e3)).length}catch{}}let s=e&&R.kernel?(R.kernel.getLoadedDomains?.()??Ls).length:0,a=null;try{let{getSharedRvfDualWriterSync:l}=await import("./shared-rvf-dual-writer-DBQJHG42.js"),d=l();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 o=null;try{let{SQLitePatternStore:l}=await import("./sqlite-persistence-7DHUFTHL.js"),d=new l;await d.initialize(),o=d.getGhostPatternCount(),d.close()}catch{}return{success:!0,data:{status:e?"healthy":"unhealthy",version:"3.11.1",loadedDomains:s,memory:n,hnsw:r,rvf:a??void 0,ghostPatterns:o??void 0,loadedPatterns:i,uptimeMs:t,timestamp:new Date().toISOString()},metadata:{executionTime:performance.now()-c,timestamp:new Date().toISOString(),requestId:N(),toolName:"aqe_health"}}}catch(e){return{success:!1,error:E(e),metadata:{executionTime:performance.now()-c,timestamp:new Date().toISOString(),requestId:N(),toolName:"aqe_health"}}}}function Tl(c,e){let t=c.getDomainAPI("requirements-validation");t?.registerWorkflowActions&&(t.registerWorkflowActions(e),console.log("[Fleet] Registered requirements-validation workflow actions (includes QCSD Ideation)"));let n=c.getDomainAPI("visual-accessibility");n?.registerWorkflowActions&&(n.registerWorkflowActions(e),console.log("[Fleet] Registered visual-accessibility workflow actions"))}export{du as a,Gt as b,We as c,Oe as d,$w as e,zw as f,Bw as g,jw as h,Uw as i,Hw as j,Vw as k,Qw as l,Ww as m,Kw as n};
699
+ `);for(let r of t.steps)n.run(r.id,e,r.planId,r.action.id,r.stepOrder,r.status,r.retries,r.startedAt.toISOString(),r.completedAt?.toISOString()??null,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)}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 o of r)if(i.has(o)){console.warn(`[PlanExecutor] Blocked prototype pollution attempt: ${t}`);return}let s=e;for(let o=0;o<r.length-1;o++){let u=r[o];Object.hasOwn(s,u)||Object.defineProperty(s,u,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0});let l=Object.getOwnPropertyDescriptor(s,u);if(!l)return;s=l.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}},gn=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=te()<this.successRate,r=`mock-agent-${Cr().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 nt(c,e){let t=new gn({successRate:e?.successRate??1});return new pn(c,t,e?.dbPath,e?.config)}var rt=class extends P{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"},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=ve(),await this.planner.initialize()),this.planner}resetInstanceCache(){this.planner=null}async execute(e,t){try{let n=await this.getPlanner(),r,i;if(typeof e.goal=="string"){let u=await n.getGoals(),l=u.find(d=>d.name===e.goal);if(!l){let d=u.map(m=>m.name).join(", ");return{success:!1,error:`Unknown goal: ${e.goal}. Available goals: ${d||"none (seed actions first)"}`}}r=l.conditions,i=l.name}else r=e.goal,i="custom";let s=e.currentState||await this.detectCurrentState(),a=e.constraints?{maxCost:e.constraints.maxCost,maxDurationMs:e.constraints.maxDurationMs,requiredAgentTypes:e.constraints.requiredAgentTypes,excludedActions:e.constraints.excludedActions}:void 0,o=await n.findPlan(s,r,a);return o?(this.markAsRealData(),{success:!0,data:{planId:o.id,goal:e.goal,actions:o.actions.map(u=>({name:u.name,agentType:u.agentType,cost:u.cost,category:u.category,description:u.description})),totalCost:o.totalCost,estimatedDurationMs:o.estimatedDurationMs,stepCount:o.actions.length,reusedFrom:o.reusedFrom,similarityScore:o.similarityScore}}):{success:!1,error:"No valid plan found for the given goal and constraints. Try relaxing constraints or seeding more actions."}}catch(n){return{success:!1,error:T(n)}}}async detectCurrentState(){return{...et}}};k();var it=class extends P{planner=null;executor=null;config={name:"qe/planning/goap_execute",description:"Execute a GOAP plan, spawning agents to perform each action step. Supports dry-run mode to simulate execution without actual agent spawning.",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=ve(),await this.planner.initialize()),this.planner}async getExecutor(){if(!this.executor){let e=await this.getPlanner();this.executor=nt(e,{successRate:.95,config:{maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,parallelExecution:!1,recordWorldState:!0}}),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((a,o)=>({action:a.name,status:"would-execute",retries:0,durationMs:a.estimatedDurationMs}))}};let i=await this.getExecutor();if(i.isExecuting())return{success:!1,error:"Another plan is currently executing. Wait for completion or cancel it."};let s=await i.execute(r,r.initialState);return this.markAsRealData(),{success:s.status==="completed",data:{planId:s.planId,mode:"execution",status:s.status,stepsCompleted:s.stepsCompleted,stepsFailed:s.stepsFailed,totalDurationMs:s.totalDurationMs,steps:s.steps.map(a=>({action:a.action.name,status:a.status,retries:a.retries,durationMs:a.durationMs,error:a.error})),error:s.error},error:s.status!=="completed"?s.error:void 0}}catch(n){return{success:!1,error:T(n)}}}};k();var st=class extends P{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)"},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=ve(),await this.planner.initialize()),this.planner}async getExecutor(){if(!this.executor){let e=await this.getPlanner();this.executor=nt(e),await this.executor.initialize()}return this.executor}resetInstanceCache(){this.planner=null,this.executor=null}async execute(e,t){try{switch(e.type){case"world":return this.getWorldState();case"goals":return this.getGoals();case"actions":return this.getActions(e.filter?.category,e.filter?.limit);case"plans":return this.getPlans(e.filter?.status,e.filter?.limit);case"execution":return this.getExecutionStatus();default:return{success:!1,error:`Unknown status type: ${e.type}`}}}catch(n){return{success:!1,error:T(n)}}}async getWorldState(){let e={...et};return this.markAsRealData(),{success:!0,data:{type:"world",data:{coverage:{line:e.coverage.line,branch:e.coverage.branch,function:e.coverage.function,measured:e.coverage.measured},quality:{testsPassing:e.quality.testsPassing,securityScore:e.quality.securityScore,performanceScore:e.quality.performanceScore},fleet:{activeAgents:e.fleet.activeAgents,maxAgents:e.fleet.maxAgents},resources:{timeRemaining:e.resources.timeRemaining,parallelSlots:e.resources.parallelSlots}}}}}async getGoals(){let t=await(await this.getPlanner()).getGoals();return this.markAsRealData(),{success:!0,data:{type:"goals",data:{goals:t.map(n=>({id:n.id,name:n.name,description:n.description,priority:n.priority,conditionCount:Object.keys(n.conditions).length})),count:t.length}}}}async getActions(e,t=50){let n=await this.getPlanner(),r=[],i=tt(),s=e?i.filter(o=>o.category===e):i;r=s.slice(0,t).map((o,u)=>({id:`action-${u}`,name:o.name,category:o.category,agentType:o.agentType,cost:o.cost,successRate:o.successRate}));let a={};for(let o of i)a[o.category]=(a[o.category]||0)+1;return this.markAsRealData(),{success:!0,data:{type:"actions",data:{actions:r,count:s.length,byCategory:a}}}}async getPlans(e,t=20){let r=await(await this.getPlanner()).getPlanReuseStats();return this.markAsRealData(),{success:!0,data:{type:"plans",data:{plans:[],count:0,reuseStats:{totalPlans:r.totalPlans,reusedPlans:r.reusedPlans,reuseRate:r.reuseRate,avgSuccessRate:r.avgSuccessRate}}}}}async getExecutionStatus(){let t=(await this.getExecutor()).isExecuting();return this.markAsRealData(),{success:!0,data:{type:"execution",data:{isExecuting:t,message:t?"Plan execution in progress":"No active execution"}}}}};k();je();ie();k();k();je();var at={HEALTH:"qe/mincut/health",ANALYZE:"qe/mincut/analyze",STRENGTHEN:"qe/mincut/strengthen"};function wr(){return Rn()}function pl(){return Pn()}var Tr=class extends P{config={name:at.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=wr(),r=pl(),i=ce();if(e.agents)for(let u of e.agents)n.hasVertex(u.id)||n.addVertex({id:u.id,type:"agent",domain:u.domain,weight:u.weight??1,createdAt:new Date});if(e.edges)for(let u of e.edges)n.hasVertex(u.source)&&n.hasVertex(u.target)&&(n.hasEdge(u.source,u.target)||n.addEdge({source:u.source,target:u.target,weight:u.weight??1,type:"coordination",bidirectional:!0}));let s=r.checkHealth(),a=e.includeWeakVertices!==!1?i.findWeakVertices(n):[],o={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&&(o.weakVertices=a.map(u=>({id:u.vertexId,domain:u.vertex?.domain,weightedDegree:u.weightedDegree,riskScore:u.riskScore,reason:u.reason}))),e.includeHistory&&(o.history=s.history.map(u=>({timestamp:u.timestamp,value:u.value}))),this.markAsRealData(),{success:!0,data:o,metadata:this.createMetadata(t.startTime,t.requestId)}}},Sr=class extends P{config={name:at.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=wr(),r=ce(),i=r.getMinCutValue(n),s=r.getMinDegreeVertex(n),a=r.findWeakVertices(n,e.weaknessThreshold),o=r.suggestEdgeAdditions(n,2),u={minCutValue:i,minDegreeVertex:s,weakVertices:a.map(l=>({id:l.vertexId,weightedDegree:l.weightedDegree,riskScore:l.riskScore,reason:l.reason,suggestions:l.suggestions.map(d=>({type:d.type,priority:d.priority,estimatedImprovement:d.estimatedImprovement}))})),suggestedEdges:o.map(l=>({source:l.source,target:l.target,weight:l.weight}))};return e.includePartitioningPoints&&(u.partitioningPoints=r.findPartitioningPoints(n)),this.markAsRealData(),{success:!0,data:u,metadata:this.createMetadata(t.startTime,t.requestId)}}},Er=class extends P{config={name:at.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=wr(),r=ce(),i=r.getMinCutValue(n),s=e.targetImprovement??1,a=r.suggestEdgeAdditions(n,s),o=[];if(e.apply)for(let l of a)n.addEdge({source:l.source,target:l.target,weight:l.weight,type:"coordination",bidirectional:!0}),o.push({type:"add_edge",source:l.source,target:l.target,weight:l.weight});else for(let l of a)o.push({type:"add_edge",source:l.source,target:l.target,weight:l.weight});let u=r.getMinCutValue(n);return this.markAsRealData(),{success:!0,data:{beforeMinCut:i,afterMinCut:e.apply?u:i+s,improvement:e.apply?u-i:s,actionsApplied:o,applied:e.apply??!1},metadata:this.createMetadata(t.startTime,t.requestId)}}},qs=[new Tr,new Sr,new Er];k();var Rr=null,hn=null;async function ot(){return Rr||hn||(hn=(async()=>{let c=It({embedding:{model:"all-MiniLM-L6-v2",cacheSize:1e3,normalize:!0,hyperbolic:!1,curvature:-1},autoInitialize:!1});return await c.initialize(),Rr=c,console.error("[EmbeddingTool] ONNX adapter initialized"),c})(),hn)}var Le=class extends P{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 ot(),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: ${T(r)}`}}}},Ne=class extends P{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 ot(),i=e.metric||"cosine",s=i==="cosine"?"cosine":i==="euclidean"?"euclidean":"poincare",a=await r.compareSimilarity(e.text1,e.text2,s),o=performance.now()-n;return this.markAsRealData(),{success:!0,data:{similarity:a,metric:i,isSimilar:a>.7,latencyMs:o}}}catch(r){return{success:!1,error:`Similarity comparison failed: ${T(r)}`}}}},qe=class extends P{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 ot()).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: ${T(r)}`}}}},Ge=class extends P{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 ot(),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: ${T(r)}`}}}},$e=class extends P{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 ot(),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: ${T(n)}`}}}},gl=new Le,hl=new Ne,fl=new qe,yl=new Ge,vl=new $e;k();var bl={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"]},ct=class extends P{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:bl,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await le(ue)),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})),o=await s.checkCoherence(a),u=[...o.recommendations,...this.generateAdditionalRecommendations(o,i)],l=o.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:o.isCoherent,energy:o.energy,lane:o.lane,contradictions:l,recommendations:u,nodeCount:r.length,executionTimeMs:d,usedFallback:o.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:T(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}};Dr();k();var K0=ft.create("qe-unified-memory");var Cl={"test-suites":{dimensions:de.DIMENSIONS,M:8,efConstruction:100,efSearch:50,metric:"cosine",namespace:"test-suites-hnsw",maxElements:1e5},coverage:{dimensions:de.DIMENSIONS,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},defects:{dimensions:de.DIMENSIONS,M:32,efConstruction:400,efSearch:200,metric:"cosine",namespace:"defects-hnsw",maxElements:1e5},quality:{dimensions:de.DIMENSIONS,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"quality-hnsw",maxElements:1e5},learning:{dimensions:de.DIMENSIONS,M:24,efConstruction:300,efSearch:150,metric:"cosine",namespace:"learning-hnsw",maxElements:1e5},coordination:{dimensions:de.DIMENSIONS,M:8,efConstruction:100,efSearch:50,metric:"cosine",namespace:"coordination-hnsw",maxElements:5e4}},Tl={enableHNSW:{"test-suites":!0,coverage:!0,defects:!0,quality:!0,learning:!0,coordination:!0},defaultNamespace:"qe-unified",enableCrossDomainSearch:!0,embeddingDimension:de.DIMENSIONS};Dr();k();import{randomUUID as Sl}from"crypto";var Pr=ft.create("MemoryAuditor"),xr={batchSize:50,energyThreshold:.4,hotspotThreshold:.6,maxRecommendations:10},fn=class{constructor(e,t,n=xr){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 h=this.patternsToNodes(g),f=await this.coherenceService.checkCoherence(h);s+=f.energy,i+=f.contradictions.length,f.energy>this.config.hotspotThreshold&&r.push({domain:p,patternIds:g.map(v=>v.id),energy:f.energy,description:this.describeHotspot(f,p)})}let a=Object.keys(n).length,o=a>0?s/a:0,u=await this.identifyHotspots(e),l=await this.generateRecommendations(u,e),d=Date.now()-t,m={totalPatterns:e.length,scannedPatterns:e.length,contradictionCount:i,globalEnergy:o,hotspots:u,recommendations:l,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:T(n),timestamp:new Date})}catch(r){Pr.warn("Failed to emit audit_failed event",{error:T(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(o=>o.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(l=>r.get(l)).filter(l=>l!==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 o=this.findOutdated(s);o.length>0&&n.push({type:"remove",patternIds:o,reason:`Found ${o.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 u=this.findBroadPatterns(s);u.length>0&&n.push({type:"split",patternIds:u,reason:`Found ${u.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){Pr.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:T(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()}-${Sl().split("-")[0]}`,type:e,source:"learning-optimization",timestamp:new Date,payload:t})}catch(n){Pr.warn("Failed to emit event",{eventType:e,error:T(n)})}}};function Ar(c,e,t){return new fn(c,e,{...xr,...t})}k();var El={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:[]},lt=class extends P{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:El,streaming:!1,timeout:6e4};coherenceService=null;auditor=null;async getService(){return this.coherenceService||(this.coherenceService=await le(ue)),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=Ar(s,void 0,{energyThreshold:i,hotspotThreshold:i+.2,maxRecommendations:10}));let a=await F(),o=wn(a,{namespace:n,embeddingDimension:384});await o.initialize();let u=await o.search("",{limit:r,useVectorSearch:!1}),l=u.success?u.value.map(p=>p.pattern):[],d;l.length>0?d=await this.auditor.auditPatterns(l):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:T(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();var wl={type:"object",properties:{votes:{type:"array",description:"Array of agent votes to verify for consensus"},confidenceThreshold:{type:"number",description:"Minimum confidence threshold (0-1, default: 0.5)",default:.5,minimum:0,maximum:1}},required:["votes"]},ut=class extends P{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:wl,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await le(ue)),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"};try{let s=await this.getService(),a=r.map(m=>({agentId:m.agentId,agentType:m.agentType||"worker",verdict:m.verdict,confidence:m.confidence,reasoning:m.reasoning,timestamp:new Date})),o=await s.verifyConsensus(a),u=o.recommendation,l=r.reduce((m,p)=>m+p.confidence,0)/r.length;l<i&&(u=`Low average confidence (${(l*100).toFixed(1)}%) - consider gathering more evidence. `+u);let d=Date.now()-n;return this.markAsRealData(),{success:!0,data:{isValid:o.isValid,isFalseConsensus:o.isFalseConsensus,confidence:o.confidence,fiedlerValue:o.fiedlerValue,collapseRisk:o.collapseRisk,recommendation:u,usedFallback:o.usedFallback,executionTimeMs:d}}}catch(s){if(s instanceof Error&&s.message.includes("WASM")){let a=this.simpleMajorityAnalysis(r);return this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{...a,recommendation:"Running in fallback mode (simple analysis). Install prime-radiant-advanced-wasm for spectral consensus analysis.",usedFallback:!0,executionTimeMs:Date.now()-n}}}return{success:!1,error:T(s)}}}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 Rl={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"]},dt=class extends P{config={name:"qe/coherence/collapse",description:"Predict swarm collapse risk using spectral analysis. Identifies vulnerable vertices and provides mitigation recommendations.",domain:"learning-optimization",schema:Rl,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await le(ue)),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},o=await s.predictCollapse(a),u=Number.isFinite(o.risk)?o.risk:0,l=this.categorizeRisk(u),d=[...o.recommendations,...this.generateAdditionalRecommendations(o,r)],m=Date.now()-n;this.markAsRealData();let p=l==="high"||l==="critical"||l==="medium"&&u>=i;return{success:!0,data:{risk:u,isAtRisk:p,riskLevel:l,fiedlerValue:o.fiedlerValue,collapseImminent:o.collapseImminent,weakVertices:o.weakVertices,recommendations:d,executionTimeMs:m,usedFallback:o.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:T(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,o=Number.isFinite(e.pendingTasks)?e.pendingTasks:0,u=Number.isFinite(e.activeTasks)?e.activeTasks:0,l=e.agents.map(h=>Number.isFinite(h.health)?h.health:1),d=l.length>0?l.reduce((h,f)=>h+f,0)/l.length:1;n+=(1-d)*.3,n+=Math.min(.25,s*2.5),a>.7&&(n+=(a-.7)*.5);let m=o/Math.max(1,u);m>1&&(n+=Math.min(.2,(m-1)*.1)),e.agents.forEach((h,f)=>{(l[f]<.5||(h.errorCount??0)>5)&&i.push(h.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 Gs=[new ct,new lt,new ut,new dt],$s={COHERENCE_CHECK:"qe/coherence/check",COHERENCE_AUDIT:"qe/coherence/audit",COHERENCE_CONSENSUS:"qe/coherence/consensus",COHERENCE_COLLAPSE:"qe/coherence/collapse"};var mt=(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))(mt||{});var yn=class{enabledHeuristics;minConfidence;constructor(e={}){this.enabledHeuristics=e.enabledHeuristics||Object.values(mt),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=[],o=[],u=[],l=75;switch(e){case"H7.4-consistency-analysis":t.domMetrics?.semanticStructure?.hasHeader&&t.domMetrics?.semanticStructure?.hasFooter?(l=85,a.push("Consistent page structure with header and footer")):(l=60,u.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?(l=82,a.push("Intuitive navigation and interaction design")):(l=55,o.push({description:"Navigation or interaction patterns unclear",severity:"medium"}));break}case"H7.1-exactness-and-clarity":{l=70;let d=t.domMetrics?.semanticStructure,m=[d?.hasHeader,d?.hasMain,d?.hasNav,d?.hasFooter].filter(Boolean).length;l=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"),u.push("Add more semantic HTML5 elements for clarity")):(o.push({description:"Weak visual hierarchy - missing semantic structure",severity:"high"}),u.push("Implement semantic HTML5: header, nav, main, footer")),t.metadata?.description&&t.metadata.description.length>20&&(l+=10,a.push("Page has descriptive metadata"));break}case"H7.3-counter-intuitive-design":{l=85;let d=!t.domMetrics?.semanticStructure?.hasNav&&(t.domMetrics?.interactiveElements||0)>10,m=!t.domMetrics?.semanticStructure?.hasHeader&&!t.domMetrics?.semanticStructure?.hasFooter;d&&(l=45,o.push({description:"Navigation structure may be counter-intuitive",severity:"high"}),u.push("Add semantic navigation elements")),m&&(l-=15,o.push({description:"Page structure lacks expected header/footer",severity:"medium"})),l>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;l=60,d>=90?(l+=20,a.push("Excellent accessibility (90%+ alt coverage) creates inclusive, positive experience")):d>=70?(l+=12,a.push("Good accessibility creates generally positive user feelings")):d<50&&(l-=15,o.push({description:"Poor accessibility (<50% alt coverage) frustrates users with disabilities",severity:"high"}),u.push("Improve alt text coverage to at least 80% for better accessibility")),p>5&&(l+=8,a.push("Strong ARIA labeling enhances screen reader experience")),m<1500?(l+=15,a.push("Very fast load time (<1.5s) delights users")):m<2500?(l+=8,a.push("Fast load time enhances user satisfaction")):m>4e3?(l-=20,o.push({description:"Very slow load time (>4s) causes significant frustration",severity:"critical"}),u.push("Optimize page load time - target under 2.5 seconds")):m>3e3&&(l-=12,o.push({description:"Slow load time causes user frustration",severity:"high"})),t.errorIndicators?.hasErrorMessages&&(l-=12,o.push({description:"Visible errors reduce user confidence and satisfaction",severity:"high"}),u.push("Review and fix visible error messages")),g>20?(l+=5,a.push("Rich interactive elements provide user control and engagement")):g<5&&(l-=8,o.push({description:"Limited interactivity may feel restrictive",severity:"medium"})),l=Math.max(20,Math.min(100,l));break}case"H5.1-gui-flow-impact":{let d=t.domMetrics?.interactiveElements||0,m=t.domMetrics?.forms||0;d>20&&(l=75,a.push(`${d} interactive elements provide user control`)),m>0&&(a.push(`${m} forms impact user input flows`),l=Math.min(100,l+10)),d===0&&(l=30,o.push({description:"Limited user interaction capability",severity:"high"}));break}case"H5.3-cross-functional-impact":l=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"),l=70+a.length*5;break;case"H5.4-data-dependent-impact":t.domMetrics?.forms&&t.domMetrics.forms>0?(l=75,a.push(`${t.domMetrics.forms} forms depend on backend data processing`)):(l=50,a.push("Limited data-dependent features"));break;case"H1.1-problem-understanding":l=n.clarityScore,n.clarityScore>80?a.push("Problem is well-defined"):o.push({description:"Problem clarity needs improvement",severity:"medium"}),a.push(...n.breakdown);break;case"H1.2-rule-of-three":l=n.potentialFailures.length>=3?85:60,a.push(`${n.potentialFailures.length} potential failure modes identified`),n.potentialFailures.length<3&&u.push("Identify at least 3 potential failure modes (Rule of Three)");break;case"H1.3-problem-complexity":l=n.complexity==="simple"?90:n.complexity==="moderate"?75:60,a.push(`Problem complexity: ${n.complexity}`);break;case"H2.1-user-needs-identification":{l=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&&o.push({description:`${r.challenges.length} user need challenges found`,severity:"medium"});break}case"H2.2-user-needs-suitability":l=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;l=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":l=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);l=d,d>80?a.push("Good balance between user and business needs"):(o.push({description:"Imbalance between user and business priorities",severity:"medium"}),u.push("Align user and business objectives more closely"));break}case"H3.3-kpi-impact-analysis":l=i.impactsKPIs?85:50,a.push(`KPIs impacted: ${i.kpisAffected.join(", ")}`),i.compromisesUX&&(o.push({description:"Business ease compromises user experience",severity:"high"}),l-=20);break;case"H4.1-oracle-problem-detection":l=75,a.push("Oracle problem detection capability active");break;case"H4.2-what-must-not-change":l=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":{l=75,(t.domMetrics?.forms||0)>0||(t.domMetrics?.interactiveElements||0)>20?(l=82,a.push("Sufficient data points for informed decision-making")):(l=60,o.push({description:"Limited data for comprehensive analysis",severity:"medium"}),u.push("Collect more user interaction data"));break}case"H6.1-competitive-analysis":l=70,a.push("Competitive analysis capability available"),t.domMetrics?.semanticStructure?.hasNav&&t.domMetrics?.interactiveElements&&t.domMetrics.interactiveElements>15?(l=78,a.push("Navigation and interaction patterns follow industry standards")):u.push("Compare interaction patterns with leading competitors");break;case"H6.2-domain-inspiration":{l=72,t.accessibility&&(t.accessibility.ariaLabelsCount||0)>0?(l=80,a.push("Modern accessibility patterns show domain inspiration")):u.push("Research domain-specific design patterns and best practices");break}case"H6.3-innovative-solutions":{l=65,(t.accessibility?.landmarkRoles||0)>3?(l=75,a.push("Advanced accessibility features show innovative thinking")):u.push("Explore innovative UX patterns to differentiate experience");break}default:s==="user-needs"?l=r.alignmentScore:s==="business-needs"?l=i.alignmentScore:s==="problem"&&(l=n.clarityScore);break}return{id:e,name:this.getHeuristicName(e),category:s,applied:!0,score:Math.min(100,Math.max(0,l)),findings:a,issues:o,recommendations:u}}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 vn=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 bn=class c{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),o=this.analyzeImmutableRequirements(e,t),u=this.calculateVisibleScore(n,i),l=this.calculateInvisibleScore(s,a),d=Math.round((u+l)/2);return{visible:{guiFlow:{forEndUser:n,forInternalUser:r},userFeelings:i,score:u},invisible:{performance:s,security:a,score:l},immutableRequirements:o,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 c.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 c.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 c.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 Pl={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"]},pt=class extends P{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:Pl,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:o=!0,includeDesign:u=!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 l=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,l);this.emitStream(t,{status:"analyzing",phase:"business-needs"});let m=this.analyzeBusinessNeeds(r,l);this.emitStream(t,{status:"analyzing",phase:"creativity"});let p=o?this.analyzeCreativity(r,l):this.createMinimalCreativityAnalysis();this.emitStream(t,{status:"analyzing",phase:"design"});let g=u?this.analyzeDesign(r):this.createMinimalDesignAnalysis();this.emitStream(t,{status:"analyzing",phase:"oracle-detection"});let f=new vn(a).detect(r,d,m);this.emitStream(t,{status:"analyzing",phase:"impact-analysis"});let y=new bn().analyze(r,l);this.emitStream(t,{status:"analyzing",phase:"heuristics",count:23});let b=await new yn({enabledHeuristics:s||Object.values(mt)}).applyAll(r,l,d,m);this.emitStream(t,{status:"analyzing",phase:"recommendations"});let w=this.generateRecommendations(l,d,m,f,y,b),E=this.calculateOverallScore(l,d,m,p,g,y,b),S=this.scoreToGrade(E),x={overallScore:E,grade:S,timestamp:new Date().toISOString(),target:n,problemAnalysis:l,userNeeds:d,businessNeeds:m,creativityAnalysis:p,designAnalysis:g,oracleProblems:f,impactAnalysis:y,heuristics:b,recommendations:w,context:r};return this.emitStream(t,{status:"complete",score:E,grade:S,heuristicsApplied:b.length,oracleProblemsFound:f.length}),{success:!0,data:x,metadata:this.createMetadata(t.startTime,t.requestId)}}catch(l){return{success:!1,error:`QX analysis failed: ${T(l)}`}}}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,o=e.domMetrics?.forms||0,u;s>500||a>50||o>3?u="complex":s>200||a>20||o>1?u="moderate":u="simple";let l=[];e.domMetrics?.semanticStructure?.hasNav&&l.push("Navigation structure"),o>0&&l.push(`Form interactions (${o} forms)`),a>0&&l.push(`User interactions (${a} elements)`),e.accessibility&&l.push("Accessibility compliance"),e.performance&&l.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;)u==="complex"?d.push({description:"Complex interaction flows may confuse first-time users",severity:"medium",likelihood:"possible"}):u==="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),l.length>=3&&(p+=10),e.domMetrics?.semanticStructure?.hasMain&&(p+=10),p=Math.min(100,p),{problemStatement:i,complexity:u,breakdown:l,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,o=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}),o>0&&n.push({description:"Form interactions for user input",priority:"nice-to-have",addressed:!0});let u=n.filter(m=>m.priority==="must-have"&&m.addressed).length,l;r.length===0&&u>=3?l="excellent":r.length<=1&&u>=2?l="good":r.length<=2&&u>=2?l="adequate":l="poor";let d=40;return d+=u*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:l,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,o=[];n>2?(a="business-ease",o=["Form completion rate","Lead generation","User sign-ups"]):r>30?(a="user-experience",o=["Time on site","Click-through rate","User engagement"]):(a="balanced",o=["Content consumption","Bounce rate","Page views"]);let u=(e.title||"").toLowerCase();(u.includes("health")||u.includes("care"))&&o.push("Patient satisfaction","Appointment completion rate","Information accessibility");let l=[];n>0&&(l.push({team:"Marketing",impactType:"positive",description:"Form conversion optimization needed"}),l.push({team:"Development",impactType:"neutral",description:"Form validation and submission handling"})),e.accessibility&&(e.accessibility.altTextsCoverage||0)<100&&l.push({team:"Content",impactType:"negative",description:"Image alt text creation required"}),i&&(i.loadTime||0)>2e3&&l.push({team:"Engineering",impactType:"negative",description:"Performance optimization needed"}),t.complexity==="complex"&&l.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 o.length>0&&(m+=15),l.length>0&&(m+=10),d||(m+=20),m=Math.min(100,m),{primaryGoal:a,kpisAffected:o,crossTeamImpact:l,compromisesUX:d,impactsKPIs:o.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",o=[],u=[],l=!0;e.domMetrics?.semanticStructure?.hasNav&&o.push("Standard navigation placement"),e.domMetrics?.semanticStructure?.hasHeader&&o.push("Header follows common layout conventions"),!e.domMetrics?.semanticStructure?.hasNav&&i>10&&(l=!1,u.push("Non-standard navigation pattern may confuse users from different regions"));let d=50+o.length*15;l||(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:l,intuitivePatterns:o,culturalIssues:u,score:d},counterIntuitive:{deviations:[],innovativeJustification:!1,freshEyesPerspective:!0,issuesCount:0},overallDesignScore:m}}generateRecommendations(e,t,n,r,i,s){let a=[],o=1;for(let u of s){for(let l of u.issues)(l.severity==="critical"||l.severity==="high")&&a.push({principle:u.name,recommendation:l.description,severity:l.severity,impact:l.severity==="critical"?90:75,effort:"medium",priority:o++,category:"qx"});for(let l of u.recommendations)a.push({principle:u.name,recommendation:l,severity:"medium",impact:60,effort:"medium",priority:o++,category:"qx"})}for(let u of r)a.push({principle:`Oracle: ${u.type}`,recommendation:u.description,severity:u.severity,impact:u.severity==="critical"?95:u.severity==="high"?80:60,effort:"high",priority:o++,category:"process",evidence:u.resolutionApproach});for(let u of t.challenges)a.push({principle:"User Needs",recommendation:u,severity:"medium",impact:65,effort:"medium",priority:o++,category:"ux"});return a.sort((u,l)=>{let d={critical:0,high:1,medium:2,low:3},m=d[u.severity]-d[l.severity];return m!==0?m:l.impact-u.impact}).slice(0,15)}calculateOverallScore(e,t,n,r,i,s,a){let o=a.reduce((l,d)=>l+d.score,0)/a.length||0,u=e.clarityScore*.1+t.alignmentScore*.2+n.alignmentScore*.15+r.creativityScore*.1+i.overallDesignScore*.15+(100-s.overallImpactScore)*.1+o*.2;return Math.round(Math.max(0,Math.min(100,u)))}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}}},vw=new pt;var Uw={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",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",...at,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",...$s,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"},xl=[new Vt,new Qt,new Kt,new Xt,new Yt,new Zt,new en,new Ye,new nn,new rn,new sn,new an,new on,new cn,new ln,new Je,new Ze,new un,new rt,new it,new st,...qs,new Le,new Ne,new qe,new Ge,new $e,...Gs,new pt,new gi,new hi,new fi,new yi];function zs(){for(let c of xl)c.resetInstanceCache()}k();var Bs=Sn.filter(c=>c!=="coordination"),R={fleetId:null,kernel:null,queen:null,router:null,workflowOrchestrator:null,initialized:!1,initTime:null,topology:"hierarchical",agentLevels:new Map};function We(){return R}function Oe(){return R.initialized&&R.kernel!==null&&R.queen!==null}function sR(c){return Oe()||(R.fleetId=`fleet-${N().slice(0,8)}`,R.kernel=c.kernel,R.queen=c.queen,R.router=c.router??null,R.workflowOrchestrator=c.workflowOrchestrator??null,R.initialized=!0,R.initTime=new Date,R.topology=c.topology??"hierarchical",R.agentLevels.clear()),R.fleetId}function aR(){return R.topology}function oR(c,e){if(R.topology!=="hierarchical"){let i={agentId:c,domain:e,level:"worker",spawnedAt:new Date};return R.agentLevels.set(c,i),"worker"}let n=Array.from(R.agentLevels.values()).find(i=>i.domain===e&&i.level==="lead")?"worker":"lead",r={agentId:c,domain:e,level:n,spawnedAt:new Date};return R.agentLevels.set(c,r),n}function cR(c){return R.agentLevels.get(c)}function lR(){return R.agentLevels}async function uR(c){try{if(R.initialized&&R.kernel&&R.queen)return{success:!0,data:{fleetId:R.fleetId,topology:c.topology||"hierarchical",maxAgents:c.maxAgents||15,enabledDomains:c.enabledDomains||Bs,status:"ready"}};R.fleetId=`fleet-${N().slice(0,8)}`;let e=c.enabledDomains||[...Sn],t=e.filter(u=>u!=="coordination"),n=process.env.AQE_MEMORY_BACKEND==="memory"?"memory":c.memoryBackend||"hybrid";R.kernel=new oi({maxConcurrentAgents:c.maxAgents||15,memoryBackend:n,hnswEnabled:!0,lazyLoading:c.lazyLoading!==!1,enabledDomains:e}),await R.kernel.initialize(),R.router=new ci(R.kernel.eventBus),await R.router.initialize();let r=u=>R.kernel.getDomainAPI(u),i=new li(R.kernel.eventBus,R.kernel.memory,r),s=R.kernel.plugins;await s.loadAll();let a=new Map;for(let u of s.getLoaded()){let l=s.getPlugin(u);l&&a.set(u,l)}try{let{getDaemon:u}=await import("./daemon-IYDTMA5M.js"),l=u().getWorkerManager();l.setKernel(R.kernel),l.setMemory(R.kernel.memory)}catch(u){console.warn(`[fleet_init] Daemon worker manager wiring skipped: ${T(u)}`)}R.queen=ui(R.kernel,R.router,i,void 0,a),await R.queen.initialize(),R.workflowOrchestrator=new ai(R.kernel.eventBus,R.kernel.memory,R.kernel.coordinator),await R.workflowOrchestrator.initialize(),Al(R.kernel,R.workflowOrchestrator);let{subscribeTrajectoryEvents:o}=await import("./task-handlers-I6YJXPYP.js");return o(R.router),R.initialized=!0,R.initTime=new Date,R.topology=c.topology||"hierarchical",R.agentLevels.clear(),{success:!0,data:{fleetId:R.fleetId,topology:R.topology,maxAgents:c.maxAgents||15,enabledDomains:t,status:"initialized"}}}catch(e){return{success:!1,error:`Failed to initialize fleet: ${T(e)}`}}}async function dR(c){if(!Oe())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(c.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 o of i)s+=1+o.teammateIds.length,r.getTeamHealth(o.domain)?.healthy&&a++;n.teams={active:i.length,totalAgentsInTeams:s,healthyCount:a}}c.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-HCKOPFAY.js"),s=i();if(s.isInitialized()){let a=u=>{try{return s.queryCount(u)}catch{return 0}},o=await s.vectorCount();n.learning={totalPatterns:a("qe_patterns"),totalExperiences:a("captured_experiences"),totalTrajectories:a("qe_trajectories"),vectorCount:o,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: ${T(e)}`}}}async function mR(c){if(!Oe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{if(c.domain){let n=R.queen.getDomainHealth(c.domain);return n?{success:!0,data:{domain:c.domain,status:n.status,agents:n.agents,errors:n.errors,lastActivity:n.lastActivity?.toISOString()}}:{success:!1,error:`Domain not found: ${c.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(c.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-2VPPIOZX.js"),r=new n,i=[];for(let[o]of e.domainHealth){let u=R.queen.getAgentsByDomain(o);for(let l of u)i.push({id:l.id,name:l.name,domain:l.domain})}let s=i.map(o=>({id:o.id,name:o.name,domain:o.domain,capabilities:[o.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: ${T(e)}`}}}async function pR(){if($i(),fs(),zs(),R.workflowOrchestrator&&(await R.workflowOrchestrator.dispose(),R.workflowOrchestrator=null),R.queen&&(await R.queen.dispose(),R.queen=null),R.router){try{let{unsubscribeTrajectoryEvents:c}=await import("./task-handlers-I6YJXPYP.js");c(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 gR(){let c=performance.now();try{let e=Oe(),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 l=R.kernel.memory;try{n.connected=!0;let d=await l.count("default"),m=await l.count("learning"),p=await l.count("patterns");n.totalEntries=d+m+p;let g=0;for(let h of["default","learning","patterns","mcp-tools","coordination"])await l.count(h)>0&&g++;n.namespaces=g}catch{}try{let d=process.env.AQE_V3_HNSW_ENABLED==="true";r.enabled=d;let m=l;d&&typeof m.vectorCount=="function"&&(r.vectorCount=await m.vectorCount())}catch{}try{i=(await l.search("pattern:*",1e3)).length}catch{}}let s=e&&R.kernel?(R.kernel.getLoadedDomains?.()??Bs).length:0,a=null;try{let{getSharedRvfDualWriterSync:l}=await import("./shared-rvf-dual-writer-INQDY5WE.js"),d=l();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 o=null;try{let{SQLitePatternStore:l}=await import("./sqlite-persistence-5Z2RAXH7.js"),d=new l;await d.initialize(),o=d.getGhostPatternCount(),d.close()}catch{}return{success:!0,data:{status:e?"healthy":"unhealthy",version:"3.11.2",loadedDomains:s,memory:n,hnsw:r,rvf:a??void 0,ghostPatterns:o??void 0,loadedPatterns:i,uptimeMs:t,timestamp:new Date().toISOString()},metadata:{executionTime:performance.now()-c,timestamp:new Date().toISOString(),requestId:N(),toolName:"aqe_health"}}}catch(e){return{success:!1,error:T(e),metadata:{executionTime:performance.now()-c,timestamp:new Date().toISOString(),requestId:N(),toolName:"aqe_health"}}}}function Al(c,e){let t=c.getDomainAPI("requirements-validation");t?.registerWorkflowActions&&(t.registerWorkflowActions(e),console.log("[Fleet] Registered requirements-validation workflow actions (includes QCSD Ideation)"));let n=c.getDomainAPI("visual-accessibility");n?.registerWorkflowActions&&(n.registerWorkflowActions(e),console.log("[Fleet] Registered visual-accessibility workflow actions"))}export{vu as a,$t as b,We as c,Oe as d,sR as e,aR as f,oR as g,cR as h,lR as i,uR as j,dR as k,mR as l,pR as m,gR as n};