agentic-qe 3.14.0 → 3.14.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 (430) hide show
  1. package/.claude/helpers/brain-checkpoint.cjs +2 -1
  2. package/.claude/helpers/validate-v3-config.sh +6 -5
  3. package/.claude/hooks/aqe-hook.cjs +14 -14
  4. package/.claude/skills/qe-browser/evals/qe-browser.yaml +30 -41
  5. package/.claude/skills/qe-browser/fixtures/serve-skills.js +37 -0
  6. package/.claude/skills/qe-browser/scripts/lib/vibium.js +1 -1
  7. package/.claude/skills/qe-browser/scripts/smoke-test.sh +56 -25
  8. package/.claude/skills/qe-browser/scripts/visual-diff.js +24 -15
  9. package/.claude/skills/skills-manifest.json +1 -1
  10. package/CHANGELOG.md +114 -0
  11. package/assets/skills/qe-browser/evals/qe-browser.yaml +30 -41
  12. package/assets/skills/qe-browser/fixtures/serve-skills.js +37 -0
  13. package/assets/skills/qe-browser/scripts/lib/vibium.js +1 -1
  14. package/assets/skills/qe-browser/scripts/smoke-test.sh +56 -25
  15. package/assets/skills/qe-browser/scripts/visual-diff.js +24 -15
  16. package/assets/skills/skills-manifest.json +1 -1
  17. package/dist/cli/bundle.js +7 -7
  18. package/dist/cli/chunks/adapter-OJF6LAJV.js +2 -0
  19. package/dist/cli/chunks/{agent-booster-wasm-JZO6VUW4.js → agent-booster-wasm-SD5N32MX.js} +2 -2
  20. package/dist/cli/chunks/{agent-handler-534KFGEJ.js → agent-handler-OZRSJM7F.js} +2 -2
  21. package/dist/cli/chunks/{agent-memory-branch-B7KWLWY4.js → agent-memory-branch-NYTRANRN.js} +2 -2
  22. package/dist/cli/chunks/aqe-learning-engine-FGT474XB.js +2 -0
  23. package/dist/cli/chunks/{arena-OW5MELJX.js → arena-EX3SC2DP.js} +4 -4
  24. package/dist/cli/chunks/{arena-7CCD3S3I.js → arena-FOTVSRK4.js} +2 -2
  25. package/dist/cli/chunks/{audit-BHVKN4E2.js → audit-Q5GHSUQY.js} +3 -3
  26. package/dist/cli/chunks/base-HH765JFV.js +2 -0
  27. package/dist/cli/chunks/{better-sqlite3-P5FA6WFK.js → better-sqlite3-S7M5R2HS.js} +2 -2
  28. package/dist/cli/chunks/{brain-handler-WNW5LOV7.js → brain-handler-5FSA46R5.js} +3 -3
  29. package/dist/cli/chunks/{branch-enumerator-TVZ2ODKH.js → branch-enumerator-RWAXTGEU.js} +2 -2
  30. package/dist/cli/chunks/{browser-TCEB2W2F.js → browser-IGDESJGF.js} +2 -2
  31. package/dist/cli/chunks/browser-workflow-NPM4FUPI.js +2 -0
  32. package/dist/cli/chunks/{chunk-Q73RRTLE.js → chunk-2EHFEMRU.js} +2 -2
  33. package/dist/cli/chunks/{chunk-ZBOWR4XT.js → chunk-2H5YJ5ZK.js} +2 -2
  34. package/dist/cli/chunks/chunk-2LKAMMMI.js +2 -0
  35. package/dist/cli/chunks/{chunk-A2WZEMWT.js → chunk-2TG24LYQ.js} +1 -1
  36. package/dist/cli/chunks/{chunk-3QT6S3A3.js → chunk-3C2K4YMS.js} +3 -3
  37. package/dist/cli/chunks/{chunk-VESOYP6A.js → chunk-3DFFFXXO.js} +2 -2
  38. package/dist/cli/chunks/{chunk-K6CGQR5R.js → chunk-3WV4H33V.js} +1 -1
  39. package/dist/cli/chunks/{chunk-IL4AEB3J.js → chunk-42WUDDUU.js} +2 -2
  40. package/dist/cli/chunks/chunk-4AKGBUYD.js +4 -0
  41. package/dist/cli/chunks/{chunk-4FEJEVG7.js → chunk-4K27ESCA.js} +1 -1
  42. package/dist/cli/chunks/{chunk-TGOGCA74.js → chunk-4M6A3PVJ.js} +2 -2
  43. package/dist/cli/chunks/{chunk-RGVD6ZUX.js → chunk-4MH22236.js} +1 -1
  44. package/dist/cli/chunks/{chunk-6DPAMYLU.js → chunk-4N44UJGI.js} +2 -2
  45. package/dist/cli/chunks/{chunk-DJITEQYS.js → chunk-4PH7O5ZH.js} +2 -2
  46. package/dist/cli/chunks/{chunk-M3HUZD2I.js → chunk-4RT7I7PI.js} +1 -1
  47. package/dist/cli/chunks/chunk-4UCMTYFQ.js +65 -0
  48. package/dist/cli/chunks/{chunk-ZI3UO7QR.js → chunk-4ZUZDFAA.js} +2 -2
  49. package/dist/cli/chunks/{chunk-QSPRQPEL.js → chunk-57TNBR2P.js} +2 -2
  50. package/dist/cli/chunks/{chunk-ZCVJCCQQ.js → chunk-5EHLGOWW.js} +2 -2
  51. package/dist/cli/chunks/{chunk-ZAAYOENS.js → chunk-5WJUNRTY.js} +2 -2
  52. package/dist/cli/chunks/{chunk-QZPFUFZG.js → chunk-67A6PEZM.js} +2 -2
  53. package/dist/cli/chunks/{chunk-7BOPFN3Y.js → chunk-6EHN7Q2Q.js} +2 -2
  54. package/dist/cli/chunks/{chunk-2HYVOX6N.js → chunk-6F4WHN7D.js} +1 -1
  55. package/dist/cli/chunks/{chunk-GVEJP5T7.js → chunk-6LMLN5R2.js} +2 -2
  56. package/dist/cli/chunks/{chunk-QKQZ4IJF.js → chunk-6SZKLWZT.js} +5 -5
  57. package/dist/cli/chunks/{chunk-PEW6FZ47.js → chunk-6VKJAMZY.js} +1 -1
  58. package/dist/cli/chunks/{chunk-VYENTZ45.js → chunk-7AFBNU6K.js} +2 -2
  59. package/dist/cli/chunks/{chunk-6IJMD2ZL.js → chunk-7FWP7CZY.js} +3 -3
  60. package/dist/cli/chunks/{chunk-IE5LC7MB.js → chunk-7SK6IMGZ.js} +2 -2
  61. package/dist/cli/chunks/{chunk-3EM2MK3Z.js → chunk-A7N3YUDJ.js} +2 -2
  62. package/dist/cli/chunks/{chunk-J3XSHJGK.js → chunk-ADK7DF3G.js} +2 -2
  63. package/dist/cli/chunks/{chunk-EJ6IP7DE.js → chunk-ARMZYHYL.js} +2 -2
  64. package/dist/cli/chunks/{chunk-BZ4QVFP2.js → chunk-BWRHOIYC.js} +2 -2
  65. package/dist/cli/chunks/{chunk-A7SKM6JL.js → chunk-C7AXRI7E.js} +1 -1
  66. package/dist/cli/chunks/{chunk-4XTHRAUV.js → chunk-CG2MUD7U.js} +1 -1
  67. package/dist/cli/chunks/{chunk-HLNQDRHA.js → chunk-CH2TQCV5.js} +1 -1
  68. package/dist/cli/chunks/{chunk-JGROLJ33.js → chunk-CIESXO73.js} +1 -1
  69. package/dist/cli/chunks/{chunk-AR6SATU3.js → chunk-CJCT452S.js} +2 -2
  70. package/dist/cli/chunks/{chunk-UUJ5VQJM.js → chunk-CJHVOBJY.js} +1 -1
  71. package/dist/cli/chunks/{chunk-VOSISOFD.js → chunk-CTCQOYBS.js} +1 -1
  72. package/dist/cli/chunks/{chunk-XITTURP2.js → chunk-D4RCV4LY.js} +2 -2
  73. package/dist/cli/chunks/{chunk-5XGVSQS2.js → chunk-DRO5NJZA.js} +2 -2
  74. package/dist/cli/chunks/{chunk-QMMDN4WX.js → chunk-DVHWLAEO.js} +3 -3
  75. package/dist/cli/chunks/{chunk-5LEAGKX5.js → chunk-DW6ZMNMR.js} +2 -2
  76. package/dist/cli/chunks/{chunk-ZBKGX72B.js → chunk-E3Q7WNJD.js} +3 -3
  77. package/dist/cli/chunks/{chunk-5MZF4N4Q.js → chunk-EAJK25IS.js} +1 -1
  78. package/dist/cli/chunks/{chunk-3RYTAYR6.js → chunk-EH5OCHAJ.js} +1 -1
  79. package/dist/cli/chunks/{chunk-UI6WSPEK.js → chunk-F2KRT2II.js} +3 -3
  80. package/dist/cli/chunks/{chunk-NDPQ2WPU.js → chunk-FPHPP5TQ.js} +1 -1
  81. package/dist/cli/chunks/{chunk-WWWX76QB.js → chunk-FREF6Y4L.js} +2 -2
  82. package/dist/cli/chunks/{chunk-SROZXIMT.js → chunk-FVGTINVR.js} +54 -54
  83. package/dist/cli/chunks/{chunk-H3YDDKBW.js → chunk-G2CLZVYI.js} +3 -3
  84. package/dist/cli/chunks/{chunk-2O4DDPEA.js → chunk-G6AV2HGY.js} +3 -3
  85. package/dist/cli/chunks/{chunk-ENGKLFLY.js → chunk-GHQ5PUOV.js} +2 -2
  86. package/dist/cli/chunks/{chunk-NKWO2X3T.js → chunk-GHUPID5E.js} +1 -1
  87. package/dist/cli/chunks/{chunk-S5YVLPXU.js → chunk-GJAWEUIN.js} +2 -2
  88. package/dist/cli/chunks/{chunk-6IZQSLYZ.js → chunk-HBTC4L53.js} +2 -2
  89. package/dist/cli/chunks/{chunk-DDPJUAXQ.js → chunk-HSJ5FQCF.js} +2 -2
  90. package/dist/cli/chunks/{chunk-OONCRNFA.js → chunk-HZ6NEJMO.js} +2 -2
  91. package/dist/cli/chunks/{chunk-LCSVROU7.js → chunk-HZMLNM2T.js} +10 -10
  92. package/dist/cli/chunks/{chunk-JY4VZ6BN.js → chunk-ICKLBATY.js} +2 -2
  93. package/dist/cli/chunks/{chunk-JMKMDSXG.js → chunk-IUNMW454.js} +2 -2
  94. package/dist/cli/chunks/{chunk-XXFKN7LB.js → chunk-IVGVOGIZ.js} +1 -1
  95. package/dist/cli/chunks/{chunk-3GUO4ERR.js → chunk-IWFL6EFI.js} +2 -2
  96. package/dist/cli/chunks/{chunk-FRL3X2QA.js → chunk-JDXLCNKV.js} +2 -2
  97. package/dist/cli/chunks/{chunk-YW4RNZWT.js → chunk-JIUF6NV6.js} +2 -2
  98. package/dist/cli/chunks/{chunk-JAK5UUWH.js → chunk-JQ2ZD3WO.js} +2 -2
  99. package/dist/cli/chunks/{chunk-YEAC3DC6.js → chunk-K574FLVB.js} +2 -2
  100. package/dist/cli/chunks/{chunk-LZHTCUCO.js → chunk-KEEBUVGV.js} +2 -2
  101. package/dist/cli/chunks/{chunk-LKR7T3OZ.js → chunk-KFXZDQ5J.js} +1 -1
  102. package/dist/cli/chunks/{chunk-7OUMJCJT.js → chunk-KPFG4OIM.js} +1 -1
  103. package/dist/cli/chunks/{chunk-HQ7243G3.js → chunk-KZOBLLXW.js} +2 -2
  104. package/dist/cli/chunks/{chunk-R6WJF4D5.js → chunk-L2F7FVIU.js} +2 -2
  105. package/dist/cli/chunks/{chunk-VRRG66XB.js → chunk-LML5VTFK.js} +1 -1
  106. package/dist/cli/chunks/{chunk-JTWJR2KY.js → chunk-LWUJQGCS.js} +2 -2
  107. package/dist/cli/chunks/{chunk-BQCTO7UB.js → chunk-MH73D5TN.js} +2 -2
  108. package/dist/cli/chunks/{chunk-U4GZWPKM.js → chunk-MWQTACNA.js} +2 -2
  109. package/dist/cli/chunks/{chunk-CIZ6LSNV.js → chunk-N3RN4QTC.js} +2 -2
  110. package/dist/cli/chunks/{chunk-ZQSXG7FA.js → chunk-N5ZRUOMR.js} +2 -2
  111. package/dist/cli/chunks/{chunk-AFGT26NR.js → chunk-NAZVPZJS.js} +2 -2
  112. package/dist/cli/chunks/{chunk-FOHYBR3O.js → chunk-NG2UVPTW.js} +1 -1
  113. package/dist/cli/chunks/{chunk-2D7UBX5S.js → chunk-NHHWLJQF.js} +1 -1
  114. package/dist/cli/chunks/{chunk-JRKEBESE.js → chunk-NNOMDM4N.js} +2 -2
  115. package/dist/cli/chunks/{chunk-YKWMKRYB.js → chunk-NRR23SJV.js} +1 -1
  116. package/dist/cli/chunks/{chunk-WKNWRDA5.js → chunk-NWFIJNEB.js} +1 -1
  117. package/dist/cli/chunks/{chunk-4MK2G6TK.js → chunk-OBCKP3G4.js} +2 -2
  118. package/dist/cli/chunks/{chunk-YKZV7O65.js → chunk-OC2CKU7I.js} +2 -2
  119. package/dist/cli/chunks/{chunk-7RVAHJQZ.js → chunk-OX6T26CD.js} +3 -3
  120. package/dist/cli/chunks/chunk-P64DMQ2C.js +2 -0
  121. package/dist/cli/chunks/{chunk-RKUYVVGJ.js → chunk-PFXX5Q32.js} +2 -2
  122. package/dist/cli/chunks/chunk-PHHXHG2W.js +2 -0
  123. package/dist/cli/chunks/{chunk-N2YAUDAV.js → chunk-PMUBG2RU.js} +2 -2
  124. package/dist/cli/chunks/{chunk-WTHAVFIC.js → chunk-PVHO6KLB.js} +1 -1
  125. package/dist/cli/chunks/{chunk-MO7EITJK.js → chunk-PWEIDHT7.js} +2 -2
  126. package/dist/cli/chunks/{chunk-52DFCV57.js → chunk-PZKZY6PB.js} +2 -2
  127. package/dist/cli/chunks/{chunk-I3VHXA2W.js → chunk-Q335R4MR.js} +2 -2
  128. package/dist/cli/chunks/{chunk-ECTPFCON.js → chunk-Q3JHS3UD.js} +2 -2
  129. package/dist/cli/chunks/{chunk-HJIAVR6P.js → chunk-QFUX7ELG.js} +2 -2
  130. package/dist/cli/chunks/{chunk-L4C42WYI.js → chunk-QW4LN5NK.js} +2 -2
  131. package/dist/cli/chunks/{chunk-HQHLHSJO.js → chunk-QXTW7XCS.js} +2 -2
  132. package/dist/cli/chunks/{chunk-SSV6KSFT.js → chunk-R5RNOLHI.js} +1 -1
  133. package/dist/cli/chunks/{chunk-AVLA5PBJ.js → chunk-RCI64RIJ.js} +2 -2
  134. package/dist/cli/chunks/{chunk-T3BZAFLP.js → chunk-RFNEHNJV.js} +1 -1
  135. package/dist/cli/chunks/{chunk-IL6QRXRP.js → chunk-RGH3WGWD.js} +10 -10
  136. package/dist/cli/chunks/{chunk-E4NU4BJA.js → chunk-RHJVDCLV.js} +2 -2
  137. package/dist/cli/chunks/{chunk-KTSCZ7AW.js → chunk-RVCWSAXI.js} +2 -2
  138. package/dist/cli/chunks/{chunk-TQJE7DNL.js → chunk-RYJHREYS.js} +2 -2
  139. package/dist/cli/chunks/{chunk-HNKPLVYS.js → chunk-S4MR6RTE.js} +1 -1
  140. package/dist/cli/chunks/{chunk-6AYO3IR2.js → chunk-S7N4BKI3.js} +2 -2
  141. package/dist/cli/chunks/{chunk-2NO4H35K.js → chunk-SEHCX4NH.js} +1 -1
  142. package/dist/cli/chunks/{chunk-GKNDP5VK.js → chunk-T46LOLW3.js} +2 -2
  143. package/dist/cli/chunks/{chunk-VXU53F7Z.js → chunk-T4C56HBW.js} +2 -2
  144. package/dist/cli/chunks/{chunk-43GPSYAL.js → chunk-TENYL5TI.js} +2 -2
  145. package/dist/cli/chunks/{chunk-6AOZU3UN.js → chunk-TLPL3EQY.js} +2 -2
  146. package/dist/cli/chunks/{chunk-4ZVGSVHV.js → chunk-TYVQNYXX.js} +4 -4
  147. package/dist/cli/chunks/{chunk-NOPVFBQM.js → chunk-U2AY57XZ.js} +2 -2
  148. package/dist/cli/chunks/{chunk-IQLRA4FV.js → chunk-U54OOA24.js} +1 -1
  149. package/dist/cli/chunks/{chunk-IQ3JFHZN.js → chunk-UHTAI4ZB.js} +1 -1
  150. package/dist/cli/chunks/{chunk-KDIZQHG5.js → chunk-UIGEUEBT.js} +2 -2
  151. package/dist/cli/chunks/{chunk-5VDVYTO5.js → chunk-UYTWDS2R.js} +2 -2
  152. package/dist/cli/chunks/{chunk-ZNSMVQCG.js → chunk-VNAKBHJI.js} +2 -2
  153. package/dist/cli/chunks/{chunk-SUSMHSXT.js → chunk-VOYJJ3KA.js} +2 -2
  154. package/dist/cli/chunks/{chunk-QQCENKCX.js → chunk-VSYBMNIR.js} +1 -1
  155. package/dist/cli/chunks/{chunk-7RAB2BZY.js → chunk-W2FLULF4.js} +2 -2
  156. package/dist/cli/chunks/{chunk-NYARYONH.js → chunk-W4OQYLYO.js} +1 -1
  157. package/dist/cli/chunks/{chunk-DOWCOZDO.js → chunk-WBH4C4BG.js} +2 -2
  158. package/dist/cli/chunks/{chunk-OIYUSWHX.js → chunk-WBMRADQP.js} +1 -1
  159. package/dist/cli/chunks/{chunk-B3H4K7CY.js → chunk-WMW47QMR.js} +2 -2
  160. package/dist/cli/chunks/{chunk-VPVZHJSU.js → chunk-WVY22NHZ.js} +2 -2
  161. package/dist/cli/chunks/{chunk-6W42XWLL.js → chunk-WXMSRBQF.js} +2 -2
  162. package/dist/cli/chunks/{chunk-CIUOC5F3.js → chunk-XPLSLHRB.js} +1 -1
  163. package/dist/cli/chunks/{chunk-E722WNWC.js → chunk-YF5OP6CR.js} +2 -2
  164. package/dist/cli/chunks/{chunk-H76TV4UU.js → chunk-YN6W2XIT.js} +3 -3
  165. package/dist/cli/chunks/{chunk-FF43SRP6.js → chunk-ZCDXJ27H.js} +1 -1
  166. package/dist/cli/chunks/{chunk-TKYEP7OR.js → chunk-ZFGND4QK.js} +1 -1
  167. package/dist/cli/chunks/{chunk-O2MZZL54.js → chunk-ZWRQ5VAU.js} +2 -2
  168. package/dist/cli/chunks/{chunk-H6NFDOMK.js → chunk-ZYLSOBOR.js} +1 -1
  169. package/dist/cli/chunks/{ci-B432UH6N.js → ci-NTRH7PAW.js} +2 -2
  170. package/dist/cli/chunks/{ci-output-GTHH7WYG.js → ci-output-F57RSD35.js} +2 -2
  171. package/dist/cli/chunks/{circuit-breaker-VW75DLME.js → circuit-breaker-4WST3QSA.js} +2 -2
  172. package/dist/cli/chunks/{claude-flow-setup-RE3IVT7U.js → claude-flow-setup-KB4TKMYI.js} +2 -2
  173. package/dist/cli/chunks/client-GPZEC54E.js +2 -0
  174. package/dist/cli/chunks/{cline-installer-NUBZZ55N.js → cline-installer-W2ZHQ6WM.js} +2 -2
  175. package/dist/cli/chunks/{code-K6JCWKNW.js → code-TF2AVR5D.js} +2 -2
  176. package/dist/cli/chunks/{code-index-extractor-I4ILB5JN.js → code-index-extractor-RMDRUVQJ.js} +2 -2
  177. package/dist/cli/chunks/codex-installer-VSTRHJHV.js +14 -0
  178. package/dist/cli/chunks/{completions-V3KJVJF4.js → completions-3Q37QVFR.js} +2 -2
  179. package/dist/cli/chunks/{complexity-analyzer-HRG7OOY3.js → complexity-analyzer-3FNFLACD.js} +2 -2
  180. package/dist/cli/chunks/{continuedev-installer-CNTDONWG.js → continuedev-installer-VTEXM455.js} +2 -2
  181. package/dist/cli/chunks/{copilot-installer-XPWWIWYA.js → copilot-installer-AGY7DQUS.js} +2 -2
  182. package/dist/cli/chunks/core-handlers-YMGHYIBR.js +2 -0
  183. package/dist/cli/chunks/{cost-tracker-MFNLQ56K.js → cost-tracker-LTZAQBX7.js} +2 -2
  184. package/dist/cli/chunks/{coverage-KOIK654V.js → coverage-TT64IOS4.js} +3 -3
  185. package/dist/cli/chunks/cross-domain-router-ECBNTGYJ.js +2 -0
  186. package/dist/cli/chunks/{cursor-installer-S5MKLRQQ.js → cursor-installer-OVOJIOHN.js} +2 -2
  187. package/dist/cli/chunks/{daemon-DUS6JYW6.js → daemon-DMFZMXKA.js} +8 -8
  188. package/dist/cli/chunks/{daemon-Z7VPGWHY.js → daemon-XCULEHWY.js} +4 -4
  189. package/dist/cli/chunks/{dag-attention-scheduler-7CQ3ARNI.js → dag-attention-scheduler-WW2RX4B5.js} +2 -2
  190. package/dist/cli/chunks/{detect-WORBCAYF.js → detect-QNWIM232.js} +2 -2
  191. package/dist/cli/chunks/{dist-node-KRNI6OYW.js → dist-node-6GQIY3CG.js} +2 -2
  192. package/dist/cli/chunks/{domain-handler-KRUR2VQG.js → domain-handler-6RJPDELX.js} +2 -2
  193. package/dist/cli/chunks/{domain-transfer-VEOVLV54.js → domain-transfer-WK524LBS.js} +2 -2
  194. package/dist/cli/chunks/dream-EHGKCFWH.js +2 -0
  195. package/dist/cli/chunks/{embed-and-insert-pattern-QU3NQVA5.js → embed-and-insert-pattern-SO6GWJW7.js} +2 -2
  196. package/dist/cli/chunks/{eval-AYQ7BSUP.js → eval-GL544IPO.js} +2 -2
  197. package/dist/cli/chunks/{experience-capture-middleware-AWQBL6LT.js → experience-capture-middleware-BCCJ35OX.js} +3 -3
  198. package/dist/cli/chunks/{fast-paths-V5EL4BYJ.js → fast-paths-CATDDBEU.js} +2 -2
  199. package/dist/cli/chunks/{feature-flags-P34BPRWU.js → feature-flags-BUXNAORY.js} +2 -2
  200. package/dist/cli/chunks/{feature-flags-BXX7BP22.js → feature-flags-KNNWWP5G.js} +2 -2
  201. package/dist/cli/chunks/{file-discovery-MS6BKQ2U.js → file-discovery-S4HF3O7D.js} +2 -2
  202. package/dist/cli/chunks/{fleet-7WVVPA4W.js → fleet-DQVQQONW.js} +3 -3
  203. package/dist/cli/chunks/{gnn-wrapper-7WQ3LEPG.js → gnn-wrapper-G7ABZUG7.js} +2 -2
  204. package/dist/cli/chunks/{heartbeat-handler-P7QD3BZH.js → heartbeat-handler-UFMELIWT.js} +4 -4
  205. package/dist/cli/chunks/heartbeat-scheduler-UFEL2CBW.js +2 -0
  206. package/dist/cli/chunks/hnsw-adapter-BLSD45CX.js +2 -0
  207. package/dist/cli/chunks/hnsw-index-A3RZODEN.js +2 -0
  208. package/dist/cli/chunks/{hnsw-legacy-bridge-Y3GAR3UP.js → hnsw-legacy-bridge-YIILSRXI.js} +2 -2
  209. package/dist/cli/chunks/{hnswlib-node-5QUXZQWQ.js → hnswlib-node-TSVRMXDH.js} +2 -2
  210. package/dist/cli/chunks/{hooks-2D64KPRY.js → hooks-OHQPNK74.js} +10 -10
  211. package/dist/cli/chunks/{hypergraph-engine-5INXEZDP.js → hypergraph-engine-LY7PJDSL.js} +2 -2
  212. package/dist/cli/chunks/{hypergraph-handler-YJJJ3ESZ.js → hypergraph-handler-YGDYZO6H.js} +3 -3
  213. package/dist/cli/chunks/impact-analyzer-OXHD3FOH.js +2 -0
  214. package/dist/cli/chunks/{init-handler-QSFYJN5Q.js → init-handler-MTK65LI3.js} +9 -8
  215. package/dist/cli/chunks/init-wizard-PKZL7QBU.js +2 -0
  216. package/dist/cli/chunks/kernel-XWPM72UJ.js +2 -0
  217. package/dist/cli/chunks/{kilocode-installer-3N3QGTJU.js → kilocode-installer-3IICU4RS.js} +2 -2
  218. package/dist/cli/chunks/{kiro-installer-GIWVTFZQ.js → kiro-installer-MXOVQYQA.js} +2 -2
  219. package/dist/cli/chunks/knowledge-graph-FRKR5XWI.js +2 -0
  220. package/dist/cli/chunks/{learning-SGO2DQ5Q.js → learning-EV5LSOOM.js} +3 -3
  221. package/dist/cli/chunks/{llm-router-HBBULO65.js → llm-router-7LYDJUOT.js} +4 -4
  222. package/dist/cli/chunks/llm-router-service-R7A5HHDM.js +2 -0
  223. package/dist/cli/chunks/{load-B5OFYB4H.js → load-F4PVAMXQ.js} +2 -2
  224. package/dist/cli/chunks/load-test-5IKDWSYL.js +2 -0
  225. package/dist/cli/chunks/{mcp-FG3LNQR4.js → mcp-DUYJUEME.js} +2 -2
  226. package/dist/cli/chunks/{memory-SPS7ZWLC.js → memory-XTTYORAS.js} +5 -5
  227. package/dist/cli/chunks/memory-backend-7VW5QCMO.js +2 -0
  228. package/dist/cli/chunks/{memory-handlers-P7FTPWP3.js → memory-handlers-VZH3R2TQ.js} +2 -2
  229. package/dist/cli/chunks/{multi-model-executor-PUB7E6KH.js → multi-model-executor-R6XCTMCF.js} +2 -2
  230. package/dist/cli/chunks/{opencode-installer-TGCSGVG2.js → opencode-installer-33ULBU2F.js} +2 -2
  231. package/dist/cli/chunks/{orchestrator-S5FTJFGB.js → orchestrator-34ZJEKTJ.js} +22 -21
  232. package/dist/cli/chunks/pattern-null-store-BU6LCB2W.js +2 -0
  233. package/dist/cli/chunks/{pattern-usage-recorder-LCXXGRAB.js → pattern-usage-recorder-GZ2M3F2E.js} +2 -2
  234. package/dist/cli/chunks/{pipeline-ENOSRHKW.js → pipeline-SR5OTY45.js} +2 -2
  235. package/dist/cli/chunks/platform-VKJFJIAW.js +2 -0
  236. package/dist/cli/chunks/{plugin-JZ5ODJSU.js → plugin-5C5UBQUQ.js} +2 -2
  237. package/dist/cli/chunks/{prime-radiant-advanced-wasm-DPJUPNCG.js → prime-radiant-advanced-wasm-KO2PQI3D.js} +2 -2
  238. package/dist/cli/chunks/protocol-executor-BSP5LWJN.js +2 -0
  239. package/dist/cli/chunks/{protocol-handler-IP4NLVY3.js → protocol-handler-ZF74NIKA.js} +2 -2
  240. package/dist/cli/chunks/{prove-P6FM4RU7.js → prove-MO5TQQU4.js} +2 -2
  241. package/dist/cli/chunks/qe-reasoning-bank-J2RC7P25.js +2 -0
  242. package/dist/cli/chunks/{quality-UHP4XO26.js → quality-EYIN6AER.js} +2 -2
  243. package/dist/cli/chunks/quality-gate-V6OQM57O.js +7 -0
  244. package/dist/cli/chunks/queen-coordinator-XI5AJV2V.js +2 -0
  245. package/dist/cli/chunks/{real-embeddings-6SO5MFRQ.js → real-embeddings-AR7TZX7U.js} +2 -2
  246. package/dist/cli/chunks/{roocode-installer-WTWUOFCH.js → roocode-installer-46E626VZ.js} +2 -2
  247. package/dist/cli/chunks/router-VXQYYA3D.js +2 -0
  248. package/dist/cli/chunks/routing-feedback-HZQTASFF.js +2 -0
  249. package/dist/cli/chunks/{routing-handler-IK7HYERQ.js → routing-handler-ZNRVW6QW.js} +2 -2
  250. package/dist/cli/chunks/{ruvector-commands-THLB4NIM.js → ruvector-commands-4L2CQMWS.js} +2 -2
  251. package/dist/cli/chunks/rvf-dual-writer-BDTLLJER.js +2 -0
  252. package/dist/cli/chunks/rvf-migration-adapter-IB343MDN.js +2 -0
  253. package/dist/cli/chunks/{rvf-migration-coordinator-BUKCSHBD.js → rvf-migration-coordinator-H4RVGBIA.js} +2 -2
  254. package/dist/cli/chunks/rvf-native-adapter-Y7SN7LHU.js +2 -0
  255. package/dist/cli/chunks/{rvf-store-integrity-ECTADZIN.js → rvf-store-integrity-OJGWWPLL.js} +2 -2
  256. package/dist/cli/chunks/safe-db-2VTKKBJU.js +2 -0
  257. package/dist/cli/chunks/schedule-QJ4CFGJY.js +2 -0
  258. package/dist/cli/chunks/scheduler-2NHDQPC3.js +2 -0
  259. package/dist/cli/chunks/{security-HN4UXFXX.js → security-JF3BVNRO.js} +3 -3
  260. package/dist/cli/chunks/{shared-rvf-adapter-XJCPX5SN.js → shared-rvf-adapter-M6NNIZ5W.js} +2 -2
  261. package/dist/cli/chunks/{shared-rvf-dual-writer-23X5PNY5.js → shared-rvf-dual-writer-LHMFCYVE.js} +2 -2
  262. package/dist/cli/chunks/sqlite-persistence-NVVAPZN3.js +2 -0
  263. package/dist/cli/chunks/{status-handler-ZXANTHKT.js → status-handler-GMIOXQIE.js} +2 -2
  264. package/dist/cli/chunks/{structural-health-LR6WI3AH.js → structural-health-YZXHVHM6.js} +2 -2
  265. package/dist/cli/chunks/{sync-I5IUJF33.js → sync-GMPCPV5L.js} +2 -2
  266. package/dist/cli/chunks/{sync-4OEI3BC2.js → sync-N56UQGCS.js} +2 -2
  267. package/dist/cli/chunks/{task-handler-R3ATJKU5.js → task-handler-VTNRGAXP.js} +2 -2
  268. package/dist/cli/chunks/{task-handlers-4X357AEW.js → task-handlers-FYSDH55N.js} +3 -3
  269. package/dist/cli/chunks/{test-PR2B5H2F.js → test-GQNCKRSP.js} +4 -4
  270. package/dist/cli/chunks/{test-scheduling-ZNOSQVLD.js → test-scheduling-GPRXSIRP.js} +3 -3
  271. package/dist/cli/chunks/{token-bootstrap-LYXOI72S.js → token-bootstrap-76SRNXGG.js} +2 -2
  272. package/dist/cli/chunks/{token-usage-R6EQZBX2.js → token-usage-O7CZDP5Q.js} +2 -2
  273. package/dist/cli/chunks/{transformers-COQWK27J.js → transformers-LTU4LSSC.js} +2 -2
  274. package/dist/cli/chunks/{tree-sitter-wasm-parser-LLIW2X3M.js → tree-sitter-wasm-parser-NQSQCMBM.js} +2 -2
  275. package/dist/cli/chunks/{types-MEYTZITK.js → types-OP6IWE6N.js} +2 -2
  276. package/dist/cli/chunks/unified-memory-DSTIEDSH.js +2 -0
  277. package/dist/cli/chunks/unified-memory-hnsw-KBV3P4OS.js +2 -0
  278. package/dist/cli/chunks/unified-persistence-XKCOUBKY.js +2 -0
  279. package/dist/cli/chunks/{upgrade-DVIJ456A.js → upgrade-OQWRBZ3R.js} +2 -2
  280. package/dist/cli/chunks/{validate-UYTSMJ5X.js → validate-TH5SRP3E.js} +2 -2
  281. package/dist/cli/chunks/{validate-swarm-P32WCJR6.js → validate-swarm-UITL2JUS.js} +2 -2
  282. package/dist/cli/chunks/{vibium-JGVOLM6X.js → vibium-O6PRAG4J.js} +2 -2
  283. package/dist/cli/chunks/visual-security-TTWSPZTZ.js +2 -0
  284. package/dist/cli/chunks/{web-tree-sitter-5ZGNCTPN.js → web-tree-sitter-XBFBY4OF.js} +2 -2
  285. package/dist/cli/chunks/{windsurf-installer-IILSSQAE.js → windsurf-installer-DVT5NRNY.js} +2 -2
  286. package/dist/cli/chunks/witness-chain-2KY73HPN.js +2 -0
  287. package/dist/cli/chunks/{witness-chain-JZMXCG3B.js → witness-chain-VRSH2F36.js} +2 -2
  288. package/dist/cli/chunks/{witness-key-manager-UUTLNUIH.js → witness-key-manager-GFHRDKQ4.js} +2 -2
  289. package/dist/cli/chunks/{workflow-NS7HXVHZ.js → workflow-HAZ6YKOG.js} +4 -4
  290. package/dist/cli/chunks/workflow-orchestrator-UK56AVOT.js +2 -0
  291. package/dist/cli/chunks/{wrappers-XKEDSV5W.js → wrappers-5LLLT7GM.js} +2 -2
  292. package/dist/cli/commands/daemon.js +3 -0
  293. package/dist/cli/commands/platform.d.ts +1 -0
  294. package/dist/cli/commands/platform.js +28 -6
  295. package/dist/cli/commands/quality-gate.js +25 -3
  296. package/dist/cli/foreground-command.d.ts +3 -0
  297. package/dist/cli/foreground-command.js +22 -0
  298. package/dist/cli/handlers/init-handler.d.ts +5 -0
  299. package/dist/cli/handlers/init-handler.js +6 -0
  300. package/dist/cli/index.js +8 -1
  301. package/dist/contracts/verdicts.d.ts +625 -0
  302. package/dist/contracts/verdicts.js +202 -14
  303. package/dist/coordination/handlers/coverage-handlers.js +8 -1
  304. package/dist/domains/chaos-resilience/diagnosis/corpus.d.ts +5 -0
  305. package/dist/domains/chaos-resilience/diagnosis/corpus.js +141 -0
  306. package/dist/domains/chaos-resilience/diagnosis/detectors.d.ts +11 -0
  307. package/dist/domains/chaos-resilience/diagnosis/detectors.js +109 -0
  308. package/dist/domains/chaos-resilience/diagnosis/index.d.ts +5 -0
  309. package/dist/domains/chaos-resilience/diagnosis/index.js +5 -0
  310. package/dist/domains/chaos-resilience/diagnosis/scorer.d.ts +8 -0
  311. package/dist/domains/chaos-resilience/diagnosis/scorer.js +128 -0
  312. package/dist/domains/chaos-resilience/diagnosis/types.d.ts +171 -0
  313. package/dist/domains/chaos-resilience/diagnosis/types.js +3 -0
  314. package/dist/domains/chaos-resilience/index.d.ts +1 -0
  315. package/dist/domains/chaos-resilience/index.js +1 -0
  316. package/dist/domains/index.d.ts +1 -0
  317. package/dist/domains/index.js +1 -0
  318. package/dist/early-exit/early-exit-controller.d.ts +4 -2
  319. package/dist/early-exit/early-exit-controller.js +95 -7
  320. package/dist/early-exit/index.d.ts +1 -1
  321. package/dist/early-exit/speculative-executor.js +3 -0
  322. package/dist/early-exit/types.d.ts +51 -0
  323. package/dist/early-exit/types.js +3 -0
  324. package/dist/index.d.ts +4 -2
  325. package/dist/index.js +2 -1
  326. package/dist/init/browser-engine-installer.d.ts +11 -0
  327. package/dist/init/browser-engine-installer.js +35 -5
  328. package/dist/init/codex-installer.d.ts +11 -1
  329. package/dist/init/codex-installer.js +90 -24
  330. package/dist/init/init-wizard-hooks.js +11 -11
  331. package/dist/init/orchestrator.js +2 -0
  332. package/dist/init/phases/07-hooks.d.ts +3 -3
  333. package/dist/init/phases/07-hooks.js +19 -18
  334. package/dist/init/phases/09-assets.d.ts +4 -0
  335. package/dist/init/phases/09-assets.js +13 -10
  336. package/dist/init/phases/phase-interface.d.ts +2 -0
  337. package/dist/init/types.d.ts +4 -0
  338. package/dist/learning/index.d.ts +3 -0
  339. package/dist/learning/index.js +2 -0
  340. package/dist/learning/pattern-mutation-error.d.ts +9 -0
  341. package/dist/learning/pattern-mutation-error.js +14 -0
  342. package/dist/learning/pattern-store.js +24 -2
  343. package/dist/learning/qe-reasoning-bank.js +24 -5
  344. package/dist/learning/rvf-pattern-store.js +23 -5
  345. package/dist/learning/structural-retrieval/corpus.d.ts +5 -0
  346. package/dist/learning/structural-retrieval/corpus.js +97 -0
  347. package/dist/learning/structural-retrieval/evaluate.d.ts +7 -0
  348. package/dist/learning/structural-retrieval/evaluate.js +124 -0
  349. package/dist/learning/structural-retrieval/index.d.ts +6 -0
  350. package/dist/learning/structural-retrieval/index.js +4 -0
  351. package/dist/learning/structural-retrieval/receipt.d.ts +14 -0
  352. package/dist/learning/structural-retrieval/receipt.js +36 -0
  353. package/dist/learning/structural-retrieval/types.d.ts +83 -0
  354. package/dist/learning/structural-retrieval/types.js +2 -0
  355. package/dist/mcp/bundle.js +423 -423
  356. package/dist/mcp/index.d.ts +1 -0
  357. package/dist/mcp/index.js +1 -0
  358. package/dist/mcp/protocol-server.js +11 -2
  359. package/dist/mcp/qe-tool-bridge.js +1 -0
  360. package/dist/mcp/services/session-resume.d.ts +15 -19
  361. package/dist/mcp/services/session-resume.js +204 -194
  362. package/dist/mcp/tool-annotations.d.ts +25 -0
  363. package/dist/mcp/tool-annotations.js +75 -0
  364. package/dist/mcp/tool-registry.js +17 -12
  365. package/dist/mcp/tools/base.d.ts +7 -1
  366. package/dist/mcp/tools/base.js +8 -0
  367. package/dist/mcp/tools/quality-assessment/gate.d.ts +8 -5
  368. package/dist/mcp/tools/quality-assessment/gate.js +9 -4
  369. package/dist/mcp/tools/registry.d.ts +3 -0
  370. package/dist/mcp/tools/registry.js +1 -0
  371. package/dist/mcp/types.d.ts +15 -0
  372. package/dist/skills/qe-court/cli.js +0 -0
  373. package/dist/validation/quality-gate-runner.d.ts +27 -4
  374. package/dist/validation/quality-gate-runner.js +33 -4
  375. package/dist/validation/verification-reach.d.ts +90 -0
  376. package/dist/validation/verification-reach.js +187 -0
  377. package/dist/verification/adversarial-verify/index.d.ts +1 -1
  378. package/dist/verification/adversarial-verify/measurement-receipt.d.ts +13 -0
  379. package/dist/verification/adversarial-verify/measurement-receipt.js +136 -0
  380. package/dist/verification/adversarial-verify/synthesize.js +7 -10
  381. package/dist/verification/adversarial-verify/types.d.ts +35 -0
  382. package/dist/verification/adversarial-verify/verify.js +6 -1
  383. package/package.json +9 -5
  384. package/schemas/coverage-gap.schema.json +41 -0
  385. package/schemas/finding-verdict.schema.json +470 -0
  386. package/schemas/risk-decision.schema.json +41 -0
  387. package/dist/cli/chunks/adapter-3VBXL7DO.js +0 -2
  388. package/dist/cli/chunks/aqe-learning-engine-NXRNKJNA.js +0 -2
  389. package/dist/cli/chunks/base-F6GMOKU2.js +0 -2
  390. package/dist/cli/chunks/browser-workflow-QRDC46LR.js +0 -2
  391. package/dist/cli/chunks/chunk-3JIJBR4V.js +0 -2
  392. package/dist/cli/chunks/chunk-R2B6EE45.js +0 -2
  393. package/dist/cli/chunks/chunk-TRDEULS7.js +0 -4
  394. package/dist/cli/chunks/chunk-WJXHE52V.js +0 -65
  395. package/dist/cli/chunks/client-HNBZUEVV.js +0 -2
  396. package/dist/cli/chunks/codex-installer-AKQ5BCHU.js +0 -15
  397. package/dist/cli/chunks/core-handlers-TB7NLYXL.js +0 -2
  398. package/dist/cli/chunks/cross-domain-router-MDSI553U.js +0 -2
  399. package/dist/cli/chunks/dream-X7ISHFEE.js +0 -2
  400. package/dist/cli/chunks/heartbeat-scheduler-2C5XGFQT.js +0 -2
  401. package/dist/cli/chunks/hnsw-adapter-KCVMXLUL.js +0 -2
  402. package/dist/cli/chunks/hnsw-index-OGWZS6MP.js +0 -2
  403. package/dist/cli/chunks/impact-analyzer-IBJ43GQL.js +0 -2
  404. package/dist/cli/chunks/init-wizard-6XMFD5LP.js +0 -2
  405. package/dist/cli/chunks/kernel-UDUMUPB3.js +0 -2
  406. package/dist/cli/chunks/knowledge-graph-JRYTUG3W.js +0 -2
  407. package/dist/cli/chunks/llm-router-service-KF5ZALUQ.js +0 -2
  408. package/dist/cli/chunks/load-test-LHMBCNCH.js +0 -2
  409. package/dist/cli/chunks/memory-backend-WZHKHBZK.js +0 -2
  410. package/dist/cli/chunks/pattern-null-store-UZSHCRL2.js +0 -2
  411. package/dist/cli/chunks/platform-WCRBO3Z7.js +0 -2
  412. package/dist/cli/chunks/protocol-executor-42NLVDTC.js +0 -2
  413. package/dist/cli/chunks/qe-reasoning-bank-W74RSMMU.js +0 -2
  414. package/dist/cli/chunks/quality-gate-63DDBSGM.js +0 -7
  415. package/dist/cli/chunks/queen-coordinator-XELKSRMS.js +0 -2
  416. package/dist/cli/chunks/router-GTW2EQZV.js +0 -2
  417. package/dist/cli/chunks/routing-feedback-NVOBWEMK.js +0 -2
  418. package/dist/cli/chunks/rvf-dual-writer-5OPVMXNL.js +0 -2
  419. package/dist/cli/chunks/rvf-migration-adapter-5S4YFTX4.js +0 -2
  420. package/dist/cli/chunks/rvf-native-adapter-LYSJHEVX.js +0 -2
  421. package/dist/cli/chunks/safe-db-AEB3JMLD.js +0 -2
  422. package/dist/cli/chunks/schedule-4QNPCQNT.js +0 -2
  423. package/dist/cli/chunks/scheduler-S3DFHX6A.js +0 -2
  424. package/dist/cli/chunks/sqlite-persistence-L2KISU2H.js +0 -2
  425. package/dist/cli/chunks/unified-memory-5KQMA7FV.js +0 -2
  426. package/dist/cli/chunks/unified-memory-hnsw-PQRPTYOD.js +0 -2
  427. package/dist/cli/chunks/unified-persistence-YDONVPJB.js +0 -2
  428. package/dist/cli/chunks/visual-security-RJ7RTNGJ.js +0 -2
  429. package/dist/cli/chunks/witness-chain-YXXXNGAM.js +0 -2
  430. package/dist/cli/chunks/workflow-orchestrator-5KUAVSTH.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.14.0");process.exit(0)}
2
- import{a as _n}from"./chunk-EJ6IP7DE.js";import{b as Fn}from"./chunk-4MK2G6TK.js";import{a as si,c as ai,d as oi}from"./chunk-TRDEULS7.js";import{a as Gr,b as Kr,c as Pe,d as xe,e as wt,f as ei,g as Ta,h as ti,i as ri,j as ii,k as ci,l as li,m as di,n as mi,o as pi,p as gi,q as hi,r as fi,s as yi,t as vi,u as bi,v as Ci,w as Ti,x as Si,y as Ei,z as Mi}from"./chunk-LCSVROU7.js";import{a as de,b as Rt,c as ni}from"./chunk-4FEJEVG7.js";import{a as Xr}from"./chunk-HJIAVR6P.js";import{a as Ai}from"./chunk-TGOGCA74.js";import{a as ki}from"./chunk-5VDVYTO5.js";import{a as Qr,b as Wr}from"./chunk-6AOZU3UN.js";import{a as Yr,c as We,d as Jr}from"./chunk-2D7UBX5S.js";import{p as wi}from"./chunk-QKQZ4IJF.js";import{a as le,b as ue}from"./chunk-NOPVFBQM.js";import{a as Ri}from"./chunk-DJITEQYS.js";import{a as Pi}from"./chunk-52DFCV57.js";import{a as xi}from"./chunk-J3XSHJGK.js";import{c as F,e as xt,i as z,j as At,l as x}from"./chunk-3JIJBR4V.js";import{a as ui}from"./chunk-MO7EITJK.js";import{e as me,g as Pt}from"./chunk-H76TV4UU.js";import{a as Vr}from"./chunk-KDIZQHG5.js";import{b as Tt}from"./chunk-UI6WSPEK.js";import{b as St,c as Et}from"./chunk-BZ4QVFP2.js";import{a as Re}from"./chunk-RGVD6ZUX.js";import{c as Zr}from"./chunk-WWWX76QB.js";import{d as On}from"./chunk-OONCRNFA.js";import{a as Br,b as J,c as H}from"./chunk-6DPAMYLU.js";import{d as Ur}from"./chunk-7RVAHJQZ.js";import{a as Te}from"./chunk-CIUOC5F3.js";import{c as Hr}from"./chunk-S5YVLPXU.js";import{h as In}from"./chunk-IL6QRXRP.js";import{a as kn}from"./chunk-WJXHE52V.js";import{c as Mn,d as Dn}from"./chunk-N2YAUDAV.js";import{d as ce}from"./chunk-5MZF4N4Q.js";import{c as jr}from"./chunk-ECTPFCON.js";import{e as we}from"./chunk-ZBKGX72B.js";import{k as U,o as ae}from"./chunk-7RAB2BZY.js";import{a as $r}from"./chunk-R2B6EE45.js";import{c as vt,d as Se,e as An}from"./chunk-JY4VZ6BN.js";import{b as A,d as Q}from"./chunk-HQHLHSJO.js";import{a as xn,b as I,c as $}from"./chunk-JGROLJ33.js";import{a as S,b as j,c as k}from"./chunk-XITTURP2.js";import{i as q}from"./chunk-FOHYBR3O.js";import{a as zr,b as ba}from"./chunk-ZQSXG7FA.js";import{a as te,c as ne,d as Qe}from"./chunk-VXU53F7Z.js";import{a as bt}from"./chunk-AR6SATU3.js";import{R as Ca,S as Ct,b as Ee}from"./chunk-ENGKLFLY.js";import{a as fa,c as ya,e as va,g as qr}from"./chunk-PEW6FZ47.js";var cs={};va(cs,{DEFAULT_QEC_CONFIG:()=>as,ReasoningQEC:()=>Kt,createReasoningQEC:()=>os,processReasoning:()=>Jo});async function Yo(){return ss?is!==null:(is=null,ss=!0,!1)}function os(o){return new Kt(o)}function Jo(o,e){return os(e).process(o)}var ar,as,Ko,Xo,is,ss,Kt,ls=ya(()=>{"use strict";An();Ct();ar=Se("ReasoningQEC"),as={minPaths:3,confidenceThreshold:.5,majorityThreshold:.5,useNativeBackend:!0,votingMethod:"weighted"},Ko={"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"]},Xo=["analytical","empirical","heuristic"],is=null,ss=!1;Kt=class{config;nativeAvailable=!1;constructor(e={}){this.config={...as,...e}}async initialize(){if(this.config.useNativeBackend){let e=Ee();(e.useQEFlashAttention||e.useQEGNNIndex)&&(this.nativeAvailable=await Yo())}}generatePaths(e){let t=Math.max(this.config.minPaths,3),n=Ko[e.type]??Xo,r=[];for(let i=0;i<t;i++){let a=n[i%n.length],s=this.generatePathSteps(e,i,a),c=this.deriveConclusion(s,a),l=this.calculatePathConfidence(s);r.push({id:i,steps:s,conclusion:c,confidence:l})}return ar.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 a=new Map;for(let l of e){let u=l.steps[i];if(!u)continue;let d=a.get(u.conclusion)??[];d.push(l.id),a.set(u.conclusion,d)}if(a.size<=1)continue;let s=[...a.entries()].map(([l,u])=>u.map(d=>({pathId:d,conclusion:l}))).flat(),c=this.classifySyndromeSeverity(a,e.length);t.push({stepIndex:i,disagreements:s,severity:c})}let r=new Map;for(let i of e){let a=r.get(i.conclusion)??[];a.push(i.id),r.set(i.conclusion,a)}if(r.size>1){let i=[...r.entries()].map(([s,c])=>c.map(l=>({pathId:l,conclusion:s}))).flat(),a=this.classifySyndromeSeverity(r,e.length);t.push({stepIndex:-1,disagreements:i,severity:a})}return ar.debug(`Extracted ${t.length} syndromes: ${t.filter(i=>i.severity==="critical").length} critical, ${t.filter(i=>i.severity==="major").length} major, ${t.filter(i=>i.severity==="minor").length} minor`),t}correctErrors(e,t){if(e.length===0)return{steps:[],conclusion:"",confidence:0,corrections:[],syndromeCount:t.length};let n=new Set(t.filter(u=>u.stepIndex>=0).map(u=>u.stepIndex)),r=Math.max(...e.map(u=>u.steps.length)),i=[],a=[];for(let u=0;u<r;u++)if(n.has(u)){let{step:d,correction:m}=this.correctStep(e,u);i.push(d),m&&a.push(m)}else{let d=e[0].steps[u];d&&i.push({...d})}let s=this.correctConclusion(e),c=this.calculateCorrectedConfidence(e,t),l={steps:i,conclusion:s,confidence:c,corrections:a,syndromeCount:t.length};return ar.debug(`Error correction applied: ${a.length} corrections, confidence: ${c.toFixed(3)}`),l}validate(e){let t=[];e.confidence<this.config.confidenceThreshold&&t.push({stepIndex:-1,type:"low-confidence",description:`Overall confidence ${e.confidence.toFixed(3)} is below threshold ${this.config.confidenceThreshold}`});for(let i of e.steps)i.evidence.length===0&&t.push({stepIndex:i.index,type:"inconsistent-evidence",description:`Step ${i.index} has no supporting evidence`});e.syndromeCount>0&&e.confidence<.3&&t.push({stepIndex:-1,type:"all-divergent",description:`${e.syndromeCount} syndromes with confidence ${e.confidence.toFixed(3)} suggests all paths diverged significantly`});for(let i of e.corrections)i.reason.includes("no clear majority")&&t.push({stepIndex:i.stepIndex,type:"no-majority",description:`Step ${i.stepIndex}: ${i.reason}`});let n=t.length===0,r=n?e.confidence:e.confidence*(1-t.length*.1);return{valid:n,confidence:Math.max(0,r),issues:t}}process(e){let t=this.generatePaths(e),n=this.extractSyndromes(t),r=this.correctErrors(t,n),i=this.validate(r);return{paths:t,syndromes:n,corrected:r,validation:i}}getConfig(){return{...this.config}}isNativeAvailable(){return this.nativeAvailable}generatePathSteps(e,t,n){return e.steps.map((r,i)=>{let a=this.generateStepConclusion(r,n,e.context,t),s=this.gatherEvidence(r,n,e.context);return{index:i,description:`[${n}] ${r}`,conclusion:a,evidence:s}})}generateStepConclusion(e,t,n,r){let i=Object.keys(n).sort(),a={0:l=>l.length>0?`Focused on ${l[0]}`:"Primary analysis",1:l=>l.length>1?`Focused on ${l[l.length-1]}`:"Secondary analysis",2:l=>l.length>0?`Cross-referencing ${l.join(" and ")}`:"Holistic analysis"},c=(a[r%3]??a[0])(i);return`[${t}] ${e}: ${c}`}gatherEvidence(e,t,n){let r=[];r.push(`Analysis via ${t}: ${e}`);for(let[i,a]of Object.entries(n))(typeof a=="string"||typeof a=="number"||typeof a=="boolean")&&r.push(`Context[${i}]: ${String(a)}`);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 y=n.get(h.conclusion)??0,v=i?g.confidence:1;n.set(h.conclusion,y+v),r.set(h.conclusion,h)}if(n.size===0)return{step:{index:t,description:`Step ${t} (no data)`,conclusion:"",evidence:[]},correction:null};let a=[...n.entries()].sort((g,h)=>h[1]-g[1]||g[0].localeCompare(h[0])),[s,c]=a[0],l=r.get(s),u=new Set;for(let g of e){let h=g.steps[t];if(h)for(let y of h.evidence)u.add(y)}let d={index:t,description:l.description,conclusion:s,evidence:[...u]},m=e[0].steps[t]?.conclusion,p=null;if(m&&m!==s){let g=e.filter(C=>C.steps[t]).length,h=[...n.values()].reduce((C,b)=>C+b,0),v=c/h>this.config.majorityThreshold;p={stepIndex:t,original:m,corrected:s,reason:v?`${i?"Weighted vote":"Majority vote"} (${c.toFixed(2)}/${h.toFixed(2)} weight from ${g} paths)`:`Selected highest ${i?"weight":"count"} (${c.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 a=t.get(i.conclusion)??0,s=n?i.confidence:1;t.set(i.conclusion,a+s)}return[...t.entries()].sort((i,a)=>a[1]-i[1]||i[0].localeCompare(a[0]))[0]?.[0]??""}calculateCorrectedConfidence(e,t){let n=e.reduce((l,u)=>l+u.confidence,0)/e.length,r=t.filter(l=>l.severity==="critical").length,i=t.filter(l=>l.severity==="major").length,a=t.filter(l=>l.severity==="minor").length,s=r*.2+i*.1+a*.03,c=t.length===0?.1:0;return Math.max(0,Math.min(1,n-s+c))}}});k();Q();import*as _ from"fs/promises";import*as D from"path";import{createHash as Sa}from"crypto";var Ea={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"}},Ln=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,a=[];if(process.env.AQE_MEMORY_BACKEND==="memory")return{taskId:e,taskType:t,timestamp:i,files:a,summary:this.extractSummary(t,n)};await this.ensureDirectories(t);let s=this.formatTimestamp(i),c=r.filenamePrefix||s;switch(t){case"generate-tests":a.push(...await this.saveTestGeneration(n,c,r));break;case"analyze-coverage":a.push(...await this.saveCoverage(n,c,r));break;case"scan-security":a.push(...await this.saveSecurityScan(n,c,r));break;case"assess-quality":a.push(...await this.saveQualityAssessment(n,c,r));break;case"index-code":a.push(...await this.saveCodeIndex(n,c,r));break;case"predict-defects":a.push(...await this.saveDefectPrediction(n,c,r));break;case"validate-contracts":a.push(...await this.saveContractValidation(n,c,r));break;case"test-accessibility":a.push(...await this.saveAccessibilityTest(n,c,r));break;case"run-chaos":a.push(...await this.saveChaosTest(n,c,r));break;default:a.push(...await this.saveGeneric(t,n,c))}let l=this.extractSummary(t,n);return await this.updateIndex(e,t,i,a,l),{taskId:e,taskType:t,timestamp:i,files:a,summary:l}}async saveTestGeneration(e,t,n){let r=[],i=e,a=D.join(this.resultsDir,"tests","generated");await _.mkdir(a,{recursive:!0});let s=D.join(this.resultsDir,"tests",`${t}_manifest.json`),c=JSON.stringify({generated:new Date().toISOString(),testsGenerated:i.testsGenerated,coverageEstimate:i.coverageEstimate,patternsUsed:i.patternsUsed,language:n.language||"typescript",framework:n.framework||"vitest",tests:i.tests},null,2);if(await _.writeFile(s,c),r.push(await this.createFileEntry(s,"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(a,p);await _.writeFile(g,d.code),r.push(await this.createFileEntry(g,"source"))}}let l=D.join(this.resultsDir,"tests",`${t}_report.md`),u=this.generateTestReport(i,n);return await _.writeFile(l,u),r.push(await this.createFileEntry(l,"markdown")),r}async saveCoverage(e,t,n){let r=[],i=e,a=D.join(this.resultsDir,"coverage"),s=D.join(a,`${t}_coverage.json`);if(await _.writeFile(s,JSON.stringify(i,null,2)),r.push(await this.createFileEntry(s,"json")),n.includeSecondary!==!1&&i.measured===!0){let u=D.join(a,`${t}_coverage.lcov`),d=this.generateLcov(i);await _.writeFile(u,d),r.push(await this.createFileEntry(u,"lcov"))}let c=D.join(a,`${t}_report.md`),l=this.generateCoverageReport(i);return await _.writeFile(c,l),r.push(await this.createFileEntry(c,"markdown")),r}async saveSecurityScan(e,t,n){let r=[],i=e,a=D.join(this.resultsDir,"security"),s=D.join(a,`${t}_scan.json`);if(await _.writeFile(s,JSON.stringify(i,null,2)),r.push(await this.createFileEntry(s,"json")),n.includeSecondary!==!1){let u=D.join(a,`${t}_scan.sarif`),d=this.generateSarif(i);await _.writeFile(u,d),r.push(await this.createFileEntry(u,"sarif"))}let c=D.join(a,`${t}_report.md`),l=this.generateSecurityReport(i);return await _.writeFile(c,l),r.push(await this.createFileEntry(c,"markdown")),r}async saveQualityAssessment(e,t,n){let r=[],i=e,a=D.join(this.resultsDir,"quality"),s=D.join(a,`${t}_assessment.json`);await _.writeFile(s,JSON.stringify(i,null,2)),r.push(await this.createFileEntry(s,"json"));let c=D.join(a,`${t}_report.md`),l=this.generateQualityReport(i);return await _.writeFile(c,l),r.push(await this.createFileEntry(c,"markdown")),r}async saveCodeIndex(e,t,n){let r=[],i=e,a=D.join(this.resultsDir,"code-index");await _.mkdir(a,{recursive:!0});let s=D.join(a,`${t}_index.json`);return await _.writeFile(s,JSON.stringify(i,null,2)),r.push(await this.createFileEntry(s,"json")),r}async saveDefectPrediction(e,t,n){let r=[],i=D.join(this.resultsDir,"defects");await _.mkdir(i,{recursive:!0});let a=D.join(i,`${t}_prediction.json`);return await _.writeFile(a,JSON.stringify(e,null,2)),r.push(await this.createFileEntry(a,"json")),r}async saveContractValidation(e,t,n){let r=[],i=D.join(this.resultsDir,"contracts");await _.mkdir(i,{recursive:!0});let a=D.join(i,`${t}_validation.json`);return await _.writeFile(a,JSON.stringify(e,null,2)),r.push(await this.createFileEntry(a,"json")),r}async saveAccessibilityTest(e,t,n){let r=[],i=D.join(this.resultsDir,"accessibility");await _.mkdir(i,{recursive:!0});let a=D.join(i,`${t}_test.json`);return await _.writeFile(a,JSON.stringify(e,null,2)),r.push(await this.createFileEntry(a,"json")),r}async saveChaosTest(e,t,n){let r=[],i=D.join(this.resultsDir,"chaos");await _.mkdir(i,{recursive:!0});let a=D.join(i,`${t}_chaos.json`);return await _.writeFile(a,JSON.stringify(e,null,2)),r.push(await this.createFileEntry(a,"json")),r}async saveGeneric(e,t,n){let r=[],i=D.join(this.resultsDir,"other");await _.mkdir(i,{recursive:!0});let a=D.join(i,`${n}_${e}.json`);return await _.writeFile(a,JSON.stringify(t,null,2)),r.push(await this.createFileEntry(a,"json")),r}generateLcov(e){let t=Math.round(e.lineCoverage??0);return`TN:agentic-qe-coverage
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.2");process.exit(0)}
2
+ import{a as Fn}from"./chunk-ARMZYHYL.js";import{b as qn}from"./chunk-OBCKP3G4.js";import{a as hi,c as fi,d as yi}from"./chunk-4AKGBUYD.js";import{a as Kr,b as si,c as xe,d as Ae,e as xt,f as ui,g as Ia,h as di,i as pi,j as gi,k as vi,l as bi,m as Ti,n as Si,o as Ei,p as wi,q as Ri,r as Pi,s as xi,t as Ai,u as ki,v as Mi,w as Ii,x as Di,y as _i,z as $i}from"./chunk-HZMLNM2T.js";import{a as me,b as At,c as mi}from"./chunk-4K27ESCA.js";import{a as ai}from"./chunk-QFUX7ELG.js";import{a as qi}from"./chunk-4M6A3PVJ.js";import{a as Gi}from"./chunk-UYTWDS2R.js";import{a as ri,b as ii}from"./chunk-TLPL3EQY.js";import{a as oi,c as Ye,d as ci}from"./chunk-NHHWLJQF.js";import{p as Oi}from"./chunk-6SZKLWZT.js";import{a as ue,b as de}from"./chunk-U2AY57XZ.js";import{a as Ni}from"./chunk-4PH7O5ZH.js";import{a as Fi}from"./chunk-PZKZY6PB.js";import{a as Li}from"./chunk-ADK7DF3G.js";import{c as N,e as Mt,i as z,j as It,l as x}from"./chunk-2LKAMMMI.js";import{a as Ci}from"./chunk-PWEIDHT7.js";import{e as pe,g as kt}from"./chunk-YN6W2XIT.js";import{a as ni}from"./chunk-UIGEUEBT.js";import{b as wt}from"./chunk-F2KRT2II.js";import{b as Rt,c as Pt}from"./chunk-BWRHOIYC.js";import{a as Pe}from"./chunk-4MH22236.js";import{c as li}from"./chunk-FREF6Y4L.js";import{d as Ln}from"./chunk-HZ6NEJMO.js";import{a as Zr,b as Z,c as H}from"./chunk-4N44UJGI.js";import{d as ei}from"./chunk-OX6T26CD.js";import{a as Se}from"./chunk-XPLSLHRB.js";import{c as ti}from"./chunk-GJAWEUIN.js";import{h as Nn}from"./chunk-RGH3WGWD.js";import{b as Dn}from"./chunk-4UCMTYFQ.js";import{c as _n,d as On}from"./chunk-PMUBG2RU.js";import{d as le}from"./chunk-EAJK25IS.js";import{c as Jr}from"./chunk-Q3JHS3UD.js";import{e as Re}from"./chunk-E3Q7WNJD.js";import{k as U,o as oe}from"./chunk-W2FLULF4.js";import{a as Xr}from"./chunk-PHHXHG2W.js";import{c as Tt,d as Ee,e as In}from"./chunk-ICKLBATY.js";import{b as A,d as Q}from"./chunk-QXTW7XCS.js";import{a as Mn,b as D,c as $}from"./chunk-CIESXO73.js";import{a as S,b as j,c as k}from"./chunk-D4RCV4LY.js";import{i as q}from"./chunk-NG2UVPTW.js";import{a as Yr,b as ka}from"./chunk-N5ZRUOMR.js";import{a as ne,c as re,d as Xe}from"./chunk-T4C56HBW.js";import{a as St}from"./chunk-CJCT452S.js";import{R as Ma,S as Et,b as we}from"./chunk-GHQ5PUOV.js";import{a as Pa,c as xa,e as Aa,g as Wr}from"./chunk-6VKJAMZY.js";var ys={};Aa(ys,{DEFAULT_QEC_CONFIG:()=>hs,ReasoningQEC:()=>Jt,createReasoningQEC:()=>fs,processReasoning:()=>cc});async function oc(){return gs?ps!==null:(ps=null,gs=!0,!1)}function fs(o){return new Jt(o)}function cc(o,e){return fs(e).process(o)}var ur,hs,sc,ac,ps,gs,Jt,vs=xa(()=>{"use strict";In();Et();ur=Ee("ReasoningQEC"),hs={minPaths:3,confidenceThreshold:.5,majorityThreshold:.5,useNativeBackend:!0,votingMethod:"weighted"},sc={"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"]},ac=["analytical","empirical","heuristic"],ps=null,gs=!1;Jt=class{config;nativeAvailable=!1;constructor(e={}){this.config={...hs,...e}}async initialize(){if(this.config.useNativeBackend){let e=we();(e.useQEFlashAttention||e.useQEGNNIndex)&&(this.nativeAvailable=await oc())}}generatePaths(e){let t=Math.max(this.config.minPaths,3),n=sc[e.type]??ac,r=[];for(let i=0;i<t;i++){let a=n[i%n.length],s=this.generatePathSteps(e,i,a),c=this.deriveConclusion(s,a),l=this.calculatePathConfidence(s);r.push({id:i,steps:s,conclusion:c,confidence:l})}return ur.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 a=new Map;for(let l of e){let u=l.steps[i];if(!u)continue;let d=a.get(u.conclusion)??[];d.push(l.id),a.set(u.conclusion,d)}if(a.size<=1)continue;let s=[...a.entries()].map(([l,u])=>u.map(d=>({pathId:d,conclusion:l}))).flat(),c=this.classifySyndromeSeverity(a,e.length);t.push({stepIndex:i,disagreements:s,severity:c})}let r=new Map;for(let i of e){let a=r.get(i.conclusion)??[];a.push(i.id),r.set(i.conclusion,a)}if(r.size>1){let i=[...r.entries()].map(([s,c])=>c.map(l=>({pathId:l,conclusion:s}))).flat(),a=this.classifySyndromeSeverity(r,e.length);t.push({stepIndex:-1,disagreements:i,severity:a})}return ur.debug(`Extracted ${t.length} syndromes: ${t.filter(i=>i.severity==="critical").length} critical, ${t.filter(i=>i.severity==="major").length} major, ${t.filter(i=>i.severity==="minor").length} minor`),t}correctErrors(e,t){if(e.length===0)return{steps:[],conclusion:"",confidence:0,corrections:[],syndromeCount:t.length};let n=new Set(t.filter(u=>u.stepIndex>=0).map(u=>u.stepIndex)),r=Math.max(...e.map(u=>u.steps.length)),i=[],a=[];for(let u=0;u<r;u++)if(n.has(u)){let{step:d,correction:m}=this.correctStep(e,u);i.push(d),m&&a.push(m)}else{let d=e[0].steps[u];d&&i.push({...d})}let s=this.correctConclusion(e),c=this.calculateCorrectedConfidence(e,t),l={steps:i,conclusion:s,confidence:c,corrections:a,syndromeCount:t.length};return ur.debug(`Error correction applied: ${a.length} corrections, confidence: ${c.toFixed(3)}`),l}validate(e){let t=[];e.confidence<this.config.confidenceThreshold&&t.push({stepIndex:-1,type:"low-confidence",description:`Overall confidence ${e.confidence.toFixed(3)} is below threshold ${this.config.confidenceThreshold}`});for(let i of e.steps)i.evidence.length===0&&t.push({stepIndex:i.index,type:"inconsistent-evidence",description:`Step ${i.index} has no supporting evidence`});e.syndromeCount>0&&e.confidence<.3&&t.push({stepIndex:-1,type:"all-divergent",description:`${e.syndromeCount} syndromes with confidence ${e.confidence.toFixed(3)} suggests all paths diverged significantly`});for(let i of e.corrections)i.reason.includes("no clear majority")&&t.push({stepIndex:i.stepIndex,type:"no-majority",description:`Step ${i.stepIndex}: ${i.reason}`});let n=t.length===0,r=n?e.confidence:e.confidence*(1-t.length*.1);return{valid:n,confidence:Math.max(0,r),issues:t}}process(e){let t=this.generatePaths(e),n=this.extractSyndromes(t),r=this.correctErrors(t,n),i=this.validate(r);return{paths:t,syndromes:n,corrected:r,validation:i}}getConfig(){return{...this.config}}isNativeAvailable(){return this.nativeAvailable}generatePathSteps(e,t,n){return e.steps.map((r,i)=>{let a=this.generateStepConclusion(r,n,e.context,t),s=this.gatherEvidence(r,n,e.context);return{index:i,description:`[${n}] ${r}`,conclusion:a,evidence:s}})}generateStepConclusion(e,t,n,r){let i=Object.keys(n).sort(),a={0:l=>l.length>0?`Focused on ${l[0]}`:"Primary analysis",1:l=>l.length>1?`Focused on ${l[l.length-1]}`:"Secondary analysis",2:l=>l.length>0?`Cross-referencing ${l.join(" and ")}`:"Holistic analysis"},c=(a[r%3]??a[0])(i);return`[${t}] ${e}: ${c}`}gatherEvidence(e,t,n){let r=[];r.push(`Analysis via ${t}: ${e}`);for(let[i,a]of Object.entries(n))(typeof a=="string"||typeof a=="number"||typeof a=="boolean")&&r.push(`Context[${i}]: ${String(a)}`);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 y=n.get(h.conclusion)??0,v=i?g.confidence:1;n.set(h.conclusion,y+v),r.set(h.conclusion,h)}if(n.size===0)return{step:{index:t,description:`Step ${t} (no data)`,conclusion:"",evidence:[]},correction:null};let a=[...n.entries()].sort((g,h)=>h[1]-g[1]||g[0].localeCompare(h[0])),[s,c]=a[0],l=r.get(s),u=new Set;for(let g of e){let h=g.steps[t];if(h)for(let y of h.evidence)u.add(y)}let d={index:t,description:l.description,conclusion:s,evidence:[...u]},m=e[0].steps[t]?.conclusion,p=null;if(m&&m!==s){let g=e.filter(C=>C.steps[t]).length,h=[...n.values()].reduce((C,b)=>C+b,0),v=c/h>this.config.majorityThreshold;p={stepIndex:t,original:m,corrected:s,reason:v?`${i?"Weighted vote":"Majority vote"} (${c.toFixed(2)}/${h.toFixed(2)} weight from ${g} paths)`:`Selected highest ${i?"weight":"count"} (${c.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 a=t.get(i.conclusion)??0,s=n?i.confidence:1;t.set(i.conclusion,a+s)}return[...t.entries()].sort((i,a)=>a[1]-i[1]||i[0].localeCompare(a[0]))[0]?.[0]??""}calculateCorrectedConfidence(e,t){let n=e.reduce((l,u)=>l+u.confidence,0)/e.length,r=t.filter(l=>l.severity==="critical").length,i=t.filter(l=>l.severity==="major").length,a=t.filter(l=>l.severity==="minor").length,s=r*.2+i*.1+a*.03,c=t.length===0?.1:0;return Math.max(0,Math.min(1,n-s+c))}}});k();Q();import*as _ from"fs/promises";import*as I from"path";import{createHash as Da}from"crypto";var _a={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"}},Gn=class{baseDir;resultsDir;constructor(e=".agentic-qe"){this.baseDir=e,this.resultsDir=I.join(e,"results")}async save(e,t,n,r={}){let i=new Date,a=[];if(process.env.AQE_MEMORY_BACKEND==="memory")return{taskId:e,taskType:t,timestamp:i,files:a,summary:this.extractSummary(t,n)};await this.ensureDirectories(t);let s=this.formatTimestamp(i),c=r.filenamePrefix||s;switch(t){case"generate-tests":a.push(...await this.saveTestGeneration(n,c,r));break;case"analyze-coverage":a.push(...await this.saveCoverage(n,c,r));break;case"scan-security":a.push(...await this.saveSecurityScan(n,c,r));break;case"assess-quality":a.push(...await this.saveQualityAssessment(n,c,r));break;case"index-code":a.push(...await this.saveCodeIndex(n,c,r));break;case"predict-defects":a.push(...await this.saveDefectPrediction(n,c,r));break;case"validate-contracts":a.push(...await this.saveContractValidation(n,c,r));break;case"test-accessibility":a.push(...await this.saveAccessibilityTest(n,c,r));break;case"run-chaos":a.push(...await this.saveChaosTest(n,c,r));break;default:a.push(...await this.saveGeneric(t,n,c))}let l=this.extractSummary(t,n);return await this.updateIndex(e,t,i,a,l),{taskId:e,taskType:t,timestamp:i,files:a,summary:l}}async saveTestGeneration(e,t,n){let r=[],i=e,a=I.join(this.resultsDir,"tests","generated");await _.mkdir(a,{recursive:!0});let s=I.join(this.resultsDir,"tests",`${t}_manifest.json`),c=JSON.stringify({generated:new Date().toISOString(),testsGenerated:i.testsGenerated,coverageEstimate:i.coverageEstimate,patternsUsed:i.patternsUsed,language:n.language||"typescript",framework:n.framework||"vitest",tests:i.tests},null,2);if(await _.writeFile(s,c),r.push(await this.createFileEntry(s,"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=I.join(a,p);await _.writeFile(g,d.code),r.push(await this.createFileEntry(g,"source"))}}let l=I.join(this.resultsDir,"tests",`${t}_report.md`),u=this.generateTestReport(i,n);return await _.writeFile(l,u),r.push(await this.createFileEntry(l,"markdown")),r}async saveCoverage(e,t,n){let r=[],i=e,a=I.join(this.resultsDir,"coverage"),s=I.join(a,`${t}_coverage.json`);if(await _.writeFile(s,JSON.stringify(i,null,2)),r.push(await this.createFileEntry(s,"json")),n.includeSecondary!==!1&&i.measured===!0){let u=I.join(a,`${t}_coverage.lcov`),d=this.generateLcov(i);await _.writeFile(u,d),r.push(await this.createFileEntry(u,"lcov"))}let c=I.join(a,`${t}_report.md`),l=this.generateCoverageReport(i);return await _.writeFile(c,l),r.push(await this.createFileEntry(c,"markdown")),r}async saveSecurityScan(e,t,n){let r=[],i=e,a=I.join(this.resultsDir,"security"),s=I.join(a,`${t}_scan.json`);if(await _.writeFile(s,JSON.stringify(i,null,2)),r.push(await this.createFileEntry(s,"json")),n.includeSecondary!==!1){let u=I.join(a,`${t}_scan.sarif`),d=this.generateSarif(i);await _.writeFile(u,d),r.push(await this.createFileEntry(u,"sarif"))}let c=I.join(a,`${t}_report.md`),l=this.generateSecurityReport(i);return await _.writeFile(c,l),r.push(await this.createFileEntry(c,"markdown")),r}async saveQualityAssessment(e,t,n){let r=[],i=e,a=I.join(this.resultsDir,"quality"),s=I.join(a,`${t}_assessment.json`);await _.writeFile(s,JSON.stringify(i,null,2)),r.push(await this.createFileEntry(s,"json"));let c=I.join(a,`${t}_report.md`),l=this.generateQualityReport(i);return await _.writeFile(c,l),r.push(await this.createFileEntry(c,"markdown")),r}async saveCodeIndex(e,t,n){let r=[],i=e,a=I.join(this.resultsDir,"code-index");await _.mkdir(a,{recursive:!0});let s=I.join(a,`${t}_index.json`);return await _.writeFile(s,JSON.stringify(i,null,2)),r.push(await this.createFileEntry(s,"json")),r}async saveDefectPrediction(e,t,n){let r=[],i=I.join(this.resultsDir,"defects");await _.mkdir(i,{recursive:!0});let a=I.join(i,`${t}_prediction.json`);return await _.writeFile(a,JSON.stringify(e,null,2)),r.push(await this.createFileEntry(a,"json")),r}async saveContractValidation(e,t,n){let r=[],i=I.join(this.resultsDir,"contracts");await _.mkdir(i,{recursive:!0});let a=I.join(i,`${t}_validation.json`);return await _.writeFile(a,JSON.stringify(e,null,2)),r.push(await this.createFileEntry(a,"json")),r}async saveAccessibilityTest(e,t,n){let r=[],i=I.join(this.resultsDir,"accessibility");await _.mkdir(i,{recursive:!0});let a=I.join(i,`${t}_test.json`);return await _.writeFile(a,JSON.stringify(e,null,2)),r.push(await this.createFileEntry(a,"json")),r}async saveChaosTest(e,t,n){let r=[],i=I.join(this.resultsDir,"chaos");await _.mkdir(i,{recursive:!0});let a=I.join(i,`${t}_chaos.json`);return await _.writeFile(a,JSON.stringify(e,null,2)),r.push(await this.createFileEntry(a,"json")),r}async saveGeneric(e,t,n){let r=[],i=I.join(this.resultsDir,"other");await _.mkdir(i,{recursive:!0});let a=I.join(i,`${n}_${e}.json`);return await _.writeFile(a,JSON.stringify(t,null,2)),r.push(await this.createFileEntry(a,"json")),r}generateLcov(e){let t=Math.round(e.lineCoverage??0);return`TN:agentic-qe-coverage
3
3
  SF:summary
4
4
  DA:1,${t}
5
5
  LF:100
@@ -108,7 +108,7 @@ ${Object.entries(e.metrics).map(([t,n])=>`| ${t} | ${n.toFixed(1)} |`).join(`
108
108
 
109
109
  ${e.recommendations.length===0?"No recommendations - all quality gates passed.":e.recommendations.map((t,n)=>`${n+1}. ${t}`).join(`
110
110
  `)}
111
- `}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=Ea[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=Sa("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 a=D.join(this.resultsDir,"index.json"),s;try{let c=await _.readFile(a,"utf-8");s=A(c)}catch{s={version:"1.0",created:new Date().toISOString(),updated:new Date().toISOString(),results:[],trends:{}}}s.results.push({id:e,type:t,timestamp:n.toISOString(),files:r.map(c=>D.relative(this.resultsDir,c.path)),summary:i}),s.updated=new Date().toISOString(),s.results.length>100&&(s.results=s.results.slice(-100)),await _.writeFile(a,JSON.stringify(s,null,2))}};function Di(o){return new Ln(o)}An();ae();Q();var Ba=["think","thinking","reasoning","reasoning_scratchpad"],Ua=new RegExp(`<(${Ba.join("|")})(?:\\s[^>]*)?>[\\s\\S]*?</\\1\\s*>`,"gi");function W(o){if(!o||typeof o!="string"||!o.includes("<"))return o;let e=o;for(let t=0;t<5;t++){let n=e.replace(Ua," ");if(n===e)break;e=n}return e===o?o:e.replace(/[ \t]{2,}/g," ").trim()}function kt(o){if(typeof o=="string")return W(o);if(Array.isArray(o))return o.map(e=>kt(e));if(o!==null&&typeof o=="object"){let e={};for(let[t,n]of Object.entries(o))e[t]=kt(n);return e}return o}var Ha={maxStepsPerTrajectory:100,autoEndTimeoutMs:1800*1e3,minQualityThreshold:.5,recentBufferSize:100},Mt=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={...Ha,...e},this.recentTrajectories=new Te(this.config.recentBufferSize)}async initialize(){this.initialized||(this.unifiedMemory=U(),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(`
111
+ `}async ensureDirectories(e){let t=[this.resultsDir,I.join(this.resultsDir,"security"),I.join(this.resultsDir,"coverage"),I.join(this.resultsDir,"quality"),I.join(this.resultsDir,"tests"),I.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=_a[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=Da("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 a=I.join(this.resultsDir,"index.json"),s;try{let c=await _.readFile(a,"utf-8");s=A(c)}catch{s={version:"1.0",created:new Date().toISOString(),updated:new Date().toISOString(),results:[],trends:{}}}s.results.push({id:e,type:t,timestamp:n.toISOString(),files:r.map(c=>I.relative(this.resultsDir,c.path)),summary:i}),s.updated=new Date().toISOString(),s.results.length>100&&(s.results=s.results.slice(-100)),await _.writeFile(a,JSON.stringify(s,null,2))}};function zi(o){return new Gn(o)}In();oe();Q();var Za=["think","thinking","reasoning","reasoning_scratchpad"],eo=new RegExp(`<(${Za.join("|")})(?:\\s[^>]*)?>[\\s\\S]*?</\\1\\s*>`,"gi");function W(o){if(!o||typeof o!="string"||!o.includes("<"))return o;let e=o;for(let t=0;t<5;t++){let n=e.replace(eo," ");if(n===e)break;e=n}return e===o?o:e.replace(/[ \t]{2,}/g," ").trim()}function Dt(o){if(typeof o=="string")return W(o);if(Array.isArray(o))return o.map(e=>Dt(e));if(o!==null&&typeof o=="object"){let e={};for(let[t,n]of Object.entries(o))e[t]=Dt(n);return e}return o}var to={maxStepsPerTrajectory:100,autoEndTimeoutMs:1800*1e3,minQualityThreshold:.5,recentBufferSize:100},_t=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={...to,...e},this.recentTrajectories=new Se(this.config.recentBufferSize)}async initialize(){this.initialized||(this.unifiedMemory=U(),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(`
112
112
  UPDATE qe_trajectories
113
113
  SET success = 0,
114
114
  ended_at = datetime('now'),
@@ -168,9 +168,9 @@ ${e.recommendations.length===0?"No recommendations - all quality gates passed.":
168
168
  WHERE domain = ? AND success = 1
169
169
  ORDER BY ended_at DESC
170
170
  LIMIT ?
171
- `))}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=W(e);let n=q(),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 a=q(),s=r.quality??this.calculateStepQuality(n);t=W(t),n={...n,data:n.data?kt(n.data):n.data,error:n.error?W(n.error):n.error};let c={id:a,action:t,result:n,quality:s,durationMs:r.durationMs??0,timestamp:new Date,context:r.context,tokensUsed:r.tokensUsed};i.steps.push(c);let l=this.prepared.get("insertStep");l&&l.run(a,e,i.steps.length-1,t,n.outcome,s,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+=s,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,a=this.calculateMetrics(r.steps),s;t&&a.averageQuality>=this.config.minQualityThreshold?s="success":t?s="partial":s="failure";let c={id:e,task:r.task,agent:r.agent,domain:r.domain,steps:r.steps,outcome:s,metrics:a,startedAt:r.startedAt,endedAt:i,feedback:n},l=this.prepared.get("updateTrajectory");return l&&l.run(i.toISOString(),t?1:0,JSON.stringify(r.steps),JSON.stringify({metrics:a,context:r.context}),null,n??null,null,e),this.activeTrajectories.delete(e),this.recentTrajectories.push(c),this.stats.trajectoriesCompleted++,c}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 a of r){let s=await this.rowToTrajectory(a);s&&i.push(s)}return i}async findSimilarTrajectories(e,t=5){this.ensureInitialized();let n=e.toLowerCase().split(/\s+/).filter(a=>a.length>3);return this.recentTrajectories.toArray().map(a=>{let s=a.task.toLowerCase(),c=n.filter(l=>s.includes(l)).length;return{trajectory:a,score:c/n.length}}).filter(a=>a.score>.2).sort((a,s)=>s.score-a.score).slice(0,t).map(a=>a.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(`
171
+ `))}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=W(e);let n=q(),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 a=q(),s=r.quality??this.calculateStepQuality(n);t=W(t),n={...n,data:n.data?Dt(n.data):n.data,error:n.error?W(n.error):n.error};let c={id:a,action:t,result:n,quality:s,durationMs:r.durationMs??0,timestamp:new Date,context:r.context,tokensUsed:r.tokensUsed};i.steps.push(c);let l=this.prepared.get("insertStep");l&&l.run(a,e,i.steps.length-1,t,n.outcome,s,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+=s,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,a=this.calculateMetrics(r.steps),s;t&&a.averageQuality>=this.config.minQualityThreshold?s="success":t?s="partial":s="failure";let c={id:e,task:r.task,agent:r.agent,domain:r.domain,steps:r.steps,outcome:s,metrics:a,startedAt:r.startedAt,endedAt:i,feedback:n},l=this.prepared.get("updateTrajectory");return l&&l.run(i.toISOString(),t?1:0,JSON.stringify(r.steps),JSON.stringify({metrics:a,context:r.context}),null,n??null,null,e),this.activeTrajectories.delete(e),this.recentTrajectories.push(c),this.stats.trajectoriesCompleted++,c}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 a of r){let s=await this.rowToTrajectory(a);s&&i.push(s)}return i}async findSimilarTrajectories(e,t=5){this.ensureInitialized();let n=e.toLowerCase().split(/\s+/).filter(a=>a.length>3);return this.recentTrajectories.toArray().map(a=>{let s=a.task.toLowerCase(),c=n.filter(l=>s.includes(l)).length;return{trajectory:a,score:c/n.length}}).filter(a=>a.score>.2).sort((a,s)=>s.score-a.score).slice(0,t).map(a=>a.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(`
172
172
  DELETE FROM qe_trajectories WHERE ended_at < ?
173
- `).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,a=0;for(let u of e)t+=u.durationMs,i+=u.quality,a+=u.tokensUsed??0,u.result.outcome==="success"?n++:u.result.outcome==="failure"&&r++;let s=i/e.length,l=n/e.length*s;return{totalDurationMs:t,successfulSteps:n,failedSteps:r,averageQuality:s,totalTokensUsed:a,efficiencyScore:l}}async rowToTrajectory(e){if(!e)return null;let t=this.prepared.get("getSteps"),n=[];if(t)n=t.all(e.id).map(s=>({id:s.id,action:s.action,result:{outcome:s.outcome,data:s.result_data?A(s.result_data):void 0,error:s.error_message??void 0,metrics:s.metrics_json?A(s.metrics_json):void 0},quality:s.quality,durationMs:s.duration_ms,timestamp:new Date(s.timestamp),context:s.context_json?A(s.context_json):void 0,tokensUsed:s.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 Nn(o={}){return new Mt(o)}ae();Q();Ct();var Va={minQualityThreshold:.6,maxExperiencesPerDomain:500,similarityThreshold:.7,topK:5,embedding:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0},autoPrune:!0,pruneThreshold:.3},Dt=class{config;unifiedMemory=null;db=null;prepared=new Map;initialized=!1;initializationPromise=null;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={...Va,...e},this.recentExperiences=new Te(100),this.hnswIndex=new Qr({dimension:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"})}async initialize(){if(!this.initialized){if(this.initializationPromise)return this.initializationPromise;this.initializationPromise=this.initializeOnce();try{await this.initializationPromise}catch(e){throw this.initializationPromise=null,e}}}async initializeOnce(){this.unifiedMemory=U(),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(`
173
+ `).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,a=0;for(let u of e)t+=u.durationMs,i+=u.quality,a+=u.tokensUsed??0,u.result.outcome==="success"?n++:u.result.outcome==="failure"&&r++;let s=i/e.length,l=n/e.length*s;return{totalDurationMs:t,successfulSteps:n,failedSteps:r,averageQuality:s,totalTokensUsed:a,efficiencyScore:l}}async rowToTrajectory(e){if(!e)return null;let t=this.prepared.get("getSteps"),n=[];if(t)n=t.all(e.id).map(s=>({id:s.id,action:s.action,result:{outcome:s.outcome,data:s.result_data?A(s.result_data):void 0,error:s.error_message??void 0,metrics:s.metrics_json?A(s.metrics_json):void 0},quality:s.quality,durationMs:s.duration_ms,timestamp:new Date(s.timestamp),context:s.context_json?A(s.context_json):void 0,tokensUsed:s.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 $n(o={}){return new _t(o)}oe();Q();Et();var no={minQualityThreshold:.6,maxExperiencesPerDomain:500,similarityThreshold:.7,topK:5,embedding:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0},autoPrune:!0,pruneThreshold:.3},Ot=class{config;unifiedMemory=null;db=null;prepared=new Map;initialized=!1;initializationPromise=null;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={...no,...e},this.recentExperiences=new Se(100),this.hnswIndex=new ri({dimension:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"})}async initialize(){if(!this.initialized){if(this.initializationPromise)return this.initializationPromise;this.initializationPromise=this.initializeOnce();try{await this.initializationPromise}catch(e){throw this.initializationPromise=null,e}}}async initializeOnce(){this.unifiedMemory=U(),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(`
174
174
  SELECT id, domain, task FROM captured_experiences
175
175
  WHERE embedding IS NULL AND consolidated_into IS NULL
176
176
  LIMIT 200
@@ -178,11 +178,11 @@ ${e.recommendations.length===0?"No recommendations - all quality gates passed.":
178
178
  UPDATE captured_experiences
179
179
  SET embedding = ?, embedding_dimension = ?
180
180
  WHERE id = ?
181
- `),n=0;for(let r of e){let i=W(`${r.domain??""}: ${r.task}`).slice(0,512),a=await we(i),s=Buffer.from(new Float32Array(a).buffer);t.run(s,a.length,r.id);let c=this.nextHnswId++;this.hnswIndex.addEmbedding({vector:a,dimension:384,namespace:"experiences",text:r.id,timestamp:Date.now(),quantization:"none",metadata:{}},c),this.idToExperienceId.set(c,r.id),this.experienceIdToHnswId.set(r.id,c),n++}console.log(`[ExperienceReplay] Backfilled ${n} captured_experiences embeddings`)}catch(e){console.warn("[ExperienceReplay] Embedding backfill failed:",e instanceof Error?e.message:e)}})(),(async()=>{try{if(!this.db||!this.db.prepare("PRAGMA table_info(qe_trajectories)").all().some(i=>i.name==="embedding"))return;let t=this.db.prepare(`
181
+ `),n=0;for(let r of e){let i=W(`${r.domain??""}: ${r.task}`).slice(0,512),a=await Re(i),s=Buffer.from(new Float32Array(a).buffer);t.run(s,a.length,r.id);let c=this.nextHnswId++;this.hnswIndex.addEmbedding({vector:a,dimension:384,namespace:"experiences",text:r.id,timestamp:Date.now(),quantization:"none",metadata:{}},c),this.idToExperienceId.set(c,r.id),this.experienceIdToHnswId.set(r.id,c),n++}console.log(`[ExperienceReplay] Backfilled ${n} captured_experiences embeddings`)}catch(e){console.warn("[ExperienceReplay] Embedding backfill failed:",e instanceof Error?e.message:e)}})(),(async()=>{try{if(!this.db||!this.db.prepare("PRAGMA table_info(qe_trajectories)").all().some(i=>i.name==="embedding"))return;let t=this.db.prepare(`
182
182
  SELECT id, domain, task FROM qe_trajectories
183
183
  WHERE embedding IS NULL AND ended_at IS NOT NULL
184
184
  LIMIT 200
185
- `).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 a=W(`${i.domain??""}: ${i.task}`).slice(0,512),s=await we(a);n.run(Buffer.from(new Float32Array(s).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)}})(),Ee().useReservoirReplay&&(this.reservoirBuffer=new Kr({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(`
185
+ `).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 a=W(`${i.domain??""}: ${i.task}`).slice(0,512),s=await Re(a);n.run(Buffer.from(new Float32Array(s).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)}})(),we().useReservoirReplay&&(this.reservoirBuffer=new si({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(`
186
186
  CREATE TABLE IF NOT EXISTS captured_experiences (
187
187
  id TEXT PRIMARY KEY,
188
188
  task TEXT NOT NULL,
@@ -256,7 +256,7 @@ ${e.recommendations.length===0?"No recommendations - all quality gates passed.":
256
256
  VALUES (?, ?, ?, ?, ?, ?)
257
257
  `)),this.prepared.set("countByDomain",this.db.prepare(`
258
258
  SELECT domain, COUNT(*) as count FROM captured_experiences WHERE consolidated_into IS NULL GROUP BY domain
259
- `))}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++,a={vector:r,dimension:384,namespace:"experiences",text:n.id,timestamp:Date.now(),quantization:"none",metadata:{}};this.hnswIndex.addEmbedding(a,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=W(e.task);t=W(t);let i=e.steps.filter(m=>m.result.outcome==="success").map(m=>W(m.action)),a=`${r} ${t} ${i.join(" ")}`,s=await we(a,this.config.embedding),c=q(),l=e.domain||"test-generation",u={id:c,trajectoryId:e.id,task:r,domain:l,strategy:t,keyActions:i,qualityScore:e.metrics.efficiencyScore,applicationCount:0,successRate:1,avgTokenSavings:0,embedding:s,createdAt:new Date,originalMetrics:e.metrics,tags:n},d=this.prepared.get("insertExperience");if(d){let m=s?this.floatArrayToBuffer(s):null;d.run(c,r,t,l,e.metrics.efficiencyScore,JSON.stringify(i),JSON.stringify(e.metrics),m,s?.length??null,JSON.stringify(n))}if(s){let m=this.nextHnswId++,p={vector:s,dimension:384,namespace:"experiences",text:c,timestamp:Date.now(),quantization:"none",metadata:{}};this.hnswIndex.addEmbedding(p,m),this.idToExperienceId.set(m,c),this.experienceIdToHnswId.set(c,m)}return this.recentExperiences.push(u),this.reservoirBuffer&&this.reservoirBuffer.admit(u.id,u,u.qualityScore),this.stats.experiencesStored++,this.config.autoPrune&&await this.autoConsolidate(l),u}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(y=>y.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 s=i[0].experience.strategy,c=new Map;for(let p of i)for(let g of p.experience.keyActions)c.set(g,(c.get(g)||0)+p.weight);let l=Array.from(c.entries()).sort((p,g)=>g[1]-p[1]).slice(0,5).map(([p])=>p),u=[],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:s,suggestedActions:l,pitfallsToAvoid:u,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=W(e);let a={vector:await we(e,this.config.embedding),dimension:384,namespace:"experiences",text:e,timestamp:Date.now(),quantization:"none",metadata:{}},s=t?r*4:r*2,c=this.hnswIndex.search(a,{limit:s,namespace:"experiences"}),l=[],u=this.prepared.get("getExperience");for(let{id:d,distance:m}of c){let p=1-m;if(p<this.config.similarityThreshold)continue;let g=this.idToExperienceId.get(d);if(g&&u){let h=u.get(g);if(h){if(t&&h.domain!==t)continue;let y=this.rowToExperience(h);if(y&&(l.push({experience:y,similarity:p}),l.length>=r))break}}}return l}async recordApplication(e,t,n,r=0,i){this.ensureInitialized();let a=this.prepared.get("updateApplication");a&&a.run(r,e);let s=this.prepared.get("insertApplication");s&&s.run(q(),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 Wr;await i.initialize(this.db);let a=await i.consolidateDomain(e,r);return a.merged>0&&await this.loadEmbeddingIndex(),console.log(`[ExperienceReplay] Auto-consolidated ${e}: ${a.merged} merged, ${a.archived} archived`),a.merged+a.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 qn(o={}){return new Dt(o)}ae();Q();var Qa={driftThreshold:.3,mergeSimilarityThreshold:.85,minQualityForRetention:.3,obsoleteDaysThreshold:60,maxPatternsPerDomain:200,embedding:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0},historyBufferSize:500},It=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={...Qa,...e},this.recentEvents=new Te(this.config.historyBufferSize)}async initialize(){this.initialized||(this.unifiedMemory=U(),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(`
259
+ `))}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++,a={vector:r,dimension:384,namespace:"experiences",text:n.id,timestamp:Date.now(),quantization:"none",metadata:{}};this.hnswIndex.addEmbedding(a,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=W(e.task);t=W(t);let i=e.steps.filter(m=>m.result.outcome==="success").map(m=>W(m.action)),a=`${r} ${t} ${i.join(" ")}`,s=await Re(a,this.config.embedding),c=q(),l=e.domain||"test-generation",u={id:c,trajectoryId:e.id,task:r,domain:l,strategy:t,keyActions:i,qualityScore:e.metrics.efficiencyScore,applicationCount:0,successRate:1,avgTokenSavings:0,embedding:s,createdAt:new Date,originalMetrics:e.metrics,tags:n},d=this.prepared.get("insertExperience");if(d){let m=s?this.floatArrayToBuffer(s):null;d.run(c,r,t,l,e.metrics.efficiencyScore,JSON.stringify(i),JSON.stringify(e.metrics),m,s?.length??null,JSON.stringify(n))}if(s){let m=this.nextHnswId++,p={vector:s,dimension:384,namespace:"experiences",text:c,timestamp:Date.now(),quantization:"none",metadata:{}};this.hnswIndex.addEmbedding(p,m),this.idToExperienceId.set(m,c),this.experienceIdToHnswId.set(c,m)}return this.recentExperiences.push(u),this.reservoirBuffer&&this.reservoirBuffer.admit(u.id,u,u.qualityScore),this.stats.experiencesStored++,this.config.autoPrune&&await this.autoConsolidate(l),u}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(y=>y.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 s=i[0].experience.strategy,c=new Map;for(let p of i)for(let g of p.experience.keyActions)c.set(g,(c.get(g)||0)+p.weight);let l=Array.from(c.entries()).sort((p,g)=>g[1]-p[1]).slice(0,5).map(([p])=>p),u=[],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:s,suggestedActions:l,pitfallsToAvoid:u,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=W(e);let a={vector:await Re(e,this.config.embedding),dimension:384,namespace:"experiences",text:e,timestamp:Date.now(),quantization:"none",metadata:{}},s=t?r*4:r*2,c=this.hnswIndex.search(a,{limit:s,namespace:"experiences"}),l=[],u=this.prepared.get("getExperience");for(let{id:d,distance:m}of c){let p=1-m;if(p<this.config.similarityThreshold)continue;let g=this.idToExperienceId.get(d);if(g&&u){let h=u.get(g);if(h){if(t&&h.domain!==t)continue;let y=this.rowToExperience(h);if(y&&(l.push({experience:y,similarity:p}),l.length>=r))break}}}return l}async recordApplication(e,t,n,r=0,i){this.ensureInitialized();let a=this.prepared.get("updateApplication");a&&a.run(r,e);let s=this.prepared.get("insertApplication");s&&s.run(q(),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 ii;await i.initialize(this.db);let a=await i.consolidateDomain(e,r);return a.merged>0&&await this.loadEmbeddingIndex(),console.log(`[ExperienceReplay] Auto-consolidated ${e}: ${a.merged} merged, ${a.archived} archived`),a.merged+a.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 zn(o={}){return new Ot(o)}oe();Q();var ro={driftThreshold:.3,mergeSimilarityThreshold:.85,minQualityForRetention:.3,obsoleteDaysThreshold:60,maxPatternsPerDomain:200,embedding:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0},historyBufferSize:500},Nt=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={...ro,...e},this.recentEvents=new Se(this.config.historyBufferSize)}async initialize(){this.initialized||(this.unifiedMemory=U(),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(`
260
260
  CREATE TABLE IF NOT EXISTS pattern_versions (
261
261
  id TEXT PRIMARY KEY,
262
262
  pattern_id TEXT NOT NULL,
@@ -328,7 +328,7 @@ ${e.recommendations.length===0?"No recommendations - all quality gates passed.":
328
328
  FROM qe_patterns
329
329
  WHERE qe_domain = ? AND quality_score < ?
330
330
  ORDER BY quality_score ASC
331
- `))}async loadEmbeddingCache(){let e=this.prepared.get("getAllPatternEmbeddings");if(!e)return;let t=e.all();this.embeddingCache.clear();for(let n of t){let r=this.bufferToFloatArray(n.embedding,n.dimension);this.embeddingCache.set(n.pattern_id,r)}console.log(`[PatternEvolution] Loaded ${this.embeddingCache.size} pattern embeddings`)}async trackVersion(e,t,n=[],r="manual"){this.ensureInitialized();let s=(this.prepared.get("getVersionCount")?.get(e)?.count??0)+1,l=this.prepared.get("getPattern")?.get(e),u=q(),d={id:u,patternId:e,version:s,embedding:t,changes:n,qualityScore:l?.quality_score??.5,successRate:l?.success_rate??.5,timestamp:new Date,trigger:r},m=this.prepared.get("insertVersion");if(m){let p=this.floatArrayToBuffer(t);m.run(u,e,s,p,t.length,JSON.stringify(n),d.qualityScore,d.successRate,r)}return this.embeddingCache.set(e,t),await this.recordEvent(e,"updated",{version:s,changes:n,trigger:r}),this.stats.versionsTracked++,d}async detectDrift(e){this.ensureInitialized(),this.stats.driftDetections++;let t=this.prepared.get("getVersionHistory");if(!t)return null;let n=t.all(e,10);if(n.length<2)return null;let r=n[0],i=n[n.length-1],a=this.bufferToFloatArray(r.embedding,r.embedding_dimension),s=this.bufferToFloatArray(i.embedding,i.embedding_dimension),l=1-bt(a,s),u=l>this.config.driftThreshold;u&&this.stats.significantDrifts++;let d,m;return l<.1?(d="keep",m="Pattern is stable with minimal drift"):l<this.config.driftThreshold?(d="keep",m="Drift is within acceptable range"):l<.6?(d="update",m="Moderate drift detected - consider versioning"):l<.8?(d="split",m="Significant drift - pattern may represent multiple concepts"):(d="archive",m="Severe drift - pattern has fundamentally changed"),{patternId:e,currentEmbedding:a,originalEmbedding:s,driftScore:l,hasSignificantDrift:u,recommendation:d,reason:m}}async findMergeCandidates(e){this.ensureInitialized();let t=this.prepared.get("getPatternEmbeddings");if(!t)return[];let n=t.all(e),r=[],i=this.prepared.get("getPattern");for(let a=0;a<n.length;a++)for(let s=a+1;s<n.length;s++){let c=this.bufferToFloatArray(n[a].embedding,n[a].dimension),l=this.bufferToFloatArray(n[s].embedding,n[s].dimension),u=bt(c,l);if(u>=this.config.mergeSimilarityThreshold){let d=i?.get(n[a].pattern_id),m=i?.get(n[s].pattern_id),p=((d?.quality_score??0)+(m?.quality_score??0))/2,g=u*p;r.push({patternId1:n[a].pattern_id,patternId2:n[s].pattern_id,similarity:u,mergeBenefit:g,suggestedName:`${d?.name??"Pattern"} + ${m?.name??"Pattern"}`})}}return r.sort((a,s)=>s.mergeBenefit-a.mergeBenefit)}async findPruneCandidates(e){this.ensureInitialized();let t=[],n=this.prepared.get("getPatternsForPruning");if(n){let i=n.all(e,this.config.minQualityForRetention);for(let a of i){let s=a.last_used_at?new Date(a.last_used_at):new Date(0),c=Math.floor((Date.now()-s.getTime())/(1e3*60*60*24)),l;c>this.config.obsoleteDaysThreshold?l="obsolete":(a.quality_score??0)<.2?l="low-quality":l="unused",t.push({patternId:a.id,name:a.name,reason:l,qualityScore:a.quality_score??0,daysSinceLastUse:c})}}let r=await this.findMergeCandidates(e);for(let i of r){let a=this.prepared.get("getPattern")?.get(i.patternId1),s=this.prepared.get("getPattern")?.get(i.patternId2);if(a&&s&&Math.abs((a.quality_score??0)-(s.quality_score??0))>.3){let l=(a.quality_score??0)<(s.quality_score??0)?a:s,u=(a.quality_score??0)>=(s.quality_score??0)?a:s;t.find(d=>d.patternId===l.id)||t.push({patternId:l.id,name:l.name,reason:"redundant",qualityScore:l.quality_score??0,daysSinceLastUse:0,similarPatterns:[u.id]})}}return t}async mergePatterns(e,t,n){if(this.ensureInitialized(),!this.db)return null;let r=this.prepared.get("getPattern"),i=r?.get(e),a=r?.get(t);if(!i||!a)return null;let[s,c]=(i.quality_score??0)>=(a.quality_score??0)?[i,a]:[a,i];n&&this.db.prepare("UPDATE qe_patterns SET name = ? WHERE id = ?").run(n,s.id);let l=(s.usage_count??0)+(c.usage_count??0),u=(s.successful_uses??0)+(c.successful_uses??0),d=l>0?u/l:0;this.db.prepare(`
331
+ `))}async loadEmbeddingCache(){let e=this.prepared.get("getAllPatternEmbeddings");if(!e)return;let t=e.all();this.embeddingCache.clear();for(let n of t){let r=this.bufferToFloatArray(n.embedding,n.dimension);this.embeddingCache.set(n.pattern_id,r)}console.log(`[PatternEvolution] Loaded ${this.embeddingCache.size} pattern embeddings`)}async trackVersion(e,t,n=[],r="manual"){this.ensureInitialized();let s=(this.prepared.get("getVersionCount")?.get(e)?.count??0)+1,l=this.prepared.get("getPattern")?.get(e),u=q(),d={id:u,patternId:e,version:s,embedding:t,changes:n,qualityScore:l?.quality_score??.5,successRate:l?.success_rate??.5,timestamp:new Date,trigger:r},m=this.prepared.get("insertVersion");if(m){let p=this.floatArrayToBuffer(t);m.run(u,e,s,p,t.length,JSON.stringify(n),d.qualityScore,d.successRate,r)}return this.embeddingCache.set(e,t),await this.recordEvent(e,"updated",{version:s,changes:n,trigger:r}),this.stats.versionsTracked++,d}async detectDrift(e){this.ensureInitialized(),this.stats.driftDetections++;let t=this.prepared.get("getVersionHistory");if(!t)return null;let n=t.all(e,10);if(n.length<2)return null;let r=n[0],i=n[n.length-1],a=this.bufferToFloatArray(r.embedding,r.embedding_dimension),s=this.bufferToFloatArray(i.embedding,i.embedding_dimension),l=1-St(a,s),u=l>this.config.driftThreshold;u&&this.stats.significantDrifts++;let d,m;return l<.1?(d="keep",m="Pattern is stable with minimal drift"):l<this.config.driftThreshold?(d="keep",m="Drift is within acceptable range"):l<.6?(d="update",m="Moderate drift detected - consider versioning"):l<.8?(d="split",m="Significant drift - pattern may represent multiple concepts"):(d="archive",m="Severe drift - pattern has fundamentally changed"),{patternId:e,currentEmbedding:a,originalEmbedding:s,driftScore:l,hasSignificantDrift:u,recommendation:d,reason:m}}async findMergeCandidates(e){this.ensureInitialized();let t=this.prepared.get("getPatternEmbeddings");if(!t)return[];let n=t.all(e),r=[],i=this.prepared.get("getPattern");for(let a=0;a<n.length;a++)for(let s=a+1;s<n.length;s++){let c=this.bufferToFloatArray(n[a].embedding,n[a].dimension),l=this.bufferToFloatArray(n[s].embedding,n[s].dimension),u=St(c,l);if(u>=this.config.mergeSimilarityThreshold){let d=i?.get(n[a].pattern_id),m=i?.get(n[s].pattern_id),p=((d?.quality_score??0)+(m?.quality_score??0))/2,g=u*p;r.push({patternId1:n[a].pattern_id,patternId2:n[s].pattern_id,similarity:u,mergeBenefit:g,suggestedName:`${d?.name??"Pattern"} + ${m?.name??"Pattern"}`})}}return r.sort((a,s)=>s.mergeBenefit-a.mergeBenefit)}async findPruneCandidates(e){this.ensureInitialized();let t=[],n=this.prepared.get("getPatternsForPruning");if(n){let i=n.all(e,this.config.minQualityForRetention);for(let a of i){let s=a.last_used_at?new Date(a.last_used_at):new Date(0),c=Math.floor((Date.now()-s.getTime())/(1e3*60*60*24)),l;c>this.config.obsoleteDaysThreshold?l="obsolete":(a.quality_score??0)<.2?l="low-quality":l="unused",t.push({patternId:a.id,name:a.name,reason:l,qualityScore:a.quality_score??0,daysSinceLastUse:c})}}let r=await this.findMergeCandidates(e);for(let i of r){let a=this.prepared.get("getPattern")?.get(i.patternId1),s=this.prepared.get("getPattern")?.get(i.patternId2);if(a&&s&&Math.abs((a.quality_score??0)-(s.quality_score??0))>.3){let l=(a.quality_score??0)<(s.quality_score??0)?a:s,u=(a.quality_score??0)>=(s.quality_score??0)?a:s;t.find(d=>d.patternId===l.id)||t.push({patternId:l.id,name:l.name,reason:"redundant",qualityScore:l.quality_score??0,daysSinceLastUse:0,similarPatterns:[u.id]})}}return t}async mergePatterns(e,t,n){if(this.ensureInitialized(),!this.db)return null;let r=this.prepared.get("getPattern"),i=r?.get(e),a=r?.get(t);if(!i||!a)return null;let[s,c]=(i.quality_score??0)>=(a.quality_score??0)?[i,a]:[a,i];n&&this.db.prepare("UPDATE qe_patterns SET name = ? WHERE id = ?").run(n,s.id);let l=(s.usage_count??0)+(c.usage_count??0),u=(s.successful_uses??0)+(c.successful_uses??0),d=l>0?u/l:0;this.db.prepare(`
332
332
  UPDATE qe_patterns SET
333
333
  usage_count = ?,
334
334
  successful_uses = ?,
@@ -342,7 +342,7 @@ ${e.recommendations.length===0?"No recommendations - all quality gates passed.":
342
342
  WHERE id = ?
343
343
  `).run(l,u,d,c.last_used_at,c.last_used_at,c.last_used_at,s.id);let m=this.prepared.get("insertRelationship");return m&&m.run(q(),c.id,s.id,"merged",1),this.db.prepare("UPDATE qe_patterns SET tier = 'archived' WHERE id = ?").run(c.id),await this.recordEvent(s.id,"merged",{absorbedFrom:c.id}),await this.recordEvent(c.id,"archived",{mergedInto:s.id}),this.stats.patternsMerged++,s.id}async autoConsolidate(e){this.ensureInitialized(),this.stats.consolidationRuns++;let t=0,n=0,r=await this.findMergeCandidates(e);for(let s of r.slice(0,5))await this.mergePatterns(s.patternId1,s.patternId2)&&t++;let i=await this.findPruneCandidates(e);for(let s of i)(s.reason==="low-quality"||s.reason==="obsolete")&&this.db&&(this.db.prepare("DELETE FROM qe_patterns WHERE id = ?").run(s.patternId),this.embeddingCache.delete(s.patternId),await this.recordEvent(s.patternId,"pruned",{reason:s.reason}),n++,this.stats.patternsPruned++);let a=this.db?.prepare(`
344
344
  SELECT COUNT(*) as count FROM qe_patterns WHERE qe_domain = ? AND tier != 'archived'
345
- `).get(e);return{merged:t,pruned:n,retained:a?.count??0}}async getEvolutionHistory(e,t=20){this.ensureInitialized();let i=(this.prepared.get("getVersionHistory")?.all(e,t)??[]).map(l=>({id:l.id,patternId:l.pattern_id,version:l.version,embedding:this.bufferToFloatArray(l.embedding,l.embedding_dimension),changes:A(l.changes||"[]"),qualityScore:l.quality_score,successRate:l.success_rate,timestamp:new Date(l.created_at),trigger:l.trigger})),c=(this.prepared.get("getEvents")?.all(e,t)??[]).map(l=>({id:l.id,patternId:l.pattern_id,eventType:l.event_type,details:A(l.details||"{}"),timestamp:new Date(l.created_at)}));return{versions:i,events:c}}async recordEvent(e,t,n){let r=this.prepared.get("insertEvent");if(r){let i={id:q(),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 Gn(o={}){return new It(o)}k();var Wa={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={...Wa,...e}}async initialize(){if(this.initialized)return;let e=performance.now();this.reasoningBank=_n(this.config.base),await this.reasoningBank.initialize(),this.config.enableTrajectories&&(this.trajectoryTracker=Nn(this.config.trajectoryTracker),await this.trajectoryTracker.initialize()),this.config.enableExperienceReplay&&(this.experienceReplay=qn(this.config.experienceReplay),await this.experienceReplay.initialize()),this.config.enablePatternEvolution&&(this.patternEvolution=Gn(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(a=>{console.warn(`[EnhancedAdapter] Failed to record experience application: ${a}`)})}}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 $(j(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 Zu(o={}){return new $n(o)}import{randomUUID as ao}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 _t=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}}},Ae=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 _t(this.config.cacheSize)}async initialize(){if(!this.isInitialized)try{let{computeRealEmbedding:e}=await import("./real-embeddings-6SO5MFRQ.js");this.onnxRuntime={generateEmbedding:async(t,n)=>{let r=await e(t);if(this.config.normalize){let i=Math.sqrt(r.reduce((a,s)=>a+s*s,0));if(i>0)return r.map(a=>a/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),a=i,s=!1;this.config.hyperbolic&&(a=this.euclideanToPoincare(i),s=!0);let c={vector:a,dimensions:a.length,model:this.config.model,isHyperbolic:s};return this.cache.set(t,c),this.totalGenerated++,this.generationTimes.push(Date.now()-r),this.generationTimes.length>100&&this.generationTimes.shift(),c}catch(i){throw new 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 a of e.texts){let s=this.getCacheKey(a),c=this.cache.get(s);if(c)r.push(c),n++;else{let l=await this.generate(a);r.push(l)}}return{embeddings:r,duration:Date.now()-t,cacheHits:n}}finally{this.config=i}}getStats(){let e=this.cache.getStats(),t=this.generationTimes.length>0?this.generationTimes.reduce((n,r)=>n+r,0)/this.generationTimes.length:0;return{totalGenerated:this.totalGenerated,cacheHits:e.hits,cacheMisses:e.misses,avgGenerationTime:t,currentModel:this.config.model,vectorsStored:e.size}}clearCache(){this.cache.clear()}updateConfig(e){let t=e.model&&e.model!==this.config.model;this.config={...this.config,...e},e.cacheSize!==void 0&&e.cacheSize!==this.cache.getStats().size&&(this.cache=new _t(e.cacheSize)),t&&(this.isInitialized=!1)}getCacheKey(e){return`${this.config.model}:${this.config.hyperbolic}:${e}`}euclideanToPoincare(e){let t=Math.sqrt(e.reduce((a,s)=>a+s*s,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(a=>a*i)}isReady(){return this.isInitialized&&this.onnxRuntime!==null}};var ke=class{embeddings;searchCount=0;searchTimes=[];constructor(){this.embeddings=new Map}store(e){this.embeddings.set(e.id,e)}storeBatch(e){for(let t of e)this.store(t)}remove(e){return this.embeddings.delete(e)}clear(){this.embeddings.clear()}async search(e,t={}){let n=Date.now(),r={metric:t.metric??"cosine",topK:t.topK??5,threshold:t.threshold??.5,namespace:t.namespace};try{let i=Array.from(this.embeddings.values());r.namespace&&(i=i.filter(u=>u.namespace===r.namespace));let a=[];for(let u of i){if(u.embedding.dimensions!==e.dimensions)continue;let d=this.calculateSimilarity(e.vector,u.embedding.vector,r.metric);(r.metric==="cosine"?d>=r.threshold:d<=r.threshold)&&a.push({stored:u,score:d})}let s=r.metric==="cosine"?-1:1;a.sort((u,d)=>s*(u.score-d.score));let l=a.slice(0,r.topK).map(({stored:u,score:d})=>({text:u.text,embedding:u.embedding,score:d,metadata:u.metadata}));return this.searchCount++,this.searchTimes.push(Date.now()-n),this.searchTimes.length>100&&this.searchTimes.shift(),l}catch(i){throw new 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 s=0;s<e.length;s++)n+=e[s]*t[s],r+=e[s]*e[s],i+=t[s]*t[s];let a=Math.sqrt(r)*Math.sqrt(i);return a===0?0:n/a}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),a=e.reduce((p,g)=>p+g*g,0),s=t.reduce((p,g)=>p+g*g,0),c=0;for(let p=0;p<e.length;p++){let g=e[p]-t[p];c+=g*g}let l=2*c,u=(1-a)*(1-s);if(u<=0)return 1/0;let d=l/u;return Math.acosh(1+d)/i}async searchBatch(e,t={}){let n=[];for(let r of e){let i=await this.search(r,t);n.push(i)}return n}async findInRadius(e,t,n="cosine"){return this.search(e,{metric:n,threshold:t,topK:this.embeddings.size})}};var Me=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),a=Math.tanh(i*n/2)/(i*n),s=t.map(l=>l*a),c=this.norm(s);if(c>=1-this.config.epsilon)throw new L("HYPERBOLIC_ERROR",`Poincar\xE9 ball constraint violated: norm = ${c}`);return{vector:s,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),a=i*n;if(a>=1)throw new L("HYPERBOLIC_ERROR","Point is on or outside Poincar\xE9 ball boundary");let s=2/i*Math.atanh(a)/n;return{vector:t.map(l=>l*s),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),a=Math.sqrt(i),s=this.normSquared(n),c=this.normSquared(r),u=2*this.euclideanDistanceSquared(n,r),d=(1-s)*(1-c);if(d<=this.config.epsilon)return 1/0;let m=u/d;return Math.acosh(1+m)/a}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),a=this.normSquared(t),s=1+2*n*r+n*a,c=1-n*i,l=1+2*n*r+n*n*i*a;if(Math.abs(l)<this.config.epsilon)throw new L("HYPERBOLIC_ERROR","M\xF6bius addition denominator is zero");return e.map((d,m)=>(s*d+c*t[m])/l)}mobiusScalarMultiply(e,t){let n=Math.abs(this.config.curvature),r=Math.sqrt(n),i=this.norm(e);if(i<this.config.epsilon)return e;let a=r*i;if(Math.abs(a)>=1)throw new L("HYPERBOLIC_ERROR","M\xF6bius scalar multiplication out of bounds");let s=Math.tanh(t*Math.atanh(a))/(r*i);return e.map(c=>c*s)}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 a=r-t[i];return n+a*a},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}}};ae();var Xe=class{generator;search;hyperbolic;isInitialized=!1;constructor(e={}){this.generator=new Ae(e.embedding),this.search=new ke,this.hyperbolic=new Me(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=U();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(a=>a.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()}_${ao().slice(0,9)}`}isReady(){return this.isInitialized&&this.generator.isReady()}};function Lt(o){return new Xe(o)}var zn={enabled:!0,dbPath:".agentic-qe/memory.db",maxOutcomes:1e5,retentionDays:90,autoCleanup:!0,cleanupIntervalMs:3600*1e3};ae();k();Q();var ho={enabled:!0,haikuThreshold:.8,sonnetThreshold:.4,includeHealthSnapshot:!1,enableLogging:!0},jn=class{config;minCutService;constructor(e){this.config={...ho,...e},this.minCutService=Xr()}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 a=this.modelTierToLabel(i),s;if(this.config.includeHealthSnapshot){let u=e.taskGraph||this.minCutService.buildTaskGraphFromTopology(n);s=this.minCutService.getStructuralHealth(u)}let c=Date.now()-t,l={modelTier:i,tierLabel:a,lambda:r.lambda,normalizedLambda:r.normalizedLambda,confidence:r.confidence,rationale:r.rationale,usedMinCut:!0,healthSnapshot:s,decisionTimeMs:c};return this.config.enableLogging&&this.logDecision(l),l}catch(r){return this.createFallbackResult(e,t,`MinCut routing error: ${r instanceof Error?r.message:String(r)}`)}}getMinCutService(){return this.minCutService}isEnabled(){return this.config.enabled}routingTierToModelTier(e){switch(e){case 1:return 1;case 2:return 2;case 3:return 4;default:return 2}}modelTierToLabel(e){switch(e){case 0:return"Booster";case 1:return"Haiku";case 2:return"Sonnet";case 3:return"Sonnet-Extended";case 4:return"Opus";default:return"Sonnet"}}createFallbackResult(e,t,n){return{modelTier:(e.isCritical,2),tierLabel:"Sonnet",lambda:0,normalizedLambda:0,confidence:.3,rationale:`Fallback to Sonnet: ${n}`,usedMinCut:!1,decisionTimeMs:Date.now()-t}}logDecision(e){let t=e.usedMinCut?"MinCut":"Fallback";console.error(`[MinCutRouter] [${t}] Tier ${e.modelTier} (${e.tierLabel}) | Lambda: ${e.normalizedLambda.toFixed(3)} | Confidence: ${(e.confidence*100).toFixed(0)}% | Time: ${e.decisionTimeMs}ms`)}};function Oi(o){return new jn(o)}import{existsSync as fo}from"fs";import{join as yo}from"path";var Nt=class{id="memory";name="Pattern Memory";priority=80;maxTokens=2e3;async gather(e){let t=[];try{let n=yo(process.cwd(),".agentic-qe","memory.db");if(!fo(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-AEB3JMLD.js"),i=r(n,{readonly:!0});try{let a=this.extractDomainKeywords(e.taskDescription);if(a.length>0){let s=a.map(()=>"domain LIKE ?").join(" OR "),c=a.map(d=>`%${d}%`),u=i.prepare(`SELECT name, domain, description, confidence
345
+ `).get(e);return{merged:t,pruned:n,retained:a?.count??0}}async getEvolutionHistory(e,t=20){this.ensureInitialized();let i=(this.prepared.get("getVersionHistory")?.all(e,t)??[]).map(l=>({id:l.id,patternId:l.pattern_id,version:l.version,embedding:this.bufferToFloatArray(l.embedding,l.embedding_dimension),changes:A(l.changes||"[]"),qualityScore:l.quality_score,successRate:l.success_rate,timestamp:new Date(l.created_at),trigger:l.trigger})),c=(this.prepared.get("getEvents")?.all(e,t)??[]).map(l=>({id:l.id,patternId:l.pattern_id,eventType:l.event_type,details:A(l.details||"{}"),timestamp:new Date(l.created_at)}));return{versions:i,events:c}}async recordEvent(e,t,n){let r=this.prepared.get("insertEvent");if(r){let i={id:q(),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 jn(o={}){return new Nt(o)}k();var io={base:{},trajectoryTracker:{},experienceReplay:{},patternEvolution:{},enableTrajectories:!0,enableExperienceReplay:!0,enablePatternEvolution:!0,autoStoreExperiences:!0,autoConsolidate:!0,consolidationIntervalMs:3600*1e3},Bn=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={...io,...e}}async initialize(){if(this.initialized)return;let e=performance.now();this.reasoningBank=Fn(this.config.base),await this.reasoningBank.initialize(),this.config.enableTrajectories&&(this.trajectoryTracker=$n(this.config.trajectoryTracker),await this.trajectoryTracker.initialize()),this.config.enableExperienceReplay&&(this.experienceReplay=zn(this.config.experienceReplay),await this.experienceReplay.initialize()),this.config.enablePatternEvolution&&(this.patternEvolution=jn(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(a=>{console.warn(`[EnhancedAdapter] Failed to record experience application: ${a}`)})}}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 D(n)}catch(t){return $(j(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 pd(o={}){return new Bn(o)}import{randomUUID as yo}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 Ft=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}}},ke=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 Ft(this.config.cacheSize)}async initialize(){if(!this.isInitialized)try{let{computeRealEmbedding:e}=await import("./real-embeddings-AR7TZX7U.js");this.onnxRuntime={generateEmbedding:async(t,n)=>{let r=await e(t);if(this.config.normalize){let i=Math.sqrt(r.reduce((a,s)=>a+s*s,0));if(i>0)return r.map(a=>a/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),a=i,s=!1;this.config.hyperbolic&&(a=this.euclideanToPoincare(i),s=!0);let c={vector:a,dimensions:a.length,model:this.config.model,isHyperbolic:s};return this.cache.set(t,c),this.totalGenerated++,this.generationTimes.push(Date.now()-r),this.generationTimes.length>100&&this.generationTimes.shift(),c}catch(i){throw new 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 a of e.texts){let s=this.getCacheKey(a),c=this.cache.get(s);if(c)r.push(c),n++;else{let l=await this.generate(a);r.push(l)}}return{embeddings:r,duration:Date.now()-t,cacheHits:n}}finally{this.config=i}}getStats(){let e=this.cache.getStats(),t=this.generationTimes.length>0?this.generationTimes.reduce((n,r)=>n+r,0)/this.generationTimes.length:0;return{totalGenerated:this.totalGenerated,cacheHits:e.hits,cacheMisses:e.misses,avgGenerationTime:t,currentModel:this.config.model,vectorsStored:e.size}}clearCache(){this.cache.clear()}updateConfig(e){let t=e.model&&e.model!==this.config.model;this.config={...this.config,...e},e.cacheSize!==void 0&&e.cacheSize!==this.cache.getStats().size&&(this.cache=new Ft(e.cacheSize)),t&&(this.isInitialized=!1)}getCacheKey(e){return`${this.config.model}:${this.config.hyperbolic}:${e}`}euclideanToPoincare(e){let t=Math.sqrt(e.reduce((a,s)=>a+s*s,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(a=>a*i)}isReady(){return this.isInitialized&&this.onnxRuntime!==null}};var Me=class{embeddings;searchCount=0;searchTimes=[];constructor(){this.embeddings=new Map}store(e){this.embeddings.set(e.id,e)}storeBatch(e){for(let t of e)this.store(t)}remove(e){return this.embeddings.delete(e)}clear(){this.embeddings.clear()}async search(e,t={}){let n=Date.now(),r={metric:t.metric??"cosine",topK:t.topK??5,threshold:t.threshold??.5,namespace:t.namespace};try{let i=Array.from(this.embeddings.values());r.namespace&&(i=i.filter(u=>u.namespace===r.namespace));let a=[];for(let u of i){if(u.embedding.dimensions!==e.dimensions)continue;let d=this.calculateSimilarity(e.vector,u.embedding.vector,r.metric);(r.metric==="cosine"?d>=r.threshold:d<=r.threshold)&&a.push({stored:u,score:d})}let s=r.metric==="cosine"?-1:1;a.sort((u,d)=>s*(u.score-d.score));let l=a.slice(0,r.topK).map(({stored:u,score:d})=>({text:u.text,embedding:u.embedding,score:d,metadata:u.metadata}));return this.searchCount++,this.searchTimes.push(Date.now()-n),this.searchTimes.length>100&&this.searchTimes.shift(),l}catch(i){throw new 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 s=0;s<e.length;s++)n+=e[s]*t[s],r+=e[s]*e[s],i+=t[s]*t[s];let a=Math.sqrt(r)*Math.sqrt(i);return a===0?0:n/a}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),a=e.reduce((p,g)=>p+g*g,0),s=t.reduce((p,g)=>p+g*g,0),c=0;for(let p=0;p<e.length;p++){let g=e[p]-t[p];c+=g*g}let l=2*c,u=(1-a)*(1-s);if(u<=0)return 1/0;let d=l/u;return Math.acosh(1+d)/i}async searchBatch(e,t={}){let n=[];for(let r of e){let i=await this.search(r,t);n.push(i)}return n}async findInRadius(e,t,n="cosine"){return this.search(e,{metric:n,threshold:t,topK:this.embeddings.size})}};var Ie=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),a=Math.tanh(i*n/2)/(i*n),s=t.map(l=>l*a),c=this.norm(s);if(c>=1-this.config.epsilon)throw new F("HYPERBOLIC_ERROR",`Poincar\xE9 ball constraint violated: norm = ${c}`);return{vector:s,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),a=i*n;if(a>=1)throw new F("HYPERBOLIC_ERROR","Point is on or outside Poincar\xE9 ball boundary");let s=2/i*Math.atanh(a)/n;return{vector:t.map(l=>l*s),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),a=Math.sqrt(i),s=this.normSquared(n),c=this.normSquared(r),u=2*this.euclideanDistanceSquared(n,r),d=(1-s)*(1-c);if(d<=this.config.epsilon)return 1/0;let m=u/d;return Math.acosh(1+m)/a}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),a=this.normSquared(t),s=1+2*n*r+n*a,c=1-n*i,l=1+2*n*r+n*n*i*a;if(Math.abs(l)<this.config.epsilon)throw new F("HYPERBOLIC_ERROR","M\xF6bius addition denominator is zero");return e.map((d,m)=>(s*d+c*t[m])/l)}mobiusScalarMultiply(e,t){let n=Math.abs(this.config.curvature),r=Math.sqrt(n),i=this.norm(e);if(i<this.config.epsilon)return e;let a=r*i;if(Math.abs(a)>=1)throw new F("HYPERBOLIC_ERROR","M\xF6bius scalar multiplication out of bounds");let s=Math.tanh(t*Math.atanh(a))/(r*i);return e.map(c=>c*s)}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 a=r-t[i];return n+a*a},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}}};oe();var Ze=class{generator;search;hyperbolic;isInitialized=!1;constructor(e={}){this.generator=new ke(e.embedding),this.search=new Me,this.hyperbolic=new Ie(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=U();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(a=>a.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()}_${yo().slice(0,9)}`}isReady(){return this.isInitialized&&this.generator.isReady()}};function Gt(o){return new Ze(o)}var Un={enabled:!0,dbPath:".agentic-qe/memory.db",maxOutcomes:1e5,retentionDays:90,autoCleanup:!0,cleanupIntervalMs:3600*1e3};oe();k();Q();var Ro={enabled:!0,haikuThreshold:.8,sonnetThreshold:.4,includeHealthSnapshot:!1,enableLogging:!0},Hn=class{config;minCutService;constructor(e){this.config={...Ro,...e},this.minCutService=ai()}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 a=this.modelTierToLabel(i),s;if(this.config.includeHealthSnapshot){let u=e.taskGraph||this.minCutService.buildTaskGraphFromTopology(n);s=this.minCutService.getStructuralHealth(u)}let c=Date.now()-t,l={modelTier:i,tierLabel:a,lambda:r.lambda,normalizedLambda:r.normalizedLambda,confidence:r.confidence,rationale:r.rationale,usedMinCut:!0,healthSnapshot:s,decisionTimeMs:c};return this.config.enableLogging&&this.logDecision(l),l}catch(r){return this.createFallbackResult(e,t,`MinCut routing error: ${r instanceof Error?r.message:String(r)}`)}}getMinCutService(){return this.minCutService}isEnabled(){return this.config.enabled}routingTierToModelTier(e){switch(e){case 1:return 1;case 2:return 2;case 3:return 4;default:return 2}}modelTierToLabel(e){switch(e){case 0:return"Booster";case 1:return"Haiku";case 2:return"Sonnet";case 3:return"Sonnet-Extended";case 4:return"Opus";default:return"Sonnet"}}createFallbackResult(e,t,n){return{modelTier:(e.isCritical,2),tierLabel:"Sonnet",lambda:0,normalizedLambda:0,confidence:.3,rationale:`Fallback to Sonnet: ${n}`,usedMinCut:!1,decisionTimeMs:Date.now()-t}}logDecision(e){let t=e.usedMinCut?"MinCut":"Fallback";console.error(`[MinCutRouter] [${t}] Tier ${e.modelTier} (${e.tierLabel}) | Lambda: ${e.normalizedLambda.toFixed(3)} | Confidence: ${(e.confidence*100).toFixed(0)}% | Time: ${e.decisionTimeMs}ms`)}};function Ui(o){return new Hn(o)}import{existsSync as Po}from"fs";import{join as xo}from"path";var $t=class{id="memory";name="Pattern Memory";priority=80;maxTokens=2e3;async gather(e){let t=[];try{let n=xo(process.cwd(),".agentic-qe","memory.db");if(!Po(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-2VTKKBJU.js"),i=r(n,{readonly:!0});try{let a=this.extractDomainKeywords(e.taskDescription);if(a.length>0){let s=a.map(()=>"domain LIKE ?").join(" OR "),c=a.map(d=>`%${d}%`),u=i.prepare(`SELECT name, domain, description, confidence
346
346
  FROM qe_patterns
347
347
  WHERE ${s}
348
348
  ORDER BY confidence DESC
@@ -350,12 +350,12 @@ ${e.recommendations.length===0?"No recommendations - all quality gates passed.":
350
350
  `);t.push({sourceId:this.id,title:"Relevant Patterns from Learning Database",content:`Found ${u.length} relevant patterns:
351
351
 
352
352
  ${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(`
353
- `);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,a]of Object.entries(r))a.some(s=>n.includes(s))&&t.push(i);return t.length>0?t:["test-generation"]}};import{execSync as vo}from"child_process";var qt=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=vo(`git log --oneline -5 -- "${n}" 2>/dev/null || true`,{encoding:"utf-8",timeout:5e3}).trim();if(r){let i=`Recent commits for ${n}:
354
- ${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 bo,readFileSync as Co}from"fs";import{basename as Bn,dirname as To,join as Un}from"path";var Gt=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(bo(i))try{let s=Co(i,"utf-8").match(/(?:it|test|describe)\s*\(\s*['"`]([^'"`]+)['"`]/g)||[];if(s.length>0){let c=`Tests for ${Bn(n)} (${i}):
353
+ `);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,a]of Object.entries(r))a.some(s=>n.includes(s))&&t.push(i);return t.length>0?t:["test-generation"]}};import{execSync as Ao}from"child_process";var zt=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=Ao(`git log --oneline -5 -- "${n}" 2>/dev/null || true`,{encoding:"utf-8",timeout:5e3}).trim();if(r){let i=`Recent commits for ${n}:
354
+ ${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 ko,readFileSync as Mo}from"fs";import{basename as Vn,dirname as Io,join as Qn}from"path";var jt=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(ko(i))try{let s=Mo(i,"utf-8").match(/(?:it|test|describe)\s*\(\s*['"`]([^'"`]+)['"`]/g)||[];if(s.length>0){let c=`Tests for ${Vn(n)} (${i}):
355
355
  ${s.join(`
356
- `)}`;t.push({sourceId:this.id,title:`Tests: ${Bn(n)}`,content:c,estimatedTokens:Math.ceil(c.length/3.5),relevance:.8})}}catch{}}return t}findTestPaths(e){let t=Bn(e).replace(/\.(ts|js|tsx|jsx)$/,""),n=To(e),r=[".test.ts",".spec.ts",".test.js",".spec.js"],i=[];for(let a of r)i.push(Un(n,`${t}${a}`)),i.push(Un(n,"__tests__",`${t}${a}`)),i.push(Un(n,"..","tests",`${t}${a}`));return i}};import{existsSync as So,readFileSync as Eo}from"fs";import{join as Hn,basename as wo}from"path";var $t=class{id="coverage";name="Coverage Data";priority=50;maxTokens=1e3;async gather(e){let t=[],n=[Hn(process.cwd(),"coverage","coverage-summary.json"),Hn(process.cwd(),"coverage","coverage-final.json"),Hn(process.cwd(),".coverage","coverage-summary.json")];for(let r of n)if(So(r))try{let i=Eo(r,"utf-8"),a=JSON.parse(i),s=[];for(let c of e.targetFiles){let l=wo(c);for(let[u,d]of Object.entries(a))if(u.includes(l)&&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&&s.push(`${l}: lines=${p}%${g!==void 0?`, branches=${g}%`:""}${h!==void 0?`, functions=${h}%`:""}`)}}if(s.length>0){let c=`Coverage for target files:
356
+ `)}`;t.push({sourceId:this.id,title:`Tests: ${Vn(n)}`,content:c,estimatedTokens:Math.ceil(c.length/3.5),relevance:.8})}}catch{}}return t}findTestPaths(e){let t=Vn(e).replace(/\.(ts|js|tsx|jsx)$/,""),n=Io(e),r=[".test.ts",".spec.ts",".test.js",".spec.js"],i=[];for(let a of r)i.push(Qn(n,`${t}${a}`)),i.push(Qn(n,"__tests__",`${t}${a}`)),i.push(Qn(n,"..","tests",`${t}${a}`));return i}};import{existsSync as Do,readFileSync as _o}from"fs";import{join as Wn,basename as Oo}from"path";var Bt=class{id="coverage";name="Coverage Data";priority=50;maxTokens=1e3;async gather(e){let t=[],n=[Wn(process.cwd(),"coverage","coverage-summary.json"),Wn(process.cwd(),"coverage","coverage-final.json"),Wn(process.cwd(),".coverage","coverage-summary.json")];for(let r of n)if(Do(r))try{let i=_o(r,"utf-8"),a=JSON.parse(i),s=[];for(let c of e.targetFiles){let l=Oo(c);for(let[u,d]of Object.entries(a))if(u.includes(l)&&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&&s.push(`${l}: lines=${p}%${g!==void 0?`, branches=${g}%`:""}${h!==void 0?`, functions=${h}%`:""}`)}}if(s.length>0){let c=`Coverage for target files:
357
357
  ${s.join(`
358
- `)}`;t.push({sourceId:this.id,title:"File Coverage Data",content:c,estimatedTokens:Math.ceil(c.length/3.5),relevance:.6})}if(a.total&&typeof a.total=="object"){let c=a.total,l=`Project coverage: lines=${c.lines?.pct??"?"}%, branches=${c.branches?.pct??"?"}%, functions=${c.functions?.pct??"?"}%`;t.push({sourceId:this.id,title:"Project Coverage Summary",content:l,estimatedTokens:Math.ceil(l.length/3.5),relevance:.4})}break}catch{continue}return t}};import{existsSync as Ro}from"fs";import{join as Po}from"path";var zt=class{id="requirements";name="Requirements Traceability";priority=75;maxTokens=2e3;async gather(e){let t=[];try{let n=Po(process.cwd(),".agentic-qe","memory.db");if(!Ro(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-AEB3JMLD.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 s=e.targetFiles.map(l=>`%${l.split("/").pop()}%`);if(s.length>0){let l=s.map(()=>"description LIKE ?").join(" OR "),d=i.prepare(`SELECT name, domain, description, confidence
358
+ `)}`;t.push({sourceId:this.id,title:"File Coverage Data",content:c,estimatedTokens:Math.ceil(c.length/3.5),relevance:.6})}if(a.total&&typeof a.total=="object"){let c=a.total,l=`Project coverage: lines=${c.lines?.pct??"?"}%, branches=${c.branches?.pct??"?"}%, functions=${c.functions?.pct??"?"}%`;t.push({sourceId:this.id,title:"Project Coverage Summary",content:l,estimatedTokens:Math.ceil(l.length/3.5),relevance:.4})}break}catch{continue}return t}};import{existsSync as No}from"fs";import{join as Fo}from"path";var Ut=class{id="requirements";name="Requirements Traceability";priority=75;maxTokens=2e3;async gather(e){let t=[];try{let n=Fo(process.cwd(),".agentic-qe","memory.db");if(!No(n))return this.fallbackGather(e);let{openDatabase:r}=await import("./safe-db-2VTKKBJU.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 s=e.targetFiles.map(l=>`%${l.split("/").pop()}%`);if(s.length>0){let l=s.map(()=>"description LIKE ?").join(" OR "),d=i.prepare(`SELECT name, domain, description, confidence
359
359
  FROM qe_patterns
360
360
  WHERE domain LIKE '%requirement%'
361
361
  AND (${l})
@@ -371,7 +371,7 @@ ${m}`,estimatedTokens:Math.ceil(m.length/3.5),relevance:.75})}}let c=this.extrac
371
371
  LIMIT 5`).all(...u);if(m.length>0){let p=m.map(g=>`- **${g.name}**: ${g.description||"No description"}`).join(`
372
372
  `);t.push({sourceId:this.id,title:"Related Requirements",content:`Requirements related to task:
373
373
 
374
- ${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 a of i)n.includes(a)&&t.push(a);return t.slice(0,5)}};import{existsSync as xo}from"fs";import{join as Ao}from"path";var jt=class{id="defects";name="Defect Intelligence";priority=65;maxTokens=1500;async gather(e){let t=[];try{let n=Ao(process.cwd(),".agentic-qe","memory.db");if(!xo(n))return[];let{openDatabase:r}=await import("./safe-db-AEB3JMLD.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 s=e.targetFiles.map(l=>`%${l.split("/").pop()}%`);if(s.length>0){let l=s.map(()=>"description LIKE ?").join(" OR "),d=i.prepare(`SELECT name, domain, description, confidence
374
+ ${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 a of i)n.includes(a)&&t.push(a);return t.slice(0,5)}};import{existsSync as Lo}from"fs";import{join as qo}from"path";var Ht=class{id="defects";name="Defect Intelligence";priority=65;maxTokens=1500;async gather(e){let t=[];try{let n=qo(process.cwd(),".agentic-qe","memory.db");if(!Lo(n))return[];let{openDatabase:r}=await import("./safe-db-2VTKKBJU.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 s=e.targetFiles.map(l=>`%${l.split("/").pop()}%`);if(s.length>0){let l=s.map(()=>"description LIKE ?").join(" OR "),d=i.prepare(`SELECT name, domain, description, confidence
375
375
  FROM qe_patterns
376
376
  WHERE domain LIKE '%defect%'
377
377
  AND (${l})
@@ -387,19 +387,19 @@ ${m}`,estimatedTokens:Math.ceil(m.length/3.5),relevance:.7})}}let c=this.extract
387
387
  LIMIT 5`).all(...u);if(m.length>0){let p=m.map(g=>`- **${g.name}**: ${g.description||"No description"}`).join(`
388
388
  `);t.push({sourceId:this.id,title:"Regression Hotspots",content:`Known regression patterns:
389
389
 
390
- ${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 ko=8e3,Mo=300*1e3;function Do(){return[new Nt,new zt,new Gt,new jt,new qt,new $t]}var Bt=class{sources;maxTokenBudget;cache=new Map;cacheTtl;constructor(e){this.sources=e?.sources||Do(),this.maxTokenBudget=e?.maxTokenBudget||ko,this.cacheTtl=e?.cacheTtlMs||Mo}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,a=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:[]}}})),s=[],c=[];for(let p of a)if(p.status==="fulfilled"){let{sourceId:g,priority:h,fragments:y}=p.value;if(y.length>0){c.push(g);for(let v of y)s.push({...v,sourcePriority:h})}}s.sort((p,g)=>p.sourcePriority!==g.sourcePriority?g.sourcePriority-p.sourcePriority:g.relevance-p.relevance);let l=[],u=0;for(let p of s)if(u+p.estimatedTokens<=i){let{sourcePriority:g,...h}=p;l.push(h),u+=p.estimatedTokens}let m={summary:this.generateSummary(e,l,c),fragments:l,totalTokens:u,sources:c,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(o){let e=[];e.push("## Compiled Context"),e.push(""),e.push(o.summary),e.push("");for(let t of o.fragments)e.push(`### ${t.title}`),e.push(t.content),e.push("");return e.push(`_Context compiled: ${o.timestamp} (${o.duration}ms)_`),e.join(`
391
- `)}var Io={enabled:!0,enableAgentBooster:!0,enableLogging:!0,maxLogEntries:1e3},Vn=class o{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 Bt,this.minCutRouter=Oi({enableLogging:e.enableLogging})}static async getInstance(e){if(o.instance&&!o.instance.disposed)return o.instance;if(o.initializationPromise)return o.initializationPromise;o.initializationPromise=o.create(e);try{return o.instance=await o.initializationPromise,o.instance}finally{o.initializationPromise=null}}static async create(e){let t={...Io,...e},n;t.enableAgentBooster?n=await Et(t.modelRouterConfig):n=St(t.modelRouterConfig);let r=new o(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 a=Re[i.tier],s=this.mapTierToStrategy(i.tier),c={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(c),this.config.enableLogging&&this.logRoutingDecision(c);let l=e.patternHints,u=l&&l.length>0?this.formatPatternContext(l):void 0,d=e.agentType,m=d?On(d)||On(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:s,useAgentBooster:i.agentBoosterEligible,modelId:i.modelId,tierInfo:{tier:i.tier,name:a.name,typicalLatencyMs:a.typicalLatencyMs,relativeCost:a.relativeCost},logEntry:c,patternHints:l,patternContext:u,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(`
392
- `)}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,a=0;for(let c of e)t.set(c.selectedTier,(t.get(c.selectedTier)||0)+1),n+=c.complexity,r+=c.decisionTimeMs,c.wasDowngraded&&i++,c.agentBoosterEligible&&a++;let s={};for(let[c,l]of t)s[c]=l/e.length;return{totalRouted:e.length,avgComplexity:n/e.length,avgDecisionTimeMs:r/e.length,downgradeRate:i/e.length,agentBoosterRate:a/e.length,tierDistribution:s,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(),o.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 Ut(o){return Vn.getInstance(o)}An();Ct();var Qn=Se("CoherenceActionGate"),_o={structuralPermit:.4,structuralDeny:.2,shiftPermit:.5,shiftDeny:.25,evidencePermit:.5,evidenceDeny:.2,combinedPermit:.5,combinedDeny:.25},Wn={structural:.3,shift:.35,evidence:.35},Oo={low:1,medium:.9,high:.75,critical:.6},Li=1e3,Ht=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={..._o,...e?.thresholds}}evaluate(e){let t=this.computeStructuralScore(e),n=this.computeShiftScore(e),r=this.computeEvidenceScore(e),i=t*Wn.structural+n*Wn.shift+r*Wn.evidence,a=Oo[e.riskLevel]??1,s=i*a,c=this.computeDecision(t,n,r,s),l=this.buildReasoning(e,c,t,n,r,s),u={decision:c,structuralScore:t,shiftScore:n,evidenceScore:r,combinedScore:s,reasoning:l,advisory:this.advisoryMode};return this.recordEvaluation(u),Qn.debug("Action gate evaluation",{action:e.type,domain:e.domain,decision:c,combinedScore:s,advisory:this.advisoryMode}),u}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},Qn.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 a=e.context;(a.stale===!0||a.outdated===!0)&&(t-=.3),(a.distributionShift===!0||a.contextChanged===!0)&&(t-=.4),this.cusumSampleCount++;let s=e.confidence;return this.cusumHigh=Math.max(0,this.cusumHigh+(s-this.cusumMean)-this.cusumK),this.cusumLow=Math.max(0,this.cusumLow-(s-this.cusumMean)-this.cusumK),this.cusumHigh>this.cusumH||this.cusumLow>this.cusumH?(t-=.2,this.cusumAlertActive||(this.cusumAlertActive=!0,Qn.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 a of r)n[a]!==void 0&&n[a]!==null&&(t*=1+.15);let i=["errors","failures","warnings","regressions","conflictingResults","noTestCoverage"];for(let a of i)n[a]!==void 0&&n[a]!==null&&(t*=1-.18);if((e.riskLevel==="critical"||e.riskLevel==="high")&&!n.testResults&&!n.peerReview&&(t-=.15),typeof n.evidenceCount=="number"){let a=n.evidenceCount;t+=Math.min(a*.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,a){let s=[];if(s.push(`Decision: ${t} for ${e.type} (${e.domain}).`),s.push(`Scores: structural=${n.toFixed(2)}, shift=${r.toFixed(2)}, evidence=${i.toFixed(2)}, combined=${a.toFixed(2)}.`),t==="DENY")n<this.thresholds.structuralDeny&&s.push("Structural filter failed: action does not fit codebase graph."),r<this.thresholds.shiftDeny&&s.push("Shift filter failed: significant context distribution shift detected."),i<this.thresholds.evidenceDeny&&s.push("Evidence filter failed: insufficient evidence to justify action."),a<this.thresholds.combinedDeny&&s.push("Combined score below minimum threshold.");else if(t==="DEFER"){let c=[];n<this.thresholds.structuralPermit&&c.push("structural"),r<this.thresholds.shiftPermit&&c.push("shift"),i<this.thresholds.evidencePermit&&c.push("evidence"),c.length>0&&s.push(`Marginal filters: ${c.join(", ")}. Human review recommended.`)}return this.advisoryMode&&s.push("(Advisory mode: decision logged only, not enforced.)"),s.join(" ")}recordEvaluation(e){switch(this.evaluationHistory.push(e),this.evaluationHistory.length>Li&&(this.evaluationHistory=this.evaluationHistory.slice(-Li)),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 Ni(o){return new Ht(o)}function qi(o,e,t,n,r,i){if(!Ee().useCoherenceActionGate)return null;let s=i??new Ht,c={type:o,domain:e,confidence:t,context:r,riskLevel:n};return s.evaluate(c)}import*as Vt from"fs/promises";k();function Fo(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Lo(o,e,t,n){if(!t)return{testCode:o,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",a=n?"":`// TODO: replace './module-under-test' with the actual import path of the module under test
393
- `,s=r(t),c=Fo(s),l=new RegExp(c+"(?:\\.[a-zA-Z]+){0,2}","g");return{testCode:o&&a+o.replace(l,i),sourceFile:e===t&&n||e}}function Kn(o){o.registerHandler("generate-tests",async e=>{let t=e.payload;try{let n=await o.getTestGenerator(t.aiEnhancement!==!1),r=[],i;if(t.sourceFiles&&t.sourceFiles.length>0)r=t.sourceFiles;else if(t.filePath)r=[t.filePath];else if(t.sourceCode){let p={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-${q()}${p}`,await Vt.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 a=t.framework||"vitest",s=i?{[i]:t.filePath?t.filePath.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/i,""):"./module-under-test"}:void 0,c=await n.generateTests({sourceFiles:r,testType:t.testType||"unit",framework:a,coverageTarget:t.coverageGoal||80,patterns:[],importPathOverrides:s});if(i)try{await Vt.unlink(i)}catch{}if(!c.success)return c;let l=c.value,u=l.tests.map(m=>{let p=Lo(m.testCode,m.sourceFile,i,t.filePath);return{name:m.name,file:m.testFile,type:m.type,sourceFile:p.sourceFile,assertions:m.assertions,testCode:p.testCode}}),d=l.tests.some(m=>m.llmEnhanced===!0);return I({testsGenerated:u.length,coverageEstimate:l.coverageEstimate,tests:u,patternsUsed:l.patternsUsed,llmEnhanced:d,...d?{}:{generationMode:"deterministic-template",note:t.aiEnhancement===!1?"LLM enhancement was disabled by the caller (aiEnhancement: false).":"No LLM provider was available, so tests are deterministic template scaffolding rather than source-aware. Configure a provider in .agentic-qe/llm-config.json (or set a provider API key) and ensure AQE_LLM_ROUTER_DISABLED is not set."}})}catch(n){return $(j(n))}}),o.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,a=/^[a-zA-Z0-9_.\/\-@]+$/,s=n.filter(c=>a.test(c));if(s.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:c}=await import("child_process"),l=c("npx",["vitest","run",...s,"--reporter=json"],{cwd:r,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});i=l.stdout||"",!i.includes("{")&&l.status!==0&&(i=c("npx",["jest",...s,"--json"],{cwd:r,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).stdout||"")}catch(c){i=c.stdout||""}try{let c=i.indexOf("{");if(c>=0){let l=JSON.parse(i.slice(c));if(l.testResults){let u=l.numTotalTests||0,d=l.numPassedTests||0,m=l.numFailedTests||0;return I({total:u,passed:d,failed:m,skipped:u-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 $(j(n))}})}import*as Ji from"fs/promises";import*as Zi from"path";k();Q();Q();import*as De from"fs/promises";import*as Z from"path";async function Xn(o){let e=[Z.join(o,"coverage","coverage-final.json"),Z.join(o,"coverage","lcov.info"),Z.join(o,".nyc_output","coverage-final.json"),Z.join(o,"coverage-final.json"),Z.join(o,"coverage.xml"),Z.join(o,"htmlcov","status.json"),Z.join(o,"cobertura-coverage.xml")];for(let t of e)try{let n=await De.readFile(t,"utf-8");if(t.endsWith(".json"))return No(n);if(t.endsWith(".info"))return Yn(n);if(t.endsWith(".xml"))return qo(n)}catch{}return null}function No(o){let e=A(o),t=[],n=0,r=0,i=0,a=0,s=0,c=0,l=0,u=0;for(let[d,m]of Object.entries(e)){let p=m,g=p.statementMap||{},h=p.s||{},y=p.branchMap||{},v=p.b||{},f=p.f||{},C=Object.keys(h).length,b=Object.values(h).filter(B=>B>0).length,E=Object.values(v).flat().length,w=Object.values(v).flat().filter(B=>B>0).length,T=Object.keys(f).length,P=Object.values(f).filter(B=>B>0).length,O=Object.keys(g).length,V=Object.values(h).filter(B=>B>0).length,se=[];for(let[B,ee]of Object.entries(h))if(ee===0){let he=g[B];he?.start?.line&&se.push(he.start.line)}let Ce=[];for(let[B,ee]of Object.entries(v)){let he=y[B];ee.forEach((ft,Y)=>{ft===0&&he?.locations?.[Y]?.start?.line&&Ce.push(he.locations[Y].start.line)})}t.push({path:d,lines:{covered:b,total:C},branches:{covered:w,total:E},functions:{covered:P,total:T},statements:{covered:V,total:O},uncoveredLines:Array.from(new Set(se)).sort((B,ee)=>B-ee),uncoveredBranches:Array.from(new Set(Ce)).sort((B,ee)=>B-ee)}),n+=C,r+=b,i+=E,a+=w,s+=T,c+=P,l+=O,u+=V}return{files:t,summary:{line:n>0?r/n*100:0,branch:i>0?a/i*100:0,function:s>0?c/s*100:0,statement:l>0?u/l*100:0,files:t.length}}}function Yn(o){let e=[],t=o.split(`
394
- `),n=null,r=0,i=0,a=0,s=0,c=0,l=0,u=[],d=[];for(let f of t)if(f.startsWith("SF:"))n=f.slice(3);else if(f.startsWith("LF:"))r=parseInt(f.slice(3),10);else if(f.startsWith("LH:"))i=parseInt(f.slice(3),10);else if(f.startsWith("BRF:"))a=parseInt(f.slice(4),10);else if(f.startsWith("BRH:"))s=parseInt(f.slice(4),10);else if(f.startsWith("FNF:"))c=parseInt(f.slice(4),10);else if(f.startsWith("FNH:"))l=parseInt(f.slice(4),10);else if(f.startsWith("DA:")){let[C,b]=f.slice(3).split(",").map(E=>parseInt(E,10));b===0&&u.push(C)}else if(f.startsWith("BRDA:")){let C=f.slice(5).split(","),b=parseInt(C[0],10),E=C[3];(E==="0"||E==="-")&&d.push(b)}else f==="end_of_record"&&n&&(e.push({path:n,lines:{covered:i,total:r},branches:{covered:s,total:a},functions:{covered:l,total:c},statements:{covered:i,total:r},uncoveredLines:Array.from(new Set(u)),uncoveredBranches:Array.from(new Set(d))}),n=null,r=i=0,a=s=0,c=l=0,u.length=0,d.length=0);let m=0,p=0,g=0,h=0,y=0,v=0;for(let f of e)m+=f.lines.total,p+=f.lines.covered,g+=f.branches.total,h+=f.branches.covered,y+=f.functions.total,v+=f.functions.covered;return{files:e,summary:{line:m>0?p/m*100:0,branch:g>0?h/g*100:0,function:y>0?v/y*100:0,statement:m>0?p/m*100:0,files:e.length}}}function qo(o){let e=[];function t(g,h){let y=g.match(new RegExp(`${h}=["']([^"']*)["']`));return y?y[1]:null}let n=/<class\s[^>]*?>/g,r;for(;(r=n.exec(o))!==null;){let g=r[0],h=t(g,"filename");if(!h)continue;let y=parseFloat(t(g,"line-rate")||"NaN"),v=parseFloat(t(g,"branch-rate")||"NaN"),f=r.index,C=o.indexOf("</class>",f),b=C>f?o.slice(f,C):"",E=0,w=0,T=0,P=0,O=0,V=0,se=[],Ce=[],B=/<line\s([^>]*?)\/>/g,ee;for(;(ee=B.exec(b))!==null;){let Y=ee[1],He=parseInt(t(Y,"number")||"0",10),yt=parseInt(t(Y,"hits")||"0",10),Rn=t(Y,"branch")==="true",Ve=t(Y,"condition-coverage");E++,yt>0?w++:se.push(He),Rn&&(T++,(Ve?parseInt(Ve,10):yt>0?100:0)===100?P++:Ce.push(He))}let he=/<method\s([^>]*?)>/g,ft;for(;(ft=he.exec(b))!==null;){O++;let Y=ft.index,He=b.indexOf("</method>",Y);if(He>Y){let yt=b.slice(Y,He),Rn=/<line\s([^>]*?)\/>/g,Ve=!1,Pn;for(;(Pn=Rn.exec(yt))!==null;)if(parseInt(t(Pn[1],"hits")||"0",10)>0){Ve=!0;break}Ve&&V++}}E===0&&!isNaN(y)&&(E=100,w=Math.round(Math.max(0,Math.min(1,y))*100)),e.push({path:h,lines:{covered:w,total:E},branches:{covered:P,total:T},functions:{covered:V,total:O},statements:{covered:w,total:E},uncoveredLines:se,uncoveredBranches:Ce})}let i=0,a=0,s=0,c=0,l=0,u=0;for(let g of e)i+=g.lines.total,a+=g.lines.covered,s+=g.branches.total,c+=g.branches.covered,l+=g.functions.total,u+=g.functions.covered;let d=o.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?a/i*100:0:m,branch:isNaN(p)?s>0?c/s*100:0:p,function:l>0?u/l*100:0,statement:i>0?a/i*100:0,files:e.length}}}async function re(o,e={}){let t=[],{includeTests:n=!0,languages:r,maxFiles:i=5e3}=e,a=[".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){a=[];for(let c of r)c==="typescript"&&a.push(".ts",".tsx"),c==="javascript"&&a.push(".js",".jsx",".mjs",".cjs"),c==="python"&&a.push(".py",".pyw"),c==="go"&&a.push(".go"),c==="rust"&&a.push(".rs"),c==="java"&&a.push(".java"),c==="kotlin"&&a.push(".kt",".kts"),c==="ruby"&&a.push(".rb"),(c==="csharp"||c==="c#")&&a.push(".cs"),c==="php"&&a.push(".php"),c==="swift"&&a.push(".swift"),(c==="c"||c==="cpp"||c==="c++")&&a.push(".c",".h",".cpp",".hpp",".cc"),c==="scala"&&a.push(".scala")}async function s(c){try{let l=await De.readdir(c,{withFileTypes:!0});for(let u of l){let d=Z.join(c,u.name);if(u.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(u.name))continue;if(t.length>=i)return;await s(d)}else if(u.isFile()){let m=Z.extname(u.name);if(!a.includes(m)||!n&&(u.name.includes(".test.")||u.name.includes(".spec.")||u.name.endsWith("_test.ts")||u.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 De.stat(o)).isFile())return[o];await s(o)}catch{}return t}function Gi(o){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 o){let a=t[i.category];a&&e.add(a)}let n=o.some(i=>i.severity==="critical"),r=o.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&&o.length===0&&e.add("No vulnerabilities found - maintain current security practices"),Array.from(e)}import*as G from"fs";import*as ji from"os";import*as N from"path";function Qt(o=process.env){let e=(o.AQE_COVERAGE_NO_EXEC??"").trim().toLowerCase();return e?e!=="false"&&e!=="0"&&e!=="no"&&e!=="off":!1}var Go=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]),Bi=new Set(["node_modules","dist","build","coverage",".git",".claude",".agentic-qe","__pycache__",".venv","target","vendor"]),Ui=new Set(["tests","test","__tests__","benches","examples","spec"]),$o=[/\.test\./i,/\.spec\./i,/_test\./i,/_spec\./i,/^test_/i,/^test\./i,/^conftest\./i];function Wt(o,e){let t=o.split(N.sep).join("/"),n=N.basename(t);if($o.some(i=>i.test(n)))return!0;let r=t;if(e){let i=N.resolve(e).split(N.sep).join("/"),a=N.resolve(o).split(N.sep).join("/");(a===i||a.startsWith(`${i}/`))&&(r=a.slice(i.length).replace(/^\//,""))}return r.split("/").some(i=>Ui.has(i))}function zo(o){let e=o.split(""),t=o.length,n=0,r=(i,a)=>{for(let s=i;s<a&&s<t;s++)o[s]!==`
390
+ ${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 Go=8e3,$o=300*1e3;function zo(){return[new $t,new Ut,new jt,new Ht,new zt,new Bt]}var Vt=class{sources;maxTokenBudget;cache=new Map;cacheTtl;constructor(e){this.sources=e?.sources||zo(),this.maxTokenBudget=e?.maxTokenBudget||Go,this.cacheTtl=e?.cacheTtlMs||$o}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,a=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:[]}}})),s=[],c=[];for(let p of a)if(p.status==="fulfilled"){let{sourceId:g,priority:h,fragments:y}=p.value;if(y.length>0){c.push(g);for(let v of y)s.push({...v,sourcePriority:h})}}s.sort((p,g)=>p.sourcePriority!==g.sourcePriority?g.sourcePriority-p.sourcePriority:g.relevance-p.relevance);let l=[],u=0;for(let p of s)if(u+p.estimatedTokens<=i){let{sourcePriority:g,...h}=p;l.push(h),u+=p.estimatedTokens}let m={summary:this.generateSummary(e,l,c),fragments:l,totalTokens:u,sources:c,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 Hi(o){let e=[];e.push("## Compiled Context"),e.push(""),e.push(o.summary),e.push("");for(let t of o.fragments)e.push(`### ${t.title}`),e.push(t.content),e.push("");return e.push(`_Context compiled: ${o.timestamp} (${o.duration}ms)_`),e.join(`
391
+ `)}var jo={enabled:!0,enableAgentBooster:!0,enableLogging:!0,maxLogEntries:1e3},Kn=class o{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 Vt,this.minCutRouter=Ui({enableLogging:e.enableLogging})}static async getInstance(e){if(o.instance&&!o.instance.disposed)return o.instance;if(o.initializationPromise)return o.initializationPromise;o.initializationPromise=o.create(e);try{return o.instance=await o.initializationPromise,o.instance}finally{o.initializationPromise=null}}static async create(e){let t={...jo,...e},n;t.enableAgentBooster?n=await Pt(t.modelRouterConfig):n=Rt(t.modelRouterConfig);let r=new o(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 a=Pe[i.tier],s=this.mapTierToStrategy(i.tier),c={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(c),this.config.enableLogging&&this.logRoutingDecision(c);let l=e.patternHints,u=l&&l.length>0?this.formatPatternContext(l):void 0,d=e.agentType,m=d?Ln(d)||Ln(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=Hi(g)}catch{}return{decision:i,executionStrategy:s,useAgentBooster:i.agentBoosterEligible,modelId:i.modelId,tierInfo:{tier:i.tier,name:a.name,typicalLatencyMs:a.typicalLatencyMs,relativeCost:a.relativeCost},logEntry:c,patternHints:l,patternContext:u,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(`
392
+ `)}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,a=0;for(let c of e)t.set(c.selectedTier,(t.get(c.selectedTier)||0)+1),n+=c.complexity,r+=c.decisionTimeMs,c.wasDowngraded&&i++,c.agentBoosterEligible&&a++;let s={};for(let[c,l]of t)s[c]=l/e.length;return{totalRouted:e.length,avgComplexity:n/e.length,avgDecisionTimeMs:r/e.length,downgradeRate:i/e.length,agentBoosterRate:a/e.length,tierDistribution:s,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(),o.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=Pe[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=Pe[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 Qt(o){return Kn.getInstance(o)}In();Et();var Xn=Ee("CoherenceActionGate"),Bo={structuralPermit:.4,structuralDeny:.2,shiftPermit:.5,shiftDeny:.25,evidencePermit:.5,evidenceDeny:.2,combinedPermit:.5,combinedDeny:.25},Yn={structural:.3,shift:.35,evidence:.35},Uo={low:1,medium:.9,high:.75,critical:.6},Vi=1e3,Wt=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={...Bo,...e?.thresholds}}evaluate(e){let t=this.computeStructuralScore(e),n=this.computeShiftScore(e),r=this.computeEvidenceScore(e),i=t*Yn.structural+n*Yn.shift+r*Yn.evidence,a=Uo[e.riskLevel]??1,s=i*a,c=this.computeDecision(t,n,r,s),l=this.buildReasoning(e,c,t,n,r,s),u={decision:c,structuralScore:t,shiftScore:n,evidenceScore:r,combinedScore:s,reasoning:l,advisory:this.advisoryMode};return this.recordEvaluation(u),Xn.debug("Action gate evaluation",{action:e.type,domain:e.domain,decision:c,combinedScore:s,advisory:this.advisoryMode}),u}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},Xn.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 a=e.context;(a.stale===!0||a.outdated===!0)&&(t-=.3),(a.distributionShift===!0||a.contextChanged===!0)&&(t-=.4),this.cusumSampleCount++;let s=e.confidence;return this.cusumHigh=Math.max(0,this.cusumHigh+(s-this.cusumMean)-this.cusumK),this.cusumLow=Math.max(0,this.cusumLow-(s-this.cusumMean)-this.cusumK),this.cusumHigh>this.cusumH||this.cusumLow>this.cusumH?(t-=.2,this.cusumAlertActive||(this.cusumAlertActive=!0,Xn.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 a of r)n[a]!==void 0&&n[a]!==null&&(t*=1+.15);let i=["errors","failures","warnings","regressions","conflictingResults","noTestCoverage"];for(let a of i)n[a]!==void 0&&n[a]!==null&&(t*=1-.18);if((e.riskLevel==="critical"||e.riskLevel==="high")&&!n.testResults&&!n.peerReview&&(t-=.15),typeof n.evidenceCount=="number"){let a=n.evidenceCount;t+=Math.min(a*.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,a){let s=[];if(s.push(`Decision: ${t} for ${e.type} (${e.domain}).`),s.push(`Scores: structural=${n.toFixed(2)}, shift=${r.toFixed(2)}, evidence=${i.toFixed(2)}, combined=${a.toFixed(2)}.`),t==="DENY")n<this.thresholds.structuralDeny&&s.push("Structural filter failed: action does not fit codebase graph."),r<this.thresholds.shiftDeny&&s.push("Shift filter failed: significant context distribution shift detected."),i<this.thresholds.evidenceDeny&&s.push("Evidence filter failed: insufficient evidence to justify action."),a<this.thresholds.combinedDeny&&s.push("Combined score below minimum threshold.");else if(t==="DEFER"){let c=[];n<this.thresholds.structuralPermit&&c.push("structural"),r<this.thresholds.shiftPermit&&c.push("shift"),i<this.thresholds.evidencePermit&&c.push("evidence"),c.length>0&&s.push(`Marginal filters: ${c.join(", ")}. Human review recommended.`)}return this.advisoryMode&&s.push("(Advisory mode: decision logged only, not enforced.)"),s.join(" ")}recordEvaluation(e){switch(this.evaluationHistory.push(e),this.evaluationHistory.length>Vi&&(this.evaluationHistory=this.evaluationHistory.slice(-Vi)),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 Qi(o){return new Wt(o)}function Wi(o,e,t,n,r,i){if(!we().useCoherenceActionGate)return null;let s=i??new Wt,c={type:o,domain:e,confidence:t,context:r,riskLevel:n};return s.evaluate(c)}import*as Kt from"fs/promises";k();function Ho(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Vo(o,e,t,n){if(!t)return{testCode:o,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",a=n?"":`// TODO: replace './module-under-test' with the actual import path of the module under test
393
+ `,s=r(t),c=Ho(s),l=new RegExp(c+"(?:\\.[a-zA-Z]+){0,2}","g");return{testCode:o&&a+o.replace(l,i),sourceFile:e===t&&n||e}}function Jn(o){o.registerHandler("generate-tests",async e=>{let t=e.payload;try{let n=await o.getTestGenerator(t.aiEnhancement!==!1),r=[],i;if(t.sourceFiles&&t.sourceFiles.length>0)r=t.sourceFiles;else if(t.filePath)r=[t.filePath];else if(t.sourceCode){let p={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-${q()}${p}`,await Kt.writeFile(i,t.sourceCode,"utf-8"),r=[i]}if(r.length===0)return D({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 a=t.framework||"vitest",s=i?{[i]:t.filePath?t.filePath.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/i,""):"./module-under-test"}:void 0,c=await n.generateTests({sourceFiles:r,testType:t.testType||"unit",framework:a,coverageTarget:t.coverageGoal||80,patterns:[],importPathOverrides:s});if(i)try{await Kt.unlink(i)}catch{}if(!c.success)return c;let l=c.value,u=l.tests.map(m=>{let p=Vo(m.testCode,m.sourceFile,i,t.filePath);return{name:m.name,file:m.testFile,type:m.type,sourceFile:p.sourceFile,assertions:m.assertions,testCode:p.testCode}}),d=l.tests.some(m=>m.llmEnhanced===!0);return D({testsGenerated:u.length,coverageEstimate:l.coverageEstimate,tests:u,patternsUsed:l.patternsUsed,llmEnhanced:d,...d?{}:{generationMode:"deterministic-template",note:t.aiEnhancement===!1?"LLM enhancement was disabled by the caller (aiEnhancement: false).":"No LLM provider was available, so tests are deterministic template scaffolding rather than source-aware. Configure a provider in .agentic-qe/llm-config.json (or set a provider API key) and ensure AQE_LLM_ROUTER_DISABLED is not set."}})}catch(n){return $(j(n))}}),o.registerHandler("execute-tests",async e=>{let t=e.payload;try{let n=t.testFiles||[];if(n.length===0)return D({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,a=/^[a-zA-Z0-9_.\/\-@]+$/,s=n.filter(c=>a.test(c));if(s.length!==n.length)return D({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:c}=await import("child_process"),l=c("npx",["vitest","run",...s,"--reporter=json"],{cwd:r,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});i=l.stdout||"",!i.includes("{")&&l.status!==0&&(i=c("npx",["jest",...s,"--json"],{cwd:r,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).stdout||"")}catch(c){i=c.stdout||""}try{let c=i.indexOf("{");if(c>=0){let l=JSON.parse(i.slice(c));if(l.testResults){let u=l.numTotalTests||0,d=l.numPassedTests||0,m=l.numFailedTests||0;return D({total:u,passed:d,failed:m,skipped:u-d-m,duration:0,coverage:0,failedTests:[]})}}}catch{}return D({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 $(j(n))}})}import*as os from"fs/promises";import*as cs from"path";k();Q();Q();import*as De from"fs/promises";import*as ee from"path";async function Zn(o){let e=[ee.join(o,"coverage","coverage-final.json"),ee.join(o,"coverage","lcov.info"),ee.join(o,".nyc_output","coverage-final.json"),ee.join(o,"coverage-final.json"),ee.join(o,"coverage.xml"),ee.join(o,"htmlcov","status.json"),ee.join(o,"cobertura-coverage.xml")];for(let t of e)try{let n=await De.readFile(t,"utf-8");if(t.endsWith(".json"))return Qo(n);if(t.endsWith(".info"))return er(n);if(t.endsWith(".xml"))return Wo(n)}catch{}return null}function Qo(o){let e=A(o),t=[],n=0,r=0,i=0,a=0,s=0,c=0,l=0,u=0;for(let[d,m]of Object.entries(e)){let p=m,g=p.statementMap||{},h=p.s||{},y=p.branchMap||{},v=p.b||{},f=p.f||{},C=Object.keys(h).length,b=Object.values(h).filter(B=>B>0).length,E=Object.values(v).flat().length,w=Object.values(v).flat().filter(B=>B>0).length,T=Object.keys(f).length,P=Object.values(f).filter(B=>B>0).length,O=Object.keys(g).length,V=Object.values(h).filter(B=>B>0).length,ae=[];for(let[B,te]of Object.entries(h))if(te===0){let fe=g[B];fe?.start?.line&&ae.push(fe.start.line)}let Te=[];for(let[B,te]of Object.entries(v)){let fe=y[B];te.forEach((bt,J)=>{bt===0&&fe?.locations?.[J]?.start?.line&&Te.push(fe.locations[J].start.line)})}t.push({path:d,lines:{covered:b,total:C},branches:{covered:w,total:E},functions:{covered:P,total:T},statements:{covered:V,total:O},uncoveredLines:Array.from(new Set(ae)).sort((B,te)=>B-te),uncoveredBranches:Array.from(new Set(Te)).sort((B,te)=>B-te)}),n+=C,r+=b,i+=E,a+=w,s+=T,c+=P,l+=O,u+=V}return{files:t,summary:{line:n>0?r/n*100:0,branch:i>0?a/i*100:0,function:s>0?c/s*100:0,statement:l>0?u/l*100:0,files:t.length}}}function er(o){let e=[],t=o.split(`
394
+ `),n=null,r=0,i=0,a=0,s=0,c=0,l=0,u=[],d=[];for(let f of t)if(f.startsWith("SF:"))n=f.slice(3);else if(f.startsWith("LF:"))r=parseInt(f.slice(3),10);else if(f.startsWith("LH:"))i=parseInt(f.slice(3),10);else if(f.startsWith("BRF:"))a=parseInt(f.slice(4),10);else if(f.startsWith("BRH:"))s=parseInt(f.slice(4),10);else if(f.startsWith("FNF:"))c=parseInt(f.slice(4),10);else if(f.startsWith("FNH:"))l=parseInt(f.slice(4),10);else if(f.startsWith("DA:")){let[C,b]=f.slice(3).split(",").map(E=>parseInt(E,10));b===0&&u.push(C)}else if(f.startsWith("BRDA:")){let C=f.slice(5).split(","),b=parseInt(C[0],10),E=C[3];(E==="0"||E==="-")&&d.push(b)}else f==="end_of_record"&&n&&(e.push({path:n,lines:{covered:i,total:r},branches:{covered:s,total:a},functions:{covered:l,total:c},statements:{covered:i,total:r},uncoveredLines:Array.from(new Set(u)),uncoveredBranches:Array.from(new Set(d))}),n=null,r=i=0,a=s=0,c=l=0,u.length=0,d.length=0);let m=0,p=0,g=0,h=0,y=0,v=0;for(let f of e)m+=f.lines.total,p+=f.lines.covered,g+=f.branches.total,h+=f.branches.covered,y+=f.functions.total,v+=f.functions.covered;return{files:e,summary:{line:m>0?p/m*100:0,branch:g>0?h/g*100:0,function:y>0?v/y*100:0,statement:m>0?p/m*100:0,files:e.length}}}function Wo(o){let e=[];function t(g,h){let y=g.match(new RegExp(`${h}=["']([^"']*)["']`));return y?y[1]:null}let n=/<class\s[^>]*?>/g,r;for(;(r=n.exec(o))!==null;){let g=r[0],h=t(g,"filename");if(!h)continue;let y=parseFloat(t(g,"line-rate")||"NaN"),v=parseFloat(t(g,"branch-rate")||"NaN"),f=r.index,C=o.indexOf("</class>",f),b=C>f?o.slice(f,C):"",E=0,w=0,T=0,P=0,O=0,V=0,ae=[],Te=[],B=/<line\s([^>]*?)\/>/g,te;for(;(te=B.exec(b))!==null;){let J=te[1],We=parseInt(t(J,"number")||"0",10),Ct=parseInt(t(J,"hits")||"0",10),An=t(J,"branch")==="true",Ke=t(J,"condition-coverage");E++,Ct>0?w++:ae.push(We),An&&(T++,(Ke?parseInt(Ke,10):Ct>0?100:0)===100?P++:Te.push(We))}let fe=/<method\s([^>]*?)>/g,bt;for(;(bt=fe.exec(b))!==null;){O++;let J=bt.index,We=b.indexOf("</method>",J);if(We>J){let Ct=b.slice(J,We),An=/<line\s([^>]*?)\/>/g,Ke=!1,kn;for(;(kn=An.exec(Ct))!==null;)if(parseInt(t(kn[1],"hits")||"0",10)>0){Ke=!0;break}Ke&&V++}}E===0&&!isNaN(y)&&(E=100,w=Math.round(Math.max(0,Math.min(1,y))*100)),e.push({path:h,lines:{covered:w,total:E},branches:{covered:P,total:T},functions:{covered:V,total:O},statements:{covered:w,total:E},uncoveredLines:ae,uncoveredBranches:Te})}let i=0,a=0,s=0,c=0,l=0,u=0;for(let g of e)i+=g.lines.total,a+=g.lines.covered,s+=g.branches.total,c+=g.branches.covered,l+=g.functions.total,u+=g.functions.covered;let d=o.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?a/i*100:0:m,branch:isNaN(p)?s>0?c/s*100:0:p,function:l>0?u/l*100:0,statement:i>0?a/i*100:0,files:e.length}}}async function ie(o,e={}){let t=[],{includeTests:n=!0,languages:r,maxFiles:i=5e3}=e,a=[".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){a=[];for(let c of r)c==="typescript"&&a.push(".ts",".tsx"),c==="javascript"&&a.push(".js",".jsx",".mjs",".cjs"),c==="python"&&a.push(".py",".pyw"),c==="go"&&a.push(".go"),c==="rust"&&a.push(".rs"),c==="java"&&a.push(".java"),c==="kotlin"&&a.push(".kt",".kts"),c==="ruby"&&a.push(".rb"),(c==="csharp"||c==="c#")&&a.push(".cs"),c==="php"&&a.push(".php"),c==="swift"&&a.push(".swift"),(c==="c"||c==="cpp"||c==="c++")&&a.push(".c",".h",".cpp",".hpp",".cc"),c==="scala"&&a.push(".scala")}async function s(c){try{let l=await De.readdir(c,{withFileTypes:!0});for(let u of l){let d=ee.join(c,u.name);if(u.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(u.name))continue;if(t.length>=i)return;await s(d)}else if(u.isFile()){let m=ee.extname(u.name);if(!a.includes(m)||!n&&(u.name.includes(".test.")||u.name.includes(".spec.")||u.name.endsWith("_test.ts")||u.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 De.stat(o)).isFile())return[o];await s(o)}catch{}return t}function Ki(o){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 o){let a=t[i.category];a&&e.add(a)}let n=o.some(i=>i.severity==="critical"),r=o.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&&o.length===0&&e.add("No vulnerabilities found - maintain current security practices"),Array.from(e)}import*as G from"fs";import*as Ji from"os";import*as L from"path";function Xt(o=process.env){let e=(o.AQE_COVERAGE_NO_EXEC??"").trim().toLowerCase();return e?e!=="false"&&e!=="0"&&e!=="no"&&e!=="off":!1}var Ko=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]),Zi=new Set(["node_modules","dist","build","coverage",".git",".claude",".agentic-qe","__pycache__",".venv","target","vendor"]),es=new Set(["tests","test","__tests__","benches","examples","spec"]),Xo=[/\.test\./i,/\.spec\./i,/_test\./i,/_spec\./i,/^test_/i,/^test\./i,/^conftest\./i];function Yt(o,e){let t=o.split(L.sep).join("/"),n=L.basename(t);if(Xo.some(i=>i.test(n)))return!0;let r=t;if(e){let i=L.resolve(e).split(L.sep).join("/"),a=L.resolve(o).split(L.sep).join("/");(a===i||a.startsWith(`${i}/`))&&(r=a.slice(i.length).replace(/^\//,""))}return r.split("/").some(i=>es.has(i))}function Yo(o){let e=o.split(""),t=o.length,n=0,r=(i,a)=>{for(let s=i;s<a&&s<t;s++)o[s]!==`
395
395
  `&&(e[s]=" ")};for(;n<t;){let i=o[n];if(i==="/"&&o[n+1]==="/"){let s=o.indexOf(`
396
- `,n),c=s===-1?t:s;r(n,c),n=c;continue}if(i==="/"&&o[n+1]==="*"){let s=0,c=n;for(;n<t;){if(o[n]==="/"&&o[n+1]==="*"){s++,n+=2;continue}if(o[n]==="*"&&o[n+1]==="/"){if(s--,n+=2,s===0)break;continue}n++}r(c,n);continue}let a=/^b?r(#*)"/.exec(o.slice(n,n+300));if(a){let s=`"${a[1]}`,c=n+a[0].length,l=o.indexOf(s,c),u=l===-1?t:l+s.length;r(n,u),n=u;continue}if(i==='"'){let s=n;for(n++;n<t;){if(o[n]==="\\"){n+=2;continue}if(o[n]==='"'){n++;break}n++}r(s,n);continue}if(i==="'"){let s=-1;if(o[n+1]==="\\"){let c=o.indexOf("'",n+2);c!==-1&&c<=n+5&&(s=c+1)}else o[n+2]==="'"&&(s=n+3);if(s!==-1){r(n,s),n=s;continue}}n++}return e.join("")}function jo(o,e){if(e!==".rs")return[];let t=zo(o).split(`
397
- `),n=[];for(let r=0;r<t.length;r++){if(!/#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]/.test(t[r]))continue;let i=-1;for(let c=r;c<Math.min(t.length,r+10);c++){let l=t[c],u=l.indexOf("{"),d=l.indexOf(";");if(d!==-1&&(u===-1||d<u))break;if(u!==-1){let m=t.slice(r,c+1).join(" ");/\bmod\s+\w+/.test(m)&&(i=c);break}}if(i===-1)continue;let a=0,s=-1;for(let c=i;c<t.length;c++){for(let l of t[c])l==="{"?a++:l==="}"&&a--;if(a<=0){s=c;break}}n.push([r+1,(s===-1?t.length-1:s)+1]),r=s===-1?t.length:s}return n}function Bo(o){if(o.length===0)return 0;let e=o.split(`
398
- `);return e[e.length-1]===""&&e.pop(),e.length}function Hi(o,e=6){let t=N.resolve(o);try{if(!G.existsSync(t))return null;G.statSync(t).isDirectory()||(t=N.dirname(t))}catch{return null}for(let n=0;n<=e;n++){if(G.existsSync(N.join(t,"Cargo.toml")))return G.realpathSync(t);let r=N.dirname(t);if(r===t)break;t=r}return null}function Vi(o,e=0){if(e>4)return!1;let t;try{t=G.readdirSync(o,{withFileTypes:!0})}catch{return!1}for(let n of t)if(n.isFile()&&N.extname(n.name)===".rs")return!0;for(let n of t)if(n.isDirectory()&&!Bi.has(n.name)&&Vi(N.join(o,n.name),e+1))return!0;return!1}function Jn(o){let e=Hi(o);if(e===null)return!1;let t=N.resolve(o);return t===e||Vi(t)}async function Qi(o,e={}){if(Qt())return null;let{execSync:t}=await import("child_process"),n=e.timeoutMs??3e5,r=Hi(o);if(!r)return null;try{t("cargo llvm-cov --version",{cwd:r,timeout:3e4,stdio:["pipe","pipe","pipe"]})}catch{return null}let i=N.join(G.mkdtempSync(N.join(ji.tmpdir(),"aqe-rust-cov-")),"lcov.info");try{if(t(`cargo llvm-cov --lcov --output-path ${JSON.stringify(i)}`,{cwd:r,timeout:n,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!G.existsSync(i))return null;let s=Yn(G.readFileSync(i,"utf-8")).files.filter(u=>!Wt(u.path,r));if(s.length===0)return null;let c=Wi(s),l=s.some(u=>u.branches.total>0);return{data:c,provenance:{method:"cargo-llvm-cov",estimated:!1,branchDataCollected:l,functionDataCollected:s.some(u=>u.functions.total>0),notes:l?[]:["cargo-llvm-cov reported no branch data (Rust branch coverage requires a nightly toolchain with -Z coverage-options=branch). Branch coverage is reported as null rather than assumed."]}}}catch{return null}finally{try{G.rmSync(N.dirname(i),{recursive:!0,force:!0})}catch{}}}var $i={".rs":{fn:/\bfn\s+\w+/g,branch:/\b(if|match|while|for)\b|\?\?|\|\||&&/g},".go":{fn:/\bfunc\s+\w*/g,branch:/\b(if|switch|case|for|select)\b|\|\||&&/g},".py":{fn:/\b(def|lambda)\b/g,branch:/\b(if|elif|for|while|except)\b|\band\b|\bor\b/g},".java":{fn:/\b(public|private|protected|static)[\w<>,\s[\]]+\w+\s*\(/g,branch:/\b(if|switch|case|for|while|catch)\b|\|\||&&/g},".rb":{fn:/\bdef\s+\w+/g,branch:/\b(if|elsif|unless|case|when|while)\b|\|\||&&/g},default:{fn:/\bfunction\b|=>|\b\w+\s*\([^)]*\)\s*\{/g,branch:/\b(if|switch|case|for|while|catch)\b|\?\?|\|\||&&/g}};function Uo(o){return $i[o]??$i.default}function zi(o,e){return(o.match(new RegExp(e.source,e.flags))||[]).length}function Wi(o){let e=i=>o.reduce((a,s)=>a+i(s),0),t=(i,a)=>a>0?Math.round(i/a*100):0,n=e(i=>i.lines.total),r=e(i=>i.lines.covered);return{files:o,summary:{line:t(r,n),branch:t(e(i=>i.branches.covered),e(i=>i.branches.total)),function:t(e(i=>i.functions.covered),e(i=>i.functions.total)),statement:t(r,n),files:o.length}}}function Ho(o){let e=[],t=o;function n(r,i){if(i>6)return;let a;try{a=G.readdirSync(r,{withFileTypes:!0})}catch{return}for(let s of a){let c=N.join(r,s.name);if(s.isDirectory()){if(Bi.has(s.name)||Ui.has(s.name))continue;n(c,i+1)}else if(s.isFile()){if(!Go.has(N.extname(s.name))||Wt(c,t))continue;e.push(c)}}}return n(o,0),e}function Ki(o){if(!G.existsSync(o)||!G.statSync(o).isDirectory())return null;let e=Ho(o);if(e.length===0)return null;let t=e.map(n=>{let r="";try{r=G.readFileSync(n,"utf-8")}catch{}let i=N.extname(n),a=Bo(r),s=jo(r,i),c=T=>s.some(([P,O])=>T>=P&&T<=O),l=s.reduce((T,[P,O])=>T+(O-P+1),0),u=Math.max(a-l,0),d=Uo(i),m=zi(r,d.fn),p=s.length>0,g=Vo(n),h=p||g,y=zi(r,d.branch),v=Math.min(y*.005,.15),f=Math.min(u*1e-4,.1),C=Math.max(.05,Math.min(.95,h?.85-v-f:.2)),b=Math.floor(u*C),E=[];for(let T=1;T<=a;T++)c(T)||E.push(T);let w=E.slice(b);return{path:n,lines:{covered:b,total:u},branches:{covered:0,total:0},functions:{covered:0,total:m},statements:{covered:b,total:u},uncoveredLines:w,uncoveredBranches:[]}});return{data:Wi(t),provenance:{method:"static-estimation",estimated:!0,branchDataCollected:!1,functionDataCollected:!1,notes:["No instrumentation ran. These numbers are a STATIC ESTIMATE derived from source shape (file size, declaration counts, presence of a test file) \u2014 they are not measured coverage and must not be reported as such.","Branch and function coverage were not collected and are reported as null."]}}}function Vo(o){let e=N.extname(o),t=o.slice(0,-e.length);return[`${t}.test${e}`,`${t}.spec${e}`,`${t}_test${e}`,`${t}.test${e}`.replace("/src/","/tests/"),`${t}.spec${e}`.replace("/src/","/tests/"),`${t}${e}`.replace("/src/","/tests/")].some(r=>{try{return G.existsSync(r)}catch{return!1}})}async function Qo(o){if(Qt())return!1;try{let{execSync:e}=await import("child_process"),t="npx vitest run --coverage --reporter=json 2>/dev/null";try{let n=await Ji.readFile(Zi.join(o,"package.json"),"utf-8"),r=A(n),i={...r.devDependencies||{},...r.dependencies||{}};i.jest||i["@jest/core"]?t="npx jest --coverage --json 2>/dev/null":(i.mocha||i.nyc)&&(t="npx nyc mocha 2>/dev/null")}catch{}return e(t,{cwd:o,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function Xi(o,e){let t=o.files.filter(l=>!Wt(l.path,e));if(t.length===0)return null;let n=l=>t.reduce((u,d)=>u+l(d),0),r=(l,u)=>u>0?Math.round(l/u*100):0,i=n(l=>l.lines.total),a=n(l=>l.lines.covered),s=t.some(l=>l.branches.total>0),c=t.some(l=>l.functions.total>0);return{data:{files:t,summary:{line:r(a,i),branch:r(n(l=>l.branches.covered),n(l=>l.branches.total)),function:r(n(l=>l.functions.covered),n(l=>l.functions.total)),statement:r(a,i),files:t.length}},provenance:{method:"instrumented-report",estimated:!1,branchDataCollected:s,functionDataCollected:c,notes:[]}}}async function Wo(o){let e=await Xn(o);if(e){let r=Xi(e,o);return r?{collected:r,ranTests:!1}:{collected:null,ranTests:!1,testOnlyReport:!0}}if(Jn(o)){let r=await Qi(o);if(r)return{collected:r,ranTests:!0}}let t=await Qo(o),n=await Xn(o);if(n){let r=Xi(n,o);return r?{collected:r,ranTests:t}:{collected:null,ranTests:t,testOnlyReport:!0}}return{collected:Ki(o),ranTests:t}}function Yi(o){return Qt()?"Coverage tooling execution is disabled (AQE_COVERAGE_NO_EXEC). No tests were run and no build tooling was invoked. Unset it, or generate a coverage report yourself and re-run, to get real measurements.":Jn(o)?"To get real measurements for this Rust crate, install cargo-llvm-cov (`cargo install cargo-llvm-cov`) and re-run; agentic-qe will invoke it automatically.":"To get real measurements, run your tests with coverage enabled (e.g. `npm test -- --coverage`, `pytest --cov`) and re-run this analysis."}function Zn(o){o.registerHandler("analyze-coverage",async e=>{let t=e.payload;try{let n=o.getCoverageAnalyzer(),r=t.target||process.cwd(),i=t.threshold||80,{collected:a,ranTests:s,testOnlyReport:c}=await Wo(r);if(!a)return I({lineCoverage:null,branchCoverage:null,functionCoverage:null,statementCoverage:null,totalFiles:0,coverageByFile:[],gaps:[],estimated:!1,measured:!1,coverageMethod:"none",algorithm:"sublinear-O(log n)",warning:c?"The coverage report contains only test files, so there is no production coverage to report. Coverage OF a test file is not a meaningful metric. Check that your coverage tool is instrumenting your source directory.":s?"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. "+Yi(r)});let{data:l,provenance:u}=a,d=await n.analyze({coverageData:l,threshold:i,includeFileDetails:t.detectGaps});if(!d.success)return d;let m=d.value,p=[];if(t.detectGaps){let f=await n.findGaps(l,i);f.success&&(p=f.value.gaps.map(C=>({file:C.file,lines:C.lines,risk:C.severity,estimated:u.estimated,...u.estimated?{confidence:.2,reason:"Possible coverage gap (STATIC ESTIMATE \u2014 no instrumentation ran)"}:{}})))}let g=f=>Math.round(f*10)/10,h=(f,C)=>C>0?Math.round(f/C*1e3)/10:null,y=[...u.notes];u.estimated&&y.push(Yi(r));let v=m.recommendations.filter(f=>!(!u.branchDataCollected&&/branch coverage/i.test(f)||!u.functionDataCollected&&/function coverage/i.test(f)));return I({lineCoverage:g(m.summary.line),branchCoverage:u.branchDataCollected?g(m.summary.branch):null,functionCoverage:u.functionDataCollected?g(m.summary.function):null,statementCoverage:g(m.summary.statement),totalFiles:m.summary.files,coverageByFile:l.files.map(f=>({file:f.path,lineCoverage:h(f.lines.covered,f.lines.total)??0,branchCoverage:u.branchDataCollected?h(f.branches.covered,f.branches.total):null,functionCoverage:u.functionDataCollected?h(f.functions.covered,f.functions.total):null})),gaps:p,meetsThreshold:m.meetsThreshold,delta:m.delta,recommendations:v,algorithm:"sublinear-O(log n)",estimated:u.estimated,measured:!u.estimated,coverageMethod:u.method,branchDataCollected:u.branchDataCollected,functionDataCollected:u.functionDataCollected,...y.length>0?{warning:y.join(" ")}:{}})}catch(n){return $(j(n))}})}import*as er from"fs/promises";import*as es from"path";k();function tr(o){o.registerHandler("scan-security",async e=>{let t=e.payload;try{let n=o.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 a=i.filter(f=>/\.(ts|tsx|js|jsx|mjs|cjs)$/.test(f)),s=i.filter(f=>!/\.(ts|tsx|js|jsx|mjs|cjs)$/.test(f)),c=[];for(let f of i)try{let C=await er.readFile(f,"utf-8"),b=C.split(`
399
- `),E=f.startsWith(r)?f.slice(r.length).replace(/^\//,""):f,w=[{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 w)for(let V=0;V<b.length;V++){let se=[...b[V].matchAll(O.regex)];for(let Ce of se)c.push({title:O.title,severity:O.severity,location:{file:E,line:V+1},description:`Potential hardcoded secret found at line ${V+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])&&c.push({title:"Potential SQL injection",severity:"high",location:{file:E,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)){c.push({title:"CORS wildcard origin",severity:"high",location:{file:E,line:b.findIndex(V=>O.test(V))+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)&&c.push({title:"Debug mode enabled",severity:"medium",location:{file:E,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)&&c.push({title:"Dangerous eval/exec usage",severity:"high",location:{file:E,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 l=["requirements.txt","pyproject.toml","Gemfile","go.mod","Cargo.toml"];for(let f of l){let C=es.join(r,f);try{let b=await er.readFile(C,"utf-8");if(c.push({title:"Dependency audit recommended",severity:"informational",location:{file:f,line:1},description:`Found ${f} \u2014 run language-specific dependency audit (e.g., pip-audit, npm audit, cargo audit)`,category:"dependencies"}),f==="requirements.txt"||f==="pyproject.toml"){let E=[{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 w of E)w.pattern.test(b)&&c.push({title:w.title,severity:w.severity,location:{file:f,line:b.split(`
400
- `).findIndex(T=>w.pattern.test(T))+1},description:w.description,category:"dependencies"})}}catch{}}let u=a.map(f=>Yr.create(f)),d=null;if(t.sast!==!1&&u.length>0){let f=await n.scanFiles(u);f.success&&(d=f.value)}let m=null;if(t.dast&&t.targetUrl){let f=await n.scanUrl(t.targetUrl,{activeScanning:!0,maxDepth:3,timeout:3e4});f.success&&(m=f.value)}let p={critical:c.filter(f=>f.severity==="critical").length,high:c.filter(f=>f.severity==="high").length,medium:c.filter(f=>f.severity==="medium").length,low:c.filter(f=>f.severity==="low").length,informational:c.filter(f=>f.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||[],...c],y=h.sort((f,C)=>{let b={critical:0,high:1,medium:2,low:3,informational:4};return b[f.severity]-b[C.severity]}).slice(0,10).map(f=>({type:f.title,severity:f.severity,file:f.location.file,line:f.location.line,description:f.description})),v=Gi(h);return I({vulnerabilities:h.length,critical:g.critical,high:g.high,medium:g.medium,low:g.low,informational:g.informational,topVulnerabilities:y,recommendations:v,scanTypes:{sast:t.sast!==!1,dast:t.dast||!1},filesScanned:i.length,jstsFilesScanned:a.length,otherFilesScanned:s.length,coverage:d?.coverage,deepAnalysisPerformed:a.length>0,analysisDepth:a.length>0?s.length>0?"full-sast-on-js-ts; pattern-matching-on-other-languages":"full-sast":"pattern-matching-only",...a.length===0?{note:s.length>0?'NO LANGUAGE-SPECIFIC ANALYSIS RAN. Only cross-language pattern matching (secrets, CORS, eval/exec) was applied to these files \u2014 full SAST is implemented for JS/TS only. A zero-finding result here means "nothing matched a generic pattern", NOT "no vulnerabilities". Run a language-specific tool (cargo audit / clippy, bandit, gosec, semgrep) for real coverage of this codebase.':"No source files were analyzed."}:{}})}catch(n){return $(j(n))}})}k();function nr(o){o.registerHandler("assess-quality",async e=>{let t=e.payload;try{let n=o.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 u=await import("path"),d=await import("fs"),m=u.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 a=await n.analyzeQuality({sourceFiles:i,includeMetrics:t.metrics||["coverage","complexity","maintainability","testability"]});if(!a.success)return a;let s=a.value,c=s.score.overall>=r,l={};for(let u of s.metrics)l[u.name]=u.value;return I({qualityScore:s.score.overall,passed:c,threshold:r,metrics:{coverage:s.score.coverage,complexity:s.score.complexity,maintainability:s.score.maintainability,security:s.score.security,...l},recommendations:s.recommendations.map(u=>`[${u.type}] ${u.title}: ${u.description}`),trends:s.trends.map(u=>({metric:u.metric,direction:u.direction,dataPoints:u.dataPoints.length})),filesAnalyzed:i.length})}catch(n){return $(j(n))}})}import*as ts from"fs/promises";k();function rr(o){o.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"],a=[];for(let s of r)i.some(c=>s.endsWith(c))&&a.push(s);return I({requirementsAnalyzed:a.length,testable:0,ambiguous:0,untestable:0,coverage:0,bddScenarios:[],warning:a.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:a.map(s=>s.startsWith(n)?s.slice(n.length+1):s).slice(0,20)})}catch(n){return $(j(n))}}),o.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 ts.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(`
401
- `).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: ${S(n)}`})}}catch(n){return $(j(n))}})}import*as ns from"fs/promises";import*as rs from"path";k();function ir(o){o.registerHandler("index-code",async e=>{let t=e.payload;try{let n=o.getKnowledgeGraph(),r=t.target||process.cwd(),i=Date.now(),a=await re(r,{includeTests:t.includeTests!==!1,languages:t.languages});if(a.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 s=await n.index({paths:a,incremental:t.incremental||!1,includeTests:t.includeTests!==!1,languages:t.languages});if(!s.success)return s;let c=s.value,l=new Set,u={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 a){let m=rs.extname(d).slice(1),p=u[m];p&&l.add(p)}return I({filesIndexed:c.filesIndexed,nodesCreated:c.nodesCreated,edgesCreated:c.edgesCreated,symbolsExtracted:c.nodesCreated,relationsFound:c.edgesCreated,target:r,incremental:t.incremental||!1,languages:Array.from(l),duration:c.duration,errors:c.errors,warnings:c.warnings})}catch(n){return $(j(n))}}),o.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 a=[];for(let u of i)try{let d=await ns.readFile(u,"utf-8"),m=d.split(`
402
- `),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 y=d.match(/\b(if|else|switch|case|for|while|catch|&&|\|\|)\b/g)||[],v=y.length/Math.max(p,1);v>.15?(g+=.25,h.push(`High branch density (${y.length} branches in ${p} lines)`)):v>.08&&(g+=.1,h.push("Moderate branch complexity")),Math.max(...m.map(E=>{let w=E.match(/^(\s*)/);return w?w[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 E=u.startsWith(n)?u.slice(n.length).replace(/^\//,""):u;a.push({file:E,probability:Math.round(g*100)/100,reason:h.join("; ")})}}catch{}a.sort((u,d)=>d.probability-u.probability);let s=a.length>0?a.reduce((u,d)=>u+d.probability,0)/a.length:0,c=Math.round(s*100),l=[];if(a.length>0){l.push(`${a.length} files flagged for potential defects out of ${i.length} analyzed`);let u=a[0];l.push(`Highest risk: ${u.file} (${Math.round(u.probability*100)}%) \u2014 ${u.reason}`)}return a.some(u=>u.reason.includes("Large file"))&&l.push("Consider splitting large files to reduce complexity"),a.some(u=>u.reason.includes("technical debt"))&&l.push("Address TODO/FIXME comments to reduce technical debt"),a.length===0&&l.push("No files exceeded the defect probability threshold \u2014 code looks healthy"),I({predictedDefects:a.slice(0,20),riskScore:c,recommendations:l,filesAnalyzed:i.length})}catch(n){return $(j(n))}})}function sr(o){o.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>")})}),o.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)."})}),o.registerHandler("optimize-learning",async e=>{try{let t=await import("./unified-memory-hnsw-PQRPTYOD.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 ie=Se("TaskExecutor");function Zo(o){return xe.resolve(Pe.CoverageAnalyzerService)(o)}function ec(o){return xe.resolve(Pe.SecurityScannerService)(o)}function us(o,e){return xe.resolve(Pe.createTestGeneratorService)(o,e)}function tc(o){return xe.resolve(Pe.KnowledgeGraphService)(o)}function nc(o){return xe.resolve(Pe.QualityAnalyzerService)(o)}function ds(o){switch(o){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 rc(o){if(["generate-tests","analyze-coverage","scan-security","execute-tests","assess-quality","validate-contracts","test-accessibility","chaos-test","predict-defects","validate-requirements","index-code"].includes(o.type))return null;let t=o.payload?.codeContext||"",n=o.payload?.sourceCode||"",r=t||n;return r?r.includes("var ")&&!r.includes("const ")&&!r.includes("let ")?"var-to-const":r.includes("console.log")||r.includes("console.warn")||r.includes("console.error")?"remove-console":r.includes(".then(")&&r.includes(".catch(")?"promise-to-async":r.includes("require(")&&!r.includes("import ")?"cjs-to-esm":r.includes("function ")&&!r.includes("=>")?"func-to-arrow":null:null}var or=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=Di(this._config.resultsDir),this.registerHandlers()}kernel;eventBus;_config;resultSaver;coverageAnalyzer=null;securityScanner=null;testGenerator=null;deterministicTestGenerator=null;knowledgeGraph=null;qualityAnalyzer=null;agentBooster=null;taskRouter=null;qualityFeedbackLoop=null;coherenceActionGate=null;taskHandlers=new Map;get config(){return this._config}registerHandler(e,t){this.taskHandlers.set(e,t)}setQualityFeedbackLoop(e){this.qualityFeedbackLoop=e}getCoverageAnalyzer(){return this.coverageAnalyzer||(this.coverageAnalyzer=Zo(this.kernel.memory)),this.coverageAnalyzer}getSecurityScanner(){return this.securityScanner||(this.securityScanner=ec(this.kernel.memory)),this.securityScanner}async getTestGenerator(e=!0){return e?(this.testGenerator||(this.testGenerator=us(this.kernel.memory,await this.resolveLLMRouter())),this.testGenerator):(this.deterministicTestGenerator||(this.deterministicTestGenerator=us(this.kernel.memory)),this.deterministicTestGenerator)}async resolveLLMRouter(){if(this.kernel.llmRouter)return this.kernel.llmRouter;try{let{getSharedLLMRouter:e}=await import("./base-F6GMOKU2.js");return await e()??void 0}catch(e){ie.debug("LLM router unavailable; using deterministic generation",{error:S(e)});return}}getKnowledgeGraph(){return this.knowledgeGraph||(this.knowledgeGraph=tc(this.kernel.memory)),this.knowledgeGraph}getQualityAnalyzer(){return this.qualityAnalyzer||(this.qualityAnalyzer=nc(this.kernel.memory)),this.qualityAnalyzer}registerHandlers(){Kn(this),Zn(this),tr(this),nr(this),rr(this),ir(this),sr(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 Ut()}catch{return null}return this.taskRouter}async executeWithAgentBooster(e,t,n){let r=rc(e);if(!r)return console.debug(`[TaskExecutor] No applicable Agent Booster transform for task ${e.id}`),null;try{let i=await this.getAgentBooster(),a=e.payload?.codeContext||e.payload?.sourceCode||"",s=await i.transform(a,r);return s.success&&s.confidence>=.7?(console.debug(`[TaskExecutor] Agent Booster transform succeeded: ${r}, confidence=${s.confidence}`),{taskId:e.id,success:!0,data:{transformed:!0,transformType:r,originalCode:s.originalCode,transformedCode:s.transformedCode,confidence:s.confidence,implementationUsed:s.implementationUsed,durationMs:s.durationMs,changeCount:s.changeCount,tier:0,model:"agent-booster"},duration:Date.now()-t,domain:n}):(console.debug(`[TaskExecutor] Agent Booster low confidence (${s.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=${ds(t)}, success=${n}, duration=${r}ms`),this.qualityFeedbackLoop){let a=e.targetDomains||[],s=n?1:0,c=r<100?1:r<500?.8:r<2e3?.6:r<5e3?.4:r<1e4?.2:.1,l=.25*s+.325+.1*c;await this.qualityFeedbackLoop.recordRoutingOutcome({taskId:e.id,taskDescription:e.type,recommendedAgent:String(t),usedAgent:String(t),followedRecommendation:!0,success:n,qualityScore:l,durationMs:r,timestamp:new Date,error:n?void 0:"Task execution failed"})}}catch(i){console.warn("[TaskExecutor] Failed to record outcome:",i)}}async execute(e){let t=Date.now(),n=this.getTaskDomain(e.type),r=e.payload,i=r?.routingTier??2,a=r?.useAgentBooster??!1,s=r?.compiledContext??void 0,c=ds(i);s&&e.payload&&(e.payload.__compiledContext=s),console.debug(`[TaskExecutor] Executing task ${e.id}: type=${e.type}, tier=${i}, model=${c}, useAgentBooster=${a}${s?", hasContext=true":""}`);let l=this.evaluateCoherenceGate(e,n);l&&console.debug(`[TaskExecutor] Coherence gate: task=${e.id}, decision=${l.decision}, combined=${l.combinedScore.toFixed(3)}, advisory=${l.advisory}`),this.validateWithReasoningQEC(e,n);try{if(i===0||a){let p=await this.executeWithAgentBooster(e,t,n);if(p)return this.recordOutcome(e,0,!0,Date.now()-t).catch(g=>{ie.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),await this.publishTaskCompleted(e.id,p.data,n),p;console.debug(`[TaskExecutor] Agent Booster fallback to Tier 1 for task ${e.id}`)}let u=this.taskHandlers.get(e.type);if(!u){let p={taskId:e.id,success:!1,error:`No handler registered for task type: ${e.type}`,duration:Date.now()-t,domain:n};return this.recordOutcome(e,i,!1,Date.now()-t).catch(g=>{ie.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),p}let d=await Promise.race([u(e),this.timeout(e.timeout||this._config.timeout)]);if(!d.success){let p="error"in d?d.error.message:"Unknown error";return await this.publishTaskFailed(e.id,p,n),this.recordOutcome(e,i,!1,Date.now()-t).catch(g=>{ie.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=>{ie.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:c,usedAgentBooster:!1}},duration:Date.now()-t,domain:n,savedFiles:m}}catch(u){let d=S(u);return await this.publishTaskFailed(e.id,d,n),this.recordOutcome(e,i,!1,Date.now()-t).catch(m=>{ie.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=Ni({advisory:!0}));let n=e.payload,r=typeof n?.confidence=="number"?n.confidence:.7,i=n?.riskLevel??"medium";return qi(e.type,t,r,i,n??{},this.coherenceActionGate)}catch(n){return ie.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:a}=(Ct(),qr(Ca));if(a()){let{createReasoningQEC:s}=(ls(),qr(cs));this._reasoningQEC=s()}}catch(a){ie.debug("ReasoningQEC module unavailable",{error:a instanceof Error?a.message:String(a)})}}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||ie.warn("ReasoningQEC validation found issues (advisory)",{taskId:e.id,domain:t,confidence:i.confidence,issues:i.issues.length})}catch(n){ie.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:q(),type:"TaskCompleted",timestamp:new Date,source:n,payload:{taskId:e,result:t}})}async publishTaskFailed(e,t,n){await this.eventBus.publish({id:q(),type:"TaskFailed",timestamp:new Date,source:n,payload:{taskId:e,error:t}})}};function ms(o,e){return new or(o,o.eventBus,e)}async function ps(){}import{randomUUID as Ie}from"crypto";k();var cr={effectiveness:.25,coverage:.2,mutationKill:.15,stability:.15,maintainability:.15,performance:.1},lr={"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}},pe={qualityWeights:cr,promotionCriteria:lr,autoPromote:!0,autoDemote:!0,minCoverageImprovementToLearn:5,maxOutcomesInMemory:1e4,persistOutcomes:!0,batchSize:100};ae();k();Q();var ur=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}},dr=class o{store;reasoningBank=null;config;db=null;persistCount=0;static RETENTION_CLEANUP_INTERVAL=100;patternMetrics=new Map;constructor(e={}){this.config={...pe,...e},this.store=new ur(this.config.maxOutcomesInMemory)}connectReasoningBank(e){this.reasoningBank=e}async initialize(){try{this.db=U(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb()}catch(e){console.warn("[TestOutcomeTracker] DB initialization failed, using memory-only:",S(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
396
+ `,n),c=s===-1?t:s;r(n,c),n=c;continue}if(i==="/"&&o[n+1]==="*"){let s=0,c=n;for(;n<t;){if(o[n]==="/"&&o[n+1]==="*"){s++,n+=2;continue}if(o[n]==="*"&&o[n+1]==="/"){if(s--,n+=2,s===0)break;continue}n++}r(c,n);continue}let a=/^b?r(#*)"/.exec(o.slice(n,n+300));if(a){let s=`"${a[1]}`,c=n+a[0].length,l=o.indexOf(s,c),u=l===-1?t:l+s.length;r(n,u),n=u;continue}if(i==='"'){let s=n;for(n++;n<t;){if(o[n]==="\\"){n+=2;continue}if(o[n]==='"'){n++;break}n++}r(s,n);continue}if(i==="'"){let s=-1;if(o[n+1]==="\\"){let c=o.indexOf("'",n+2);c!==-1&&c<=n+5&&(s=c+1)}else o[n+2]==="'"&&(s=n+3);if(s!==-1){r(n,s),n=s;continue}}n++}return e.join("")}function Jo(o,e){if(e!==".rs")return[];let t=Yo(o).split(`
397
+ `),n=[];for(let r=0;r<t.length;r++){if(!/#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]/.test(t[r]))continue;let i=-1;for(let c=r;c<Math.min(t.length,r+10);c++){let l=t[c],u=l.indexOf("{"),d=l.indexOf(";");if(d!==-1&&(u===-1||d<u))break;if(u!==-1){let m=t.slice(r,c+1).join(" ");/\bmod\s+\w+/.test(m)&&(i=c);break}}if(i===-1)continue;let a=0,s=-1;for(let c=i;c<t.length;c++){for(let l of t[c])l==="{"?a++:l==="}"&&a--;if(a<=0){s=c;break}}n.push([r+1,(s===-1?t.length-1:s)+1]),r=s===-1?t.length:s}return n}function Zo(o){if(o.length===0)return 0;let e=o.split(`
398
+ `);return e[e.length-1]===""&&e.pop(),e.length}function ts(o,e=6){let t=L.resolve(o);try{if(!G.existsSync(t))return null;G.statSync(t).isDirectory()||(t=L.dirname(t))}catch{return null}for(let n=0;n<=e;n++){if(G.existsSync(L.join(t,"Cargo.toml")))return G.realpathSync(t);let r=L.dirname(t);if(r===t)break;t=r}return null}function ns(o,e=0){if(e>4)return!1;let t;try{t=G.readdirSync(o,{withFileTypes:!0})}catch{return!1}for(let n of t)if(n.isFile()&&L.extname(n.name)===".rs")return!0;for(let n of t)if(n.isDirectory()&&!Zi.has(n.name)&&ns(L.join(o,n.name),e+1))return!0;return!1}function tr(o){let e=ts(o);if(e===null)return!1;let t=L.resolve(o);return t===e||ns(t)}async function rs(o,e={}){if(Xt())return null;let{execSync:t}=await import("child_process"),n=e.timeoutMs??3e5,r=ts(o);if(!r)return null;try{t("cargo llvm-cov --version",{cwd:r,timeout:3e4,stdio:["pipe","pipe","pipe"]})}catch{return null}let i=L.join(G.mkdtempSync(L.join(Ji.tmpdir(),"aqe-rust-cov-")),"lcov.info");try{if(t(`cargo llvm-cov --lcov --output-path ${JSON.stringify(i)}`,{cwd:r,timeout:n,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!G.existsSync(i))return null;let s=er(G.readFileSync(i,"utf-8")).files.filter(u=>!Yt(u.path,r));if(s.length===0)return null;let c=is(s),l=s.some(u=>u.branches.total>0);return{data:c,provenance:{method:"cargo-llvm-cov",estimated:!1,branchDataCollected:l,functionDataCollected:s.some(u=>u.functions.total>0),notes:l?[]:["cargo-llvm-cov reported no branch data (Rust branch coverage requires a nightly toolchain with -Z coverage-options=branch). Branch coverage is reported as null rather than assumed."]}}}catch{return null}finally{try{G.rmSync(L.dirname(i),{recursive:!0,force:!0})}catch{}}}var Xi={".rs":{fn:/\bfn\s+\w+/g,branch:/\b(if|match|while|for)\b|\?\?|\|\||&&/g},".go":{fn:/\bfunc\s+\w*/g,branch:/\b(if|switch|case|for|select)\b|\|\||&&/g},".py":{fn:/\b(def|lambda)\b/g,branch:/\b(if|elif|for|while|except)\b|\band\b|\bor\b/g},".java":{fn:/\b(public|private|protected|static)[\w<>,\s[\]]+\w+\s*\(/g,branch:/\b(if|switch|case|for|while|catch)\b|\|\||&&/g},".rb":{fn:/\bdef\s+\w+/g,branch:/\b(if|elsif|unless|case|when|while)\b|\|\||&&/g},default:{fn:/\bfunction\b|=>|\b\w+\s*\([^)]*\)\s*\{/g,branch:/\b(if|switch|case|for|while|catch)\b|\?\?|\|\||&&/g}};function ec(o){return Xi[o]??Xi.default}function Yi(o,e){return(o.match(new RegExp(e.source,e.flags))||[]).length}function is(o){let e=i=>o.reduce((a,s)=>a+i(s),0),t=(i,a)=>a>0?Math.round(i/a*100):0,n=e(i=>i.lines.total),r=e(i=>i.lines.covered);return{files:o,summary:{line:t(r,n),branch:t(e(i=>i.branches.covered),e(i=>i.branches.total)),function:t(e(i=>i.functions.covered),e(i=>i.functions.total)),statement:t(r,n),files:o.length}}}function tc(o){let e=[],t=o;function n(r,i){if(i>6)return;let a;try{a=G.readdirSync(r,{withFileTypes:!0})}catch{return}for(let s of a){let c=L.join(r,s.name);if(s.isDirectory()){if(Zi.has(s.name)||es.has(s.name))continue;n(c,i+1)}else if(s.isFile()){if(!Ko.has(L.extname(s.name))||Yt(c,t))continue;e.push(c)}}}return n(o,0),e}function nr(o){if(!G.existsSync(o)||!G.statSync(o).isDirectory())return null;let e=tc(o);if(e.length===0)return null;let t=e.map(n=>{let r="";try{r=G.readFileSync(n,"utf-8")}catch{}let i=L.extname(n),a=Zo(r),s=Jo(r,i),c=T=>s.some(([P,O])=>T>=P&&T<=O),l=s.reduce((T,[P,O])=>T+(O-P+1),0),u=Math.max(a-l,0),d=ec(i),m=Yi(r,d.fn),p=s.length>0,g=nc(n),h=p||g,y=Yi(r,d.branch),v=Math.min(y*.005,.15),f=Math.min(u*1e-4,.1),C=Math.max(.05,Math.min(.95,h?.85-v-f:.2)),b=Math.floor(u*C),E=[];for(let T=1;T<=a;T++)c(T)||E.push(T);let w=E.slice(b);return{path:n,lines:{covered:b,total:u},branches:{covered:0,total:0},functions:{covered:0,total:m},statements:{covered:b,total:u},uncoveredLines:w,uncoveredBranches:[]}});return{data:is(t),provenance:{method:"static-estimation",estimated:!0,branchDataCollected:!1,functionDataCollected:!1,notes:["No instrumentation ran. These numbers are a STATIC ESTIMATE derived from source shape (file size, declaration counts, presence of a test file) \u2014 they are not measured coverage and must not be reported as such.","Branch and function coverage were not collected and are reported as null."]}}}function nc(o){let e=L.extname(o),t=o.slice(0,-e.length);return[`${t}.test${e}`,`${t}.spec${e}`,`${t}_test${e}`,`${t}.test${e}`.replace("/src/","/tests/"),`${t}.spec${e}`.replace("/src/","/tests/"),`${t}${e}`.replace("/src/","/tests/")].some(r=>{try{return G.existsSync(r)}catch{return!1}})}async function rc(o){if(Xt())return!1;try{let{execSync:e}=await import("child_process"),t="npx vitest run --coverage --reporter=json 2>/dev/null";try{let n=await os.readFile(cs.join(o,"package.json"),"utf-8"),r=A(n),i={...r.devDependencies||{},...r.dependencies||{}};i.jest||i["@jest/core"]?t="npx jest --coverage --json 2>/dev/null":(i.mocha||i.nyc)&&(t="npx nyc mocha 2>/dev/null")}catch{}return e(t,{cwd:o,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}function ss(o,e){let t=o.files.filter(l=>!Yt(l.path,e));if(t.length===0)return null;let n=l=>t.reduce((u,d)=>u+l(d),0),r=(l,u)=>u>0?Math.round(l/u*100):0,i=n(l=>l.lines.total),a=n(l=>l.lines.covered),s=t.some(l=>l.branches.total>0),c=t.some(l=>l.functions.total>0);return{data:{files:t,summary:{line:r(a,i),branch:r(n(l=>l.branches.covered),n(l=>l.branches.total)),function:r(n(l=>l.functions.covered),n(l=>l.functions.total)),statement:r(a,i),files:t.length}},provenance:{method:"instrumented-report",estimated:!1,branchDataCollected:s,functionDataCollected:c,notes:[]}}}async function ic(o){let e=await Zn(o);if(e){let i=ss(e,o);return i?{collected:i,ranTests:!1}:{collected:null,ranTests:!1,testOnlyReport:!0}}if(tr(o)){let i=await rs(o);return i?{collected:i,ranTests:!0}:{collected:nr(o),ranTests:!1}}let n=await rc(o),r=await Zn(o);if(r){let i=ss(r,o);return i?{collected:i,ranTests:n}:{collected:null,ranTests:n,testOnlyReport:!0}}return{collected:nr(o),ranTests:n}}function as(o){return Xt()?"Coverage tooling execution is disabled (AQE_COVERAGE_NO_EXEC). No tests were run and no build tooling was invoked. Unset it, or generate a coverage report yourself and re-run, to get real measurements.":tr(o)?"To get real measurements for this Rust crate, install cargo-llvm-cov (`cargo install cargo-llvm-cov`) and re-run; agentic-qe will invoke it automatically.":"To get real measurements, run your tests with coverage enabled (e.g. `npm test -- --coverage`, `pytest --cov`) and re-run this analysis."}function rr(o){o.registerHandler("analyze-coverage",async e=>{let t=e.payload;try{let n=o.getCoverageAnalyzer(),r=t.target||process.cwd(),i=t.threshold||80,{collected:a,ranTests:s,testOnlyReport:c}=await ic(r);if(!a)return D({lineCoverage:null,branchCoverage:null,functionCoverage:null,statementCoverage:null,totalFiles:0,coverageByFile:[],gaps:[],estimated:!1,measured:!1,coverageMethod:"none",algorithm:"sublinear-O(log n)",warning:c?"The coverage report contains only test files, so there is no production coverage to report. Coverage OF a test file is not a meaningful metric. Check that your coverage tool is instrumenting your source directory.":s?"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. "+as(r)});let{data:l,provenance:u}=a,d=await n.analyze({coverageData:l,threshold:i,includeFileDetails:t.detectGaps});if(!d.success)return d;let m=d.value,p=[];if(t.detectGaps){let f=await n.findGaps(l,i);f.success&&(p=f.value.gaps.map(C=>({file:C.file,lines:C.lines,risk:C.severity,estimated:u.estimated,...u.estimated?{confidence:.2,reason:"Possible coverage gap (STATIC ESTIMATE \u2014 no instrumentation ran)"}:{}})))}let g=f=>Math.round(f*10)/10,h=(f,C)=>C>0?Math.round(f/C*1e3)/10:null,y=[...u.notes];u.estimated&&y.push(as(r));let v=m.recommendations.filter(f=>!(!u.branchDataCollected&&/branch coverage/i.test(f)||!u.functionDataCollected&&/function coverage/i.test(f)));return D({lineCoverage:g(m.summary.line),branchCoverage:u.branchDataCollected?g(m.summary.branch):null,functionCoverage:u.functionDataCollected?g(m.summary.function):null,statementCoverage:g(m.summary.statement),totalFiles:m.summary.files,coverageByFile:l.files.map(f=>({file:f.path,lineCoverage:h(f.lines.covered,f.lines.total)??0,branchCoverage:u.branchDataCollected?h(f.branches.covered,f.branches.total):null,functionCoverage:u.functionDataCollected?h(f.functions.covered,f.functions.total):null})),gaps:p,meetsThreshold:m.meetsThreshold,delta:m.delta,recommendations:v,algorithm:"sublinear-O(log n)",estimated:u.estimated,measured:!u.estimated,coverageMethod:u.method,branchDataCollected:u.branchDataCollected,functionDataCollected:u.functionDataCollected,...y.length>0?{warning:y.join(" ")}:{}})}catch(n){return $(j(n))}})}import*as ir from"fs/promises";import*as ls from"path";k();function sr(o){o.registerHandler("scan-security",async e=>{let t=e.payload;try{let n=o.getSecurityScanner(),r=t.target||process.cwd(),i=await ie(r);if(i.length===0)return D({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 a=i.filter(f=>/\.(ts|tsx|js|jsx|mjs|cjs)$/.test(f)),s=i.filter(f=>!/\.(ts|tsx|js|jsx|mjs|cjs)$/.test(f)),c=[];for(let f of i)try{let C=await ir.readFile(f,"utf-8"),b=C.split(`
399
+ `),E=f.startsWith(r)?f.slice(r.length).replace(/^\//,""):f,w=[{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 w)for(let V=0;V<b.length;V++){let ae=[...b[V].matchAll(O.regex)];for(let Te of ae)c.push({title:O.title,severity:O.severity,location:{file:E,line:V+1},description:`Potential hardcoded secret found at line ${V+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])&&c.push({title:"Potential SQL injection",severity:"high",location:{file:E,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)){c.push({title:"CORS wildcard origin",severity:"high",location:{file:E,line:b.findIndex(V=>O.test(V))+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)&&c.push({title:"Debug mode enabled",severity:"medium",location:{file:E,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)&&c.push({title:"Dangerous eval/exec usage",severity:"high",location:{file:E,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 l=["requirements.txt","pyproject.toml","Gemfile","go.mod","Cargo.toml"];for(let f of l){let C=ls.join(r,f);try{let b=await ir.readFile(C,"utf-8");if(c.push({title:"Dependency audit recommended",severity:"informational",location:{file:f,line:1},description:`Found ${f} \u2014 run language-specific dependency audit (e.g., pip-audit, npm audit, cargo audit)`,category:"dependencies"}),f==="requirements.txt"||f==="pyproject.toml"){let E=[{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 w of E)w.pattern.test(b)&&c.push({title:w.title,severity:w.severity,location:{file:f,line:b.split(`
400
+ `).findIndex(T=>w.pattern.test(T))+1},description:w.description,category:"dependencies"})}}catch{}}let u=a.map(f=>oi.create(f)),d=null;if(t.sast!==!1&&u.length>0){let f=await n.scanFiles(u);f.success&&(d=f.value)}let m=null;if(t.dast&&t.targetUrl){let f=await n.scanUrl(t.targetUrl,{activeScanning:!0,maxDepth:3,timeout:3e4});f.success&&(m=f.value)}let p={critical:c.filter(f=>f.severity==="critical").length,high:c.filter(f=>f.severity==="high").length,medium:c.filter(f=>f.severity==="medium").length,low:c.filter(f=>f.severity==="low").length,informational:c.filter(f=>f.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||[],...c],y=h.sort((f,C)=>{let b={critical:0,high:1,medium:2,low:3,informational:4};return b[f.severity]-b[C.severity]}).slice(0,10).map(f=>({type:f.title,severity:f.severity,file:f.location.file,line:f.location.line,description:f.description})),v=Ki(h);return D({vulnerabilities:h.length,critical:g.critical,high:g.high,medium:g.medium,low:g.low,informational:g.informational,topVulnerabilities:y,recommendations:v,scanTypes:{sast:t.sast!==!1,dast:t.dast||!1},filesScanned:i.length,jstsFilesScanned:a.length,otherFilesScanned:s.length,coverage:d?.coverage,deepAnalysisPerformed:a.length>0,analysisDepth:a.length>0?s.length>0?"full-sast-on-js-ts; pattern-matching-on-other-languages":"full-sast":"pattern-matching-only",...a.length===0?{note:s.length>0?'NO LANGUAGE-SPECIFIC ANALYSIS RAN. Only cross-language pattern matching (secrets, CORS, eval/exec) was applied to these files \u2014 full SAST is implemented for JS/TS only. A zero-finding result here means "nothing matched a generic pattern", NOT "no vulnerabilities". Run a language-specific tool (cargo audit / clippy, bandit, gosec, semgrep) for real coverage of this codebase.':"No source files were analyzed."}:{}})}catch(n){return $(j(n))}})}k();function ar(o){o.registerHandler("assess-quality",async e=>{let t=e.payload;try{let n=o.getQualityAnalyzer(),r=t.threshold||80,i=[];if(t.sourceFiles&&t.sourceFiles.length>0)i=t.sourceFiles;else if(t.target)i=await ie(t.target,{includeTests:!1});else{let u=await import("path"),d=await import("fs"),m=u.join(process.cwd(),"src"),p=d.existsSync(m)?m:process.cwd();i=await ie(p,{includeTests:!1})}if(i.length===0)return D({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 a=await n.analyzeQuality({sourceFiles:i,includeMetrics:t.metrics||["coverage","complexity","maintainability","testability"]});if(!a.success)return a;let s=a.value,c=s.score.overall>=r,l={};for(let u of s.metrics)l[u.name]=u.value;return D({qualityScore:s.score.overall,passed:c,threshold:r,metrics:{coverage:s.score.coverage,complexity:s.score.complexity,maintainability:s.score.maintainability,security:s.score.security,...l},recommendations:s.recommendations.map(u=>`[${u.type}] ${u.title}: ${u.description}`),trends:s.trends.map(u=>({metric:u.metric,direction:u.direction,dataPoints:u.dataPoints.length})),filesAnalyzed:i.length})}catch(n){return $(j(n))}})}import*as us from"fs/promises";k();function or(o){o.registerHandler("validate-requirements",async e=>{let t=e.payload;try{let n=t.requirementsPath||process.cwd(),r=await ie(n,{includeTests:!1,languages:[]}),i=[".md",".feature",".gherkin",".txt",".rst"],a=[];for(let s of r)i.some(c=>s.endsWith(c))&&a.push(s);return D({requirementsAnalyzed:a.length,testable:0,ambiguous:0,untestable:0,coverage:0,bddScenarios:[],warning:a.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:a.map(s=>s.startsWith(n)?s.slice(n.length+1):s).slice(0,20)})}catch(n){return $(j(n))}}),o.registerHandler("validate-contracts",async e=>{let t=e.payload;try{if(!t.contractPath)return D({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 us.readFile(t.contractPath,"utf-8"),r=t.contractPath.endsWith(".json"),i=t.contractPath.endsWith(".yaml")||t.contractPath.endsWith(".yml");return r&&JSON.parse(n),D({contractPath:t.contractPath,valid:!0,format:r?"json":i?"yaml":"unknown",breakingChanges:[],warnings:[],linesAnalyzed:n.split(`
401
+ `).length,note:"Structural validation passed. For semantic contract testing, use consumer-driven contract tests."})}catch(n){return D({contractPath:t.contractPath,valid:!1,breakingChanges:[],warnings:[],error:`Could not read or parse contract file: ${S(n)}`})}}catch(n){return $(j(n))}})}import*as ds from"fs/promises";import*as ms from"path";k();function cr(o){o.registerHandler("index-code",async e=>{let t=e.payload;try{let n=o.getKnowledgeGraph(),r=t.target||process.cwd(),i=Date.now(),a=await ie(r,{includeTests:t.includeTests!==!1,languages:t.languages});if(a.length===0)return D({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 s=await n.index({paths:a,incremental:t.incremental||!1,includeTests:t.includeTests!==!1,languages:t.languages});if(!s.success)return s;let c=s.value,l=new Set,u={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 a){let m=ms.extname(d).slice(1),p=u[m];p&&l.add(p)}return D({filesIndexed:c.filesIndexed,nodesCreated:c.nodesCreated,edgesCreated:c.edgesCreated,symbolsExtracted:c.nodesCreated,relationsFound:c.edgesCreated,target:r,incremental:t.incremental||!1,languages:Array.from(l),duration:c.duration,errors:c.errors,warnings:c.warnings})}catch(n){return $(j(n))}}),o.registerHandler("predict-defects",async e=>{let t=e.payload;try{let n=t.target||process.cwd(),r=t.minConfidence||.5,i=await ie(n,{includeTests:!1});if(i.length===0)return D({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 a=[];for(let u of i)try{let d=await ds.readFile(u,"utf-8"),m=d.split(`
402
+ `),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 y=d.match(/\b(if|else|switch|case|for|while|catch|&&|\|\|)\b/g)||[],v=y.length/Math.max(p,1);v>.15?(g+=.25,h.push(`High branch density (${y.length} branches in ${p} lines)`)):v>.08&&(g+=.1,h.push("Moderate branch complexity")),Math.max(...m.map(E=>{let w=E.match(/^(\s*)/);return w?w[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 E=u.startsWith(n)?u.slice(n.length).replace(/^\//,""):u;a.push({file:E,probability:Math.round(g*100)/100,reason:h.join("; ")})}}catch{}a.sort((u,d)=>d.probability-u.probability);let s=a.length>0?a.reduce((u,d)=>u+d.probability,0)/a.length:0,c=Math.round(s*100),l=[];if(a.length>0){l.push(`${a.length} files flagged for potential defects out of ${i.length} analyzed`);let u=a[0];l.push(`Highest risk: ${u.file} (${Math.round(u.probability*100)}%) \u2014 ${u.reason}`)}return a.some(u=>u.reason.includes("Large file"))&&l.push("Consider splitting large files to reduce complexity"),a.some(u=>u.reason.includes("technical debt"))&&l.push("Address TODO/FIXME comments to reduce technical debt"),a.length===0&&l.push("No files exceeded the defect probability threshold \u2014 code looks healthy"),D({predictedDefects:a.slice(0,20),riskScore:c,recommendations:l,filesAnalyzed:i.length})}catch(n){return $(j(n))}})}function lr(o){o.registerHandler("test-accessibility",async e=>{let t=e.payload;return D({url:t.url||"",standard:t.standard||"wcag21-aa",passed:!1,violations:[],warnings:[],score:0,note:"Accessibility testing requires a browser environment (Puppeteer/Playwright). Use tools like axe-core, pa11y, or Lighthouse CLI for WCAG compliance testing. Example: npx pa11y "+(t.url||"<url>")})}),o.registerHandler("run-chaos",async e=>{let t=e.payload;return D({faultType:t.faultType||"unknown",target:t.target||"unknown",dryRun:t.dryRun??!0,duration:t.duration||0,systemBehavior:"not-executed",resilience:null,note:"Chaos engineering requires infrastructure-level fault injection. Use tools like Chaos Monkey, Litmus, or toxiproxy for real resilience testing. For Node.js apps, consider: nock (HTTP faults), testcontainers (dependency failures)."})}),o.registerHandler("optimize-learning",async e=>{try{let t=await import("./unified-memory-hnsw-KBV3P4OS.js");return D({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 D({patternsLearned:0,modelsUpdated:0,memoryConsolidated:!1,note:'Learning system not initialized. Run "aqe init --auto" first.'})}})}var se=Ee("TaskExecutor");function lc(o){return Ae.resolve(xe.CoverageAnalyzerService)(o)}function uc(o){return Ae.resolve(xe.SecurityScannerService)(o)}function bs(o,e){return Ae.resolve(xe.createTestGeneratorService)(o,e)}function dc(o){return Ae.resolve(xe.KnowledgeGraphService)(o)}function mc(o){return Ae.resolve(xe.QualityAnalyzerService)(o)}function Cs(o){switch(o){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 pc(o){if(["generate-tests","analyze-coverage","scan-security","execute-tests","assess-quality","validate-contracts","test-accessibility","chaos-test","predict-defects","validate-requirements","index-code"].includes(o.type))return null;let t=o.payload?.codeContext||"",n=o.payload?.sourceCode||"",r=t||n;return r?r.includes("var ")&&!r.includes("const ")&&!r.includes("let ")?"var-to-const":r.includes("console.log")||r.includes("console.warn")||r.includes("console.error")?"remove-console":r.includes(".then(")&&r.includes(".catch(")?"promise-to-async":r.includes("require(")&&!r.includes("import ")?"cjs-to-esm":r.includes("function ")&&!r.includes("=>")?"func-to-arrow":null:null}var dr=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=zi(this._config.resultsDir),this.registerHandlers()}kernel;eventBus;_config;resultSaver;coverageAnalyzer=null;securityScanner=null;testGenerator=null;deterministicTestGenerator=null;knowledgeGraph=null;qualityAnalyzer=null;agentBooster=null;taskRouter=null;qualityFeedbackLoop=null;coherenceActionGate=null;taskHandlers=new Map;get config(){return this._config}registerHandler(e,t){this.taskHandlers.set(e,t)}setQualityFeedbackLoop(e){this.qualityFeedbackLoop=e}getCoverageAnalyzer(){return this.coverageAnalyzer||(this.coverageAnalyzer=lc(this.kernel.memory)),this.coverageAnalyzer}getSecurityScanner(){return this.securityScanner||(this.securityScanner=uc(this.kernel.memory)),this.securityScanner}async getTestGenerator(e=!0){return e?(this.testGenerator||(this.testGenerator=bs(this.kernel.memory,await this.resolveLLMRouter())),this.testGenerator):(this.deterministicTestGenerator||(this.deterministicTestGenerator=bs(this.kernel.memory)),this.deterministicTestGenerator)}async resolveLLMRouter(){if(this.kernel.llmRouter)return this.kernel.llmRouter;try{let{getSharedLLMRouter:e}=await import("./base-HH765JFV.js");return await e()??void 0}catch(e){se.debug("LLM router unavailable; using deterministic generation",{error:S(e)});return}}getKnowledgeGraph(){return this.knowledgeGraph||(this.knowledgeGraph=dc(this.kernel.memory)),this.knowledgeGraph}getQualityAnalyzer(){return this.qualityAnalyzer||(this.qualityAnalyzer=mc(this.kernel.memory)),this.qualityAnalyzer}registerHandlers(){Jn(this),rr(this),sr(this),ar(this),or(this),cr(this),lr(this)}async getAgentBooster(){return this.agentBooster||(this.agentBooster=await wt({enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7})),this.agentBooster}async getTaskRouterInstance(){if(!this.taskRouter)try{this.taskRouter=await Qt()}catch{return null}return this.taskRouter}async executeWithAgentBooster(e,t,n){let r=pc(e);if(!r)return console.debug(`[TaskExecutor] No applicable Agent Booster transform for task ${e.id}`),null;try{let i=await this.getAgentBooster(),a=e.payload?.codeContext||e.payload?.sourceCode||"",s=await i.transform(a,r);return s.success&&s.confidence>=.7?(console.debug(`[TaskExecutor] Agent Booster transform succeeded: ${r}, confidence=${s.confidence}`),{taskId:e.id,success:!0,data:{transformed:!0,transformType:r,originalCode:s.originalCode,transformedCode:s.transformedCode,confidence:s.confidence,implementationUsed:s.implementationUsed,durationMs:s.durationMs,changeCount:s.changeCount,tier:0,model:"agent-booster"},duration:Date.now()-t,domain:n}):(console.debug(`[TaskExecutor] Agent Booster low confidence (${s.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=${Cs(t)}, success=${n}, duration=${r}ms`),this.qualityFeedbackLoop){let a=e.targetDomains||[],s=n?1:0,c=r<100?1:r<500?.8:r<2e3?.6:r<5e3?.4:r<1e4?.2:.1,l=.25*s+.325+.1*c;await this.qualityFeedbackLoop.recordRoutingOutcome({taskId:e.id,taskDescription:e.type,recommendedAgent:String(t),usedAgent:String(t),followedRecommendation:!0,success:n,qualityScore:l,durationMs:r,timestamp:new Date,error:n?void 0:"Task execution failed"})}}catch(i){console.warn("[TaskExecutor] Failed to record outcome:",i)}}async execute(e){let t=Date.now(),n=this.getTaskDomain(e.type),r=e.payload,i=r?.routingTier??2,a=r?.useAgentBooster??!1,s=r?.compiledContext??void 0,c=Cs(i);s&&e.payload&&(e.payload.__compiledContext=s),console.debug(`[TaskExecutor] Executing task ${e.id}: type=${e.type}, tier=${i}, model=${c}, useAgentBooster=${a}${s?", hasContext=true":""}`);let l=this.evaluateCoherenceGate(e,n);l&&console.debug(`[TaskExecutor] Coherence gate: task=${e.id}, decision=${l.decision}, combined=${l.combinedScore.toFixed(3)}, advisory=${l.advisory}`),this.validateWithReasoningQEC(e,n);try{if(i===0||a){let p=await this.executeWithAgentBooster(e,t,n);if(p)return this.recordOutcome(e,0,!0,Date.now()-t).catch(g=>{se.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),await this.publishTaskCompleted(e.id,p.data,n),p;console.debug(`[TaskExecutor] Agent Booster fallback to Tier 1 for task ${e.id}`)}let u=this.taskHandlers.get(e.type);if(!u){let p={taskId:e.id,success:!1,error:`No handler registered for task type: ${e.type}`,duration:Date.now()-t,domain:n};return this.recordOutcome(e,i,!1,Date.now()-t).catch(g=>{se.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),p}let d=await Promise.race([u(e),this.timeout(e.timeout||this._config.timeout)]);if(!d.success){let p="error"in d?d.error.message:"Unknown error";return await this.publishTaskFailed(e.id,p,n),this.recordOutcome(e,i,!1,Date.now()-t).catch(g=>{se.warn("recordOutcome failed",{error:g instanceof Error?g.message:String(g),taskId:e.id})}),{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=>{se.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:c,usedAgentBooster:!1}},duration:Date.now()-t,domain:n,savedFiles:m}}catch(u){let d=S(u);return await this.publishTaskFailed(e.id,d,n),this.recordOutcome(e,i,!1,Date.now()-t).catch(m=>{se.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=Qi({advisory:!0}));let n=e.payload,r=typeof n?.confidence=="number"?n.confidence:.7,i=n?.riskLevel??"medium";return Wi(e.type,t,r,i,n??{},this.coherenceActionGate)}catch(n){return se.warn("Coherence gate evaluation error (continuing)",{error:n instanceof Error?n.message:String(n),taskId:e.id}),null}}_reasoningQEC=null;_reasoningQECLoaded=!1;validateWithReasoningQEC(e,t){try{if(!this._reasoningQECLoaded){this._reasoningQECLoaded=!0;try{let{isReasoningQECEnabled:a}=(Et(),Wr(Ma));if(a()){let{createReasoningQEC:s}=(vs(),Wr(ys));this._reasoningQEC=s()}}catch(a){se.debug("ReasoningQEC module unavailable",{error:a instanceof Error?a.message:String(a)})}}if(!this._reasoningQEC)return;let n=e.payload,r=n?.reasoningSteps;if(!r||r.length<2)return;let i=this._reasoningQEC.validate({type:t,context:n,steps:r});i.valid||se.warn("ReasoningQEC validation found issues (advisory)",{taskId:e.id,domain:t,confidence:i.confidence,issues:i.issues.length})}catch(n){se.debug("ReasoningQEC evaluation error",{error:n instanceof Error?n.message:String(n),taskId:e.id})}}getTaskDomain(e){return{"generate-tests":"test-generation","execute-tests":"test-execution","analyze-coverage":"coverage-analysis","assess-quality":"quality-assessment","predict-defects":"defect-intelligence","validate-requirements":"requirements-validation","index-code":"code-intelligence","scan-security":"security-compliance","validate-contracts":"contract-testing","test-accessibility":"visual-accessibility","run-chaos":"chaos-resilience","optimize-learning":"learning-optimization","cross-domain-workflow":"learning-optimization","protocol-execution":"learning-optimization","ideation-assessment":"requirements-validation"}[e]||"learning-optimization"}async timeout(e){return new Promise((t,n)=>{setTimeout(()=>n(new Error(`Task execution timed out after ${e}ms`)),e)})}async publishTaskCompleted(e,t,n){await this.eventBus.publish({id:q(),type:"TaskCompleted",timestamp:new Date,source:n,payload:{taskId:e,result:t}})}async publishTaskFailed(e,t,n){await this.eventBus.publish({id:q(),type:"TaskFailed",timestamp:new Date,source:n,payload:{taskId:e,error:t}})}};function Ts(o,e){return new dr(o,o.eventBus,e)}async function Ss(){}import{randomUUID as _e}from"crypto";k();var mr={effectiveness:.25,coverage:.2,mutationKill:.15,stability:.15,maintainability:.15,performance:.1},pr={"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}},ge={qualityWeights:mr,promotionCriteria:pr,autoPromote:!0,autoDemote:!0,minCoverageImprovementToLearn:5,maxOutcomesInMemory:1e4,persistOutcomes:!0,batchSize:100};oe();k();Q();var gr=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}},hr=class o{store;reasoningBank=null;config;db=null;persistCount=0;static RETENTION_CLEANUP_INTERVAL=100;patternMetrics=new Map;constructor(e={}){this.config={...ge,...e},this.store=new gr(this.config.maxOutcomesInMemory)}connectReasoningBank(e){this.reasoningBank=e}async initialize(){try{this.db=U(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb()}catch(e){console.warn("[TestOutcomeTracker] DB initialization failed, using memory-only:",S(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
403
403
  SELECT * FROM test_outcomes ORDER BY created_at DESC LIMIT ?
404
404
  `).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(`
405
405
  INSERT OR REPLACE INTO test_outcomes (
@@ -414,7 +414,7 @@ ${p}`,estimatedTokens:Math.ceil(p.length/3.5),relevance:.6})}}}finally{i.close()
414
414
  DELETE FROM test_outcomes WHERE id NOT IN (
415
415
  SELECT id FROM test_outcomes ORDER BY created_at DESC LIMIT ?
416
416
  )
417
- `).run(t)}catch(t){console.warn("[TestOutcomeTracker] Retention cleanup failed:",S(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,a=e.flaky?.2:1-(e.flakinessScore??0),s=e.maintainabilityScore,l=Math.max(0,1-e.executionTimeMs/1e4);return t.effectiveness*n+t.coverage*r+t.mutationKill*i+t.stability*a+t.maintainability*s+t.performance*l}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(s=>s.passed&&!s.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,a=e.reduce((p,g)=>p+g.executionTimeMs,0)/e.length,s=e.filter(p=>p.flaky).length,c=e.reduce((p,g)=>p+g.maintainabilityScore,0)/e.length,l=new Map,u=this.groupBy(e,p=>p.generatedBy);for(let[p,g]of u)l.set(p,{total:g.length,passed:g.filter(h=>h.passed).length,avgCoverage:g.reduce((h,y)=>h+y.coverage.lines,0)/g.length,avgMaintainability:g.reduce((h,y)=>h+y.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,y)=>h+y.coverage.lines,0)/g.length});return{totalTests:e.length,passedTests:t,passRate:t/e.length,avgCoverage:n,avgMutationScore:i,avgExecutionTimeMs:a,flakyTests:s,avgMaintainability:c,byAgent:l,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),a=n.get(i)||[];a.push(r),n.set(i,a)}return n}};function gs(o){return new dr(o)}import{randomUUID as ic}from"crypto";ae();k();Q();var mr=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}},pr=class o{sessionStore;strategies=new Map;reasoningBank=null;config;db=null;persistCount=0;static RETENTION_CLEANUP_INTERVAL=50;constructor(e={}){this.config={...pe,...e},this.sessionStore=new mr(this.config.maxOutcomesInMemory)}connectReasoningBank(e){this.reasoningBank=e}async initialize(){try{this.db=U(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb()}catch(e){console.warn("[CoverageLearner] DB init failed, using memory-only:",S(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
417
+ `).run(t)}catch(t){console.warn("[TestOutcomeTracker] Retention cleanup failed:",S(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,a=e.flaky?.2:1-(e.flakinessScore??0),s=e.maintainabilityScore,l=Math.max(0,1-e.executionTimeMs/1e4);return t.effectiveness*n+t.coverage*r+t.mutationKill*i+t.stability*a+t.maintainability*s+t.performance*l}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(s=>s.passed&&!s.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,a=e.reduce((p,g)=>p+g.executionTimeMs,0)/e.length,s=e.filter(p=>p.flaky).length,c=e.reduce((p,g)=>p+g.maintainabilityScore,0)/e.length,l=new Map,u=this.groupBy(e,p=>p.generatedBy);for(let[p,g]of u)l.set(p,{total:g.length,passed:g.filter(h=>h.passed).length,avgCoverage:g.reduce((h,y)=>h+y.coverage.lines,0)/g.length,avgMaintainability:g.reduce((h,y)=>h+y.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,y)=>h+y.coverage.lines,0)/g.length});return{totalTests:e.length,passedTests:t,passRate:t/e.length,avgCoverage:n,avgMutationScore:i,avgExecutionTimeMs:a,flakyTests:s,avgMaintainability:c,byAgent:l,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),a=n.get(i)||[];a.push(r),n.set(i,a)}return n}};function Es(o){return new hr(o)}import{randomUUID as gc}from"crypto";oe();k();Q();var fr=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}},yr=class o{sessionStore;strategies=new Map;reasoningBank=null;config;db=null;persistCount=0;static RETENTION_CLEANUP_INTERVAL=50;constructor(e={}){this.config={...ge,...e},this.sessionStore=new fr(this.config.maxOutcomesInMemory)}connectReasoningBank(e){this.reasoningBank=e}async initialize(){try{this.db=U(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb()}catch(e){console.warn("[CoverageLearner] DB init failed, using memory-only:",S(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
418
418
  SELECT * FROM coverage_sessions ORDER BY created_at DESC LIMIT ?
419
419
  `).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 a=this.extractFilePattern(r.targetPath),s=`${r.technique}:${a}`,c=this.strategies.get(s);c?this.strategies.set(s,{...c,avgImprovement:(c.avgImprovement*c.successCount+i)/(c.successCount+1),successCount:c.successCount+1,confidence:Math.min(1,c.confidence+.05),lastUsedAt:new Date(n.completed_at)}):this.strategies.set(s,{id:`strategy-${n.id}`,description:`Coverage strategy: ${r.technique} for ${a} files`,technique:r.technique,filePatterns:[a],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(`
420
420
  INSERT OR REPLACE INTO coverage_sessions (
@@ -428,17 +428,17 @@ ${p}`,estimatedTokens:Math.ceil(p.length/3.5),relevance:.6})}}}finally{i.close()
428
428
  DELETE FROM coverage_sessions WHERE id NOT IN (
429
429
  SELECT id FROM coverage_sessions ORDER BY created_at DESC LIMIT ?
430
430
  )
431
- `).run(t)}catch(t){console.warn("[CoverageLearner] Retention cleanup failed:",S(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,a=n.functions-t.functions;return r*.4+i*.35+a*.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()}-${ic().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(s=>s.addressed).length,a=e.gapsTargeted.length;return`${r} for ${this.extractFilePattern(e.targetPath)} files. Achieved ${t.toFixed(1)}% improvement. Addressed ${i}/${a} 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(s=>t.includes(s.split("/").pop()||"")||s.includes(t.split("/").pop()||""))||i.filePatterns.length===0){let s=(Date.now()-i.lastUsedAt.getTime())/864e5,c=Math.max(.5,1-s/30),l=i.avgImprovement*i.confidence*c;l>r&&(r=l,n=i)}return n}getAllStrategies(){return Array.from(this.strategies.values())}getStrategiesByTechnique(e){return this.getAllStrategies().filter(t=>t.technique===e)}getSessionStats(){let e=this.sessionStore.getAll();if(e.length===0)return{totalSessions:0,successfulSessions:0,avgImprovement:0,byTechnique:new Map,strategiesLearned:0};let t=e.map(s=>this.calculateOverallImprovement(s)),n=t.filter(s=>s>=this.config.minCoverageImprovementToLearn).length,r=t.reduce((s,c)=>s+c,0)/t.length,i=new Map,a=new Map;for(let s of e){let c=a.get(s.technique)||[];c.push(s),a.set(s.technique,c)}for(let[s,c]of a){let l=c.map(u=>this.calculateOverallImprovement(u));i.set(s,{count:c.length,avgImprovement:l.reduce((u,d)=>u+d,0)/l.length})}return{totalSessions:e.length,successfulSessions:n,avgImprovement:r,byTechnique:i,strategiesLearned:this.strategies.size}}analyzeGapResolution(){let t=this.sessionStore.getAll().flatMap(i=>i.gapsTargeted);if(t.length===0)return{totalGapsTargeted:0,gapsAddressed:0,resolutionRate:0,byGapType:new Map};let n=t.filter(i=>i.addressed).length,r=new Map;for(let i of t){let a=r.get(i.type)||{targeted:0,addressed:0};a.targeted++,i.addressed&&a.addressed++,r.set(i.type,a)}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 hs(o){return new pr(o)}var gr=class{weights;historicalScores=[];maxHistory;constructor(e={},t=100){this.weights={...cr,...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((a,s)=>a+s,0)/e.length,r=t.reduce((a,s)=>a+s,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 a of e){let s=this.calculateDimensions(a);t.effectiveness+=s.effectiveness,t.coverage+=s.coverage,t.mutationKill+=s.mutationKill,t.stability+=s.stability,t.maintainability+=s.maintainability,t.performance+=s.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 fs(o,e){return new gr(o,e)}var hr=class{criteria;promotionHistory=[];demotionHistory=[];reasoningBank=null;config;constructor(e={}){this.config={...pe,...e},this.criteria={...lr}}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 a={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(a),a}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 a={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(a),a}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 a of this.promotionHistory)e[a.toTier]++;let t={"short-term":0,working:0,"long-term":0,permanent:0};for(let a of this.demotionHistory)t[a.toTier]++;let n=Date.now()-10080*60*1e3,r=this.promotionHistory.filter(a=>a.timestamp.getTime()>n).length,i=this.demotionHistory.filter(a=>a.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 ys(o){return new hr(o)}var fr=class{outcomeTracker;coverageLearner;qualityCalculator;promotionManager;routingFeedback;reasoningBank=null;config;constructor(e={}){this.config={...pe,...e},this.outcomeTracker=gs(this.config),this.coverageLearner=hs(this.config),this.qualityCalculator=fs(this.config.qualityWeights),this.promotionManager=ys(this.config),this.routingFeedback=Zr(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,a=this.outcomeTracker.getPatternMetrics(e.patternId);if(a){let s=await this.promotionManager.processPatternChange(i,{patternId:e.patternId,successCount:a.successCount,failureCount:a.failureCount,successRate:a.successRate,qualityScore:a.avgQuality,ageDays:this.calculateAgeDays(i.createdAt),recentSuccessRate:this.calculateRecentSuccessRate(e.patternId),recentFailureCount:this.calculateRecentFailures(e.patternId)});n={action:s.action,tier:s.event&&"toTier"in s.event?s.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(),a=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:a.totalOutcomes,recommendationFollowRate:1-a.overrideRate,successRateWhenFollowed:a.recommendationSuccessRate,successRateWhenOverridden:a.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 vs(o){let e=new fr(o);return await e.initialize(),bs=e,e}var bs=null;function Cs(){return bs}function _e(){return`test-${Ie()}`}function Ss(o){return`${o}-${Ie()}`}function Xt(o){return{enabled:!0,agentId:Ss(o),message:"Experience captured asynchronously via learning pipeline"}}async function sc(o,e,t,n,r){let i=Ss(o);try{let{kernel:a}=Je();if(!a)return{enabled:!1,agentId:i,message:"Learning engine not available - kernel not initialized"};let s=await oc();if(!s)return{enabled:!1,agentId:i,message:"Learning engine not available"};let c=s.getExperienceCaptureService();if(!c)return{enabled:!1,agentId:i,message:"Experience capture service not available"};let l=ac(e),u=c.startCapture(`${e}: ${JSON.stringify(t).slice(0,200)}`,{agent:o,domain:l||void 0,metadata:{tool:e,durationMs:r}});c.recordStep(u,{action:`execute-${e}`,result:typeof n=="object"?JSON.stringify(n).slice(0,500):String(n).slice(0,500),quality:.7});let d=await c.completeCapture(u,{success:!0,quality:.7});if(d.success){let m=d.value;return{enabled:!0,agentId:i,message:`Experience captured: ${m.id} (domain: ${l||"general"}, quality: ${m.quality})`,experienceId:m.id,domain:l||"general"}}return{enabled:!0,agentId:i,message:"Experience capture completed (no pattern extracted)"}}catch(a){return{enabled:!1,agentId:i,message:`Learning capture failed: ${S(a)}`}}}function ac(o){return{test_generate_enhanced:"test-generation",test_execute_parallel:"test-execution",coverage_analyze_sublinear:"coverage-analysis",quality_assess:"quality-assessment",security_scan_comprehensive:"security-compliance",contract_validate:"contract-testing",accessibility_test:"visual-accessibility",chaos_test:"chaos-resilience",defect_predict:"defect-intelligence",requirements_validate:"requirements-validation",code_index:"code-intelligence"}[o]||null}async function oc(){return As()}async function cc(o,e,t,n){let r=Cs();if(!r&&yr&&(r=await yr),!!r){if(o==="test-generation"&&e){let i=e.tests||e.generatedTests||[];for(let a of i.slice(0,20)){let s={id:String(a.id||Ie()),testId:String(a.id||a.name||Ie()),testName:String(a.name||a.testName||"generated-test"),generatedBy:"qe-test-generation",patternId:a.patternId,framework:a.framework||n.framework||"vitest",language:a.language||n.language||"typescript",domain:"test-generation",passed:a.passed!==!1,coverage:{lines:Number(a.coverageLines||0),branches:Number(a.coverageBranches||0),functions:Number(a.coverageFunctions||0)},executionTimeMs:Number(a.executionTimeMs||t/Math.max(i.length,1)),flaky:!!a.flaky,maintainabilityScore:Number(a.qualityScore||a.maintainability||.7),timestamp:new Date};await r.recordTestOutcome(s)}}if(o==="coverage-analysis"&&e){let i={id:Ie(),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((a,s)=>({id:String(a.id||`gap-${Ie().slice(0,8)}-${s}`),type:["uncovered-line","uncovered-branch","uncovered-function","partial-branch"].includes(String(a.type))?String(a.type):"uncovered-line",filePath:String(a.file||a.filePath||""),startLine:Number(a.line||a.startLine||0),endLine:a.endLine?Number(a.endLine):void 0,riskScore:Number(a.riskScore||.5),addressed:!!a.addressed})),durationMs:t,startedAt:new Date(Date.now()-t),completedAt:new Date};await r.recordCoverageSession(i)}}}function Es(o){let e=o.split(`
432
- `).length,t=(o.match(/if|switch|for|while|catch/g)||[]).length;return{score:e+t*2,level:t>5?"high":t>2?"medium":"low"}}function ws(o,e){let t=[];return o.level==="high"&&(t.push("Consider refactoring complex functions"),t.push("Add unit tests for each branch")),t.push("Consider adding edge case tests"),t.push("Add error handling tests"),e==="integration"&&(t.push("Add mock external dependencies"),t.push("Test API contract boundaries")),{recommendations:t,estimatedTime:`${Math.round(o.score*.5)} minutes`,confidence:.85}}function Rs(o,e,t,n){let r=[],i=/(?:function\s+(\w+)|const\s+(\w+)\s*=|def\s+(\w+)|func\s+(\w+))/g,a=[],s;for(;(s=i.exec(o))!==null;){let l=s[1]||s[2]||s[3]||s[4];l&&a.push(l)}for(let l=0;l<Math.min(a.length,n);l++){let u=a[l]||"exampleFunction";r.push({id:_e(),name:`test_${u}_${l}`,type:e,parameters:[],assertions:[`${u}() === null`],expectedResult:null,estimatedDuration:e==="integration"?2e3:1e3,aiGenerated:!0})}(e==="integration"||n>a.length)&&r.push({id:_e(),name:`integration_ComponentA_${r.length}`,type:"integration",parameters:[],assertions:["ComponentA integration test passes"],expectedResult:null,estimatedDuration:2e3,aiGenerated:!0});let c=["high-complexity","deep-nesting","null-handling","empty-input"];for(let l=r.length;l<n&&l-r.length<c.length;l++)r.push({id:_e(),name:`edge_case_${c[l-r.length]}_${l}`,type:"unit",parameters:[],assertions:[`${c[l-r.length]} edge case handled`],expectedResult:null,estimatedDuration:1500,aiGenerated:!0});return r}function Ps(o,e){let t=[],n=o.split(`
433
- `);return o.includes("eval(")&&t.push({type:"dangerous-eval",line:n.findIndex(r=>r.includes("eval("))+1,severity:"critical",suggestion:"Replace eval() with safer alternatives"}),o.includes("var ")&&(e==="javascript"||e==="typescript")&&t.push({type:"var-usage",line:n.findIndex(r=>r.includes("var "))+1,severity:"low",suggestion:"Use const or let instead of var"}),o.includes("any")&&e==="typescript"&&t.push({type:"any-type",line:n.findIndex(r=>r.includes("any"))+1,severity:"medium",suggestion:"Replace any with specific types"}),t}var Ye=null,yr=null,oe=null,lc=Number(process.env.AQE_ROUTE_TIMEOUT_MS)||5e3;function uc(o,e,t){return new Promise(n=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(t))},e);typeof i.unref=="function"&&i.unref(),o.then(a=>{r||(r=!0,clearTimeout(i),n(a))},()=>{r||(r=!0,clearTimeout(i),n(t))})})}function dc(){if(!Ye){let{kernel:o}=Je();if(!o)throw new Error("Kernel not initialized");Ye=ms(o);let e=Ye;yr=vs().then(t=>(e.setQualityFeedbackLoop(t),t)).catch(t=>(console.warn("[HandlerFactory] Failed to initialize QualityFeedbackLoop:",t),null))}return Ye}function xs(){if(Ye=null,oe){let o=oe;oe=null,o.dispose().catch(()=>{})}}async function As(){if(oe)return oe;try{let{kernel:o}=Je();if(!o)return null;let{createAQELearningEngine:e}=await import("./aqe-learning-engine-NXRNKJNA.js"),t=o.memory,n=e(t,{projectRoot:process.cwd(),enableClaudeFlow:!1});return await n.initialize(),oe=n,oe}catch(o){return console.debug("[HandlerFactory] Learning engine init failed:",S(o)),null}}async function mc(o,e){try{let t=await As();if(!t)return[];let n=e,r=await t.searchPatterns(o,{limit:5,minConfidence:.4,domain:n,useVectorSearch:!0});return!r.success||r.value.length===0?[]:r.value.filter(i=>i.similarity>=.4).map(i=>({name:i.pattern.name,description:i.pattern.description,similarity:i.similarity,confidence:i.pattern.confidence,canReuse:i.canReuse,patternId:i.pattern.id}))}catch(t){return console.debug("[HandlerFactory] Pattern search failed:",S(t)),[]}}async function pc(o,e,t){try{let n=await mc(o,e);return n.length>0&&console.debug(`[HandlerFactory] Found ${n.length} relevant patterns for ${e}`),await(await Ut()).routeTask({task:o,domain:e,codeContext:t,agentType:`qe-${e}`,enablePatternSearch:!0,patternHints:n.length>0?n:void 0})}catch(n){return console.error(`[HandlerFactory] Routing failed for ${e}: ${n}`),null}}async function Ts(o,e,t,n){if(!(!o||o.length===0)&&oe)try{for(let r of o)r.patternId&&await oe.recordOutcome({patternId:r.patternId,success:e,metrics:{executionTimeMs:n},feedback:`Domain handler ${t} execution ${e?"succeeded":"failed"}`})}catch{}}function K(o){let{domain:e,taskType:t,priority:n="p1",defaultTimeout:r=18e4,buildTaskDescription:i,mapToPayload:a,mapToResult:s,calculateTimeout:c,includeCodeContext:l}=o;return async u=>{if(!Oe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:d}=Je(),m=null;try{let p=i(u),g=l?.(u);m=await uc(pc(p,e,g),lc,null);let h=a(u,m),y=c?.(u)??r,v=await d.submitTask({type:t,priority:n,targetDomains:[e],payload:h,timeout:y});if(!v.success)return{success:!1,error:v.error.message};let f=dc(),C=d.getTaskStatus(v.value);if(!C)return{success:!1,error:"Task not found after submission"};let b=await f.execute(C.task);if(!b.success)return{success:!1,error:b.error||"Task execution failed"};let E=b.data,w=s(v.value,E,b.duration,b.savedFiles,u);Ts(m?.patternHints,!0,e,b.duration),sc(`qe-${e}`,t,u,E,b.duration).catch(()=>{});try{await cc(e,E,b.duration,u)}catch{}return{success:!0,data:w}}catch(p){let g=S(p);return Ts(m?.patternHints,!1,e,0),{success:!1,error:`Failed to ${t.replace(/-/g," ")}: ${g}`}}}}var Yt=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(s=>s.success).length/this.taskMetrics.length,r=this.taskMetrics.reduce((s,c)=>s+c.retries,0)/this.taskMetrics.length,i=Math.min(.2,r*.1),a=t*(1-i);return Math.min(1,Math.max(0,a))}getLoadBalanceScore(){if(this.workerLoads.size===0)return .9;let e=Array.from(this.workerLoads.values()).map(s=>s.completedTaskCount);if(e.length<=1)return 1;let t=e.reduce((s,c)=>s+c,0)/e.length;if(t===0)return 1;let n=e.reduce((s,c)=>s+Math.pow(c-t,2),0)/e.length,a=1/(1+Math.sqrt(n)/t);return Math.min(1,Math.max(0,a))}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()}},fe=new Yt;Ta();function gc(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function hc(o){return Array.isArray(o)&&o.every(e=>typeof e=="string")}function fc(o){return typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1}function ks(o){let e=[];return gc(o)?(o.contract!=="risk-decision@1"&&e.push('contract must be "risk-decision@1"'),["approve","block","escalate"].includes(o.decision)||e.push("decision must be approve|block|escalate"),hc(o.riskFactors)||e.push("riskFactors must be string[]"),fc(o.confidence)||e.push("confidence must be a number in [0,1]"),(typeof o.rationale!="string"||o.rationale.length===0)&&e.push("rationale must be a non-empty string"),{valid:e.length===0,errors:e}):{valid:!1,errors:["not an object"]}}function Ms(o){let{passed:e,qualityScore:t,recommendations:n=[]}=o,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 Ds=Object.keys(wt);function yc(o){if(!o)return"typescript";let e=o.toLowerCase().trim(),t={ts:"typescript",js:"javascript",py:"python","c#":"csharp","c-sharp":"csharp",cs:"csharp",golang:"go",rs:"rust",kt:"kotlin"};return t[e]?t[e]:Ds.includes(e)?e:null}var Is={domain:"test-generation",taskType:"generate-tests",priority:"p1",defaultTimeout:12e4,buildTaskDescription:o=>`Generate ${o.testType||"unit"} tests for ${o.language||"typescript"} code`,includeCodeContext:o=>o.sourceCode,mapToPayload:(o,e)=>{let t=yc(o.language);if(t===null)throw new Error(`Unsupported language '${o.language}'. Supported languages: ${Ds.join(", ")}. Open a feature request for additional language support.`);let n;if(o.framework){n=o.framework;let r=ei[n];if(r&&r!==t){let i=a=>a==="javascript"||a==="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 (${wt[t]}).`)}}else n=wt[t];return{sourceCode:o.sourceCode,filePath:o.filePath,language:t,framework:n,testType:o.testType||"unit",coverageGoal:o.coverageGoal||80,aiEnhancement:o.aiEnhancement!==!1,detectAntiPatterns:o.detectAntiPatterns||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,n,r)=>{let i=r?.sourceCode||"",a=r?.language||"typescript",s=r?.testType||"unit",c=e.testsGenerated||6,l=Es(i),u=r?.aiEnhancement!==!1?ws(l,s):{recommendations:[],estimatedTime:"0 minutes",confidence:0},d=r?.detectAntiPatterns?Ps(i,a):[],m=Xt("test-generator"),p=e.tests,g=Array.isArray(p)&&p.length>0&&p[0].testCode,h=e.llmEnhanced===!0,y=g?p.map((v,f)=>({id:_e(),name:v.name||`test_${f}`,type:v.type||s,parameters:[],assertions:v.testCode?vc(v.testCode):[`test assertion ${f}`],expectedResult:null,estimatedDuration:v.type==="integration"?2e3:1e3,aiGenerated:h,testCode:v.testCode,sourceFile:v.sourceFile,testFile:v.testFile||v.file})):Rs(i,s,a,c);return{tests:y,antiPatterns:d,suggestions:d.map(v=>`Fix: ${v.type} - ${v.suggestion}`),aiInsights:u,coverage:{predicted:e.coverageEstimate||r?.coverageGoal||80,confidence:h?.9:.3,achievable:!0},properties:y.filter(v=>v.type==="property").map(v=>({name:v.name,invariant:"output_matches_expectation"})),language:a,complexity:l,learning:m,taskId:o,status:"completed",testsGenerated:y.length,coverageEstimate:e.coverageEstimate||r?.coverageGoal||80,patternsUsed:e.patternsUsed||["assertion-patterns","mock-generation","edge-case-detection"],duration:t,savedFiles:n,llmEnhanced:h,...e.generationMode?{generationMode:e.generationMode}:{},...e.note?{note:e.note}:{}}}},_s={domain:"test-execution",taskType:"execute-tests",priority:"p1",defaultTimeout:3e5,buildTaskDescription:o=>`Execute ${o.testFiles?.length||0} test files with ${o.parallel!==!1?"parallel":"sequential"} execution`,mapToPayload:(o,e)=>({testFiles:o.testFiles||[],testSuites:o.testSuites||[],parallel:o.parallel!==!1,parallelism:o.parallelism||4,retryCount:o.retryCount||3,timeout:o.timeout||6e4,collectCoverage:o.collectCoverage||!1,reportFormat:o.reportFormat||"json",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:o=>o.timeout||3e5,mapToResult:(o,e,t,n,r)=>{let i=e.total||0,a=e.passed||0,s=e.failed||0,c=e.coverage,l=r?.parallelism||4,u=fe.getRetryStats(),d=fe.getWorkersUsed(),m={workersUsed:d>0?d:Math.min(l,i||1),efficiency:fe.getWorkerEfficiency(),loadBalance:fe.getLoadBalanceScore(),avgExecutionTime:t/Math.max(i,1)},p={totalRetries:u.totalRetries,successfulRetries:u.successfulRetries,maxRetriesReached:u.maxRetriesReached},g=Xt("test-executor");return{workerStats:m,retryStats:p,results:(()=>{let h=fe.getTestDurations(i);return Array.from({length:i},(y,v)=>({id:_e(),name:`test_case_${v}`,status:v<a?"passed":"failed",duration:h[v]||200,retries:0}))})(),summary:{totalTests:i,passRate:i>0?a/i*100:0,avgDuration:t/Math.max(i,1),parallelEfficiency:m.efficiency},learning:g,taskId:o,status:"completed",total:i,passed:a,failed:s,duration:t,coverage:c,savedFiles:n}}},Os={domain:"coverage-analysis",taskType:"analyze-coverage",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Analyze coverage for ${o.target||"project"} with gap detection`,mapToPayload:(o,e)=>({target:o.target||".",includeRisk:o.includeRisk||!1,detectGaps:o.detectGaps!==!1,mlPowered:o.mlPowered||!1,prioritization:o.prioritization||"complexity",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>{let r=e.summary,i=r?.files??e.totalFiles??0,a=e.gaps||[],s=e.branchDataCollected===!0,c=e.functionDataCollected===!0,l=s?r?.branch??e.branchCoverage??null:null,u=c?r?.function??e.functionCoverage??null:null,d=e.estimated===!0,m=e.measured===!0,g=r?.line??e.lineCoverage??null,y=r?.statement??e.statementCoverage??g,v=Xt("coverage-analyzer"),f=a.map((E,w)=>{let T=E;return T?.file?{id:`gap-${Date.now()}-${w}`,file:T.file,line:T.lines?.[0]||0,uncoveredLines:T.lines||[],type:T.type||"uncovered-line",severity:T.severity||"medium",reason:T.reason||"Missing test case",priority:T.priority||"medium",suggestion:T.suggestedTest||"Add test coverage",suggestedTest:T.suggestedTest||"Add test coverage",riskScore:T.riskScore||.5,confidence:T.confidence??(m?.7:.2),estimated:T.estimated===!0||d}:null}).filter(E=>E!==null),C=e.coverageByFile;return{coverageByFile:C?C.map(E=>({file:E.file,lineCoverage:E.lineCoverage||0,branchCoverage:E.branchCoverage??null,functionCoverage:E.functionCoverage??null})):[],gapAnalysis:{totalGaps:f.length,highPriority:f.filter(E=>E.priority==="high").length,gaps:f},trends:{lineCoverageTrend:i>0?"stable":"no-data",branchCoverageTrend:i>0?"stable":"no-data",weeklyChange:0},aiInsights:i>0?{recommendations:d?["ESTIMATED RESULT \u2014 no instrumentation ran. The figures below are a static guess from source shape, not measured coverage. Do not act on individual gaps without running real instrumentation first.",...e.recommendations||[]]:e.recommendations||["Run tests with coverage enabled to get accurate metrics"],riskAssessment:d||!m||g===null?"unknown":g<70?"high":g<85?"medium":"low",confidence:d?.2:m?.88:0}:{recommendations:["No coverage data found. Run tests with coverage first (e.g., npm test -- --coverage, or pytest --cov)"],riskAssessment:"unknown",confidence:0},learning:v,taskId:o,status:"completed",lineCoverage:g,branchCoverage:l,functionCoverage:u,statementCoverage:y,totalFiles:i,gaps:f,duration:t,savedFiles:n,estimated:d,measured:m,coverageMethod:e.coverageMethod??"unknown",branchDataCollected:s,functionDataCollected:c,...e.warning?{warning:e.warning}:{}}}},Fs={domain:"quality-assessment",taskType:"assess-quality",priority:"p0",defaultTimeout:18e4,buildTaskDescription:o=>`Assess quality with ${o.runGate?"quality gate":"metrics analysis"}`,mapToPayload:(o,e)=>({runGate:o.runGate||!1,threshold:o.threshold||80,metrics:o.metrics||["coverage","complexity","maintainability"],routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>{let r=Ms({passed:typeof e.passed=="boolean"?e.passed:void 0,qualityScore:e.qualityScore,recommendations:e.recommendations||[]});return{taskId:o,status:"completed",qualityScore:e.qualityScore||0,passed:e.passed||!1,metrics:e.metrics||{},recommendations:e.recommendations||[],duration:t,savedFiles:n,...ks(r).valid?{riskDecision:r}:{}}}},Ls={domain:"security-compliance",taskType:"scan-security",priority:"p0",defaultTimeout:6e5,buildTaskDescription:o=>{let e=[];return o.sast!==!1&&e.push("SAST"),o.dast&&e.push("DAST"),`Security scan (${e.join(", ")}) for ${o.target||"project"}`},mapToPayload:(o,e)=>({sast:o.sast!==!1,dast:o.dast||!1,compliance:o.compliance||[],target:o.target||".",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,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})},Ns={domain:"contract-testing",taskType:"validate-contracts",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Validate API contract at ${o.contractPath}`,mapToPayload:(o,e)=>({contractPath:o.contractPath,providerUrl:o.providerUrl,consumerName:o.consumerName,checkBreakingChanges:o.checkBreakingChanges!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",valid:e.valid||!1,breakingChanges:e.breakingChanges||[],warnings:e.warnings||[],duration:t,savedFiles:n})},qs={domain:"visual-accessibility",taskType:"test-accessibility",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Test accessibility for ${o.url} against ${o.standard||"WCAG 2.1 AA"} standard`,mapToPayload:(o,e)=>({url:o.url,standard:o.standard||"wcag21-aa",includeScreenReader:o.includeScreenReader||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",passed:e.passed||!1,score:e.score||0,violations:e.violations||[],warnings:e.warnings||[],duration:t,savedFiles:n})},Gs={domain:"chaos-resilience",taskType:"run-chaos",priority:"p2",defaultTimeout:9e4,buildTaskDescription:o=>`Run chaos test with ${o.faultType||"latency"} fault injection on ${o.target}`,mapToPayload:(o,e)=>({faultType:o.faultType||"latency",target:o.target,duration:o.duration||3e4,intensity:o.intensity||50,dryRun:o.dryRun!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:o=>(o.duration||3e4)+6e4,mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",faultType:e.faultType||"latency",resilience:e.resilience||{recovered:!1,recoveryTime:0,dataLoss:!1},duration:t,savedFiles:n})},$s={domain:"defect-intelligence",taskType:"predict-defects",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Predict defects in ${o.target||"codebase"} with ${o.lookback||30} day lookback`,mapToPayload:(o,e)=>({target:o.target||".",lookback:o.lookback||30,minConfidence:o.minConfidence||.7,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",predictedDefects:e.predictedDefects||[],riskScore:e.riskScore||0,recommendations:e.recommendations||[],duration:t,savedFiles:n})},zs={domain:"requirements-validation",taskType:"validate-requirements",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Validate requirements${o.generateBDD?" and generate BDD scenarios":""}`,mapToPayload:(o,e)=>({requirementsPath:o.requirementsPath,testPath:o.testPath,generateBDD:o.generateBDD||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",requirementsAnalyzed:e.requirementsAnalyzed||0,testable:e.testable||0,coverage:e.coverage||0,bddScenarios:e.bddScenarios||[],duration:t,savedFiles:n})},js={domain:"code-intelligence",taskType:"index-code",priority:"p2",defaultTimeout:3e5,buildTaskDescription:o=>`Index code in ${o.target||"codebase"}${o.incremental?" incrementally":""}`,mapToPayload:(o,e)=>({target:o.target||".",incremental:o.incremental||!1,gitSince:o.gitSince,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",filesIndexed:e.filesIndexed||0,symbolsExtracted:e.symbolsExtracted||0,relationsFound:e.relationsFound||0,duration:t,savedFiles:n})};function vc(o){let e=[],t=o.split(`
434
- `);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 a=r.match(/assert\w*\((.+)\)/);if(a){e.push(a[0]);continue}let s=r.match(/(?:it|test)\s*\(\s*['"`](.+?)['"`]/);s&&e.push(s[1])}return e.length>0?e:["test generated from source analysis"]}function Bs(){xs()}var ah=K(Is),oh=K(_s),ch=K(Os),lh=K(Fs),uh=K(Ls),dh=K(Ns),mh=K(qs),ph=K(Gs),gh=K($s),hh=K(zs),fh=K(js);k();var Jt=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:bc,streaming:!0,timeout:12e4};testGeneratorService=null;async getService(e){if(!this.testGeneratorService){let t=await F(),n=await z(e);this.testGeneratorService=ti({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:a="typescript",coverageTarget:s=80,patterns:c=[],aiEnhancement:l=!0,detectAntiPatterns:u=!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(Fn.isEnabled()){let v=`Generate ${r} tests for ${n.length} files using ${i}`,f=await Fn.checkTaskEarlyExit(v,"test-generation");f.canExit&&f.reusedPattern&&(this.emitStream(t,{status:"pattern-reuse",message:`Reusing pattern: ${f.reusedPattern.name}`,tokensSaved:f.estimatedTokensSaved}),console.log(`[TestGenerateTool] Early exit: reusing pattern ${f.reusedPattern.name}, saving ~${f.estimatedTokensSaved} tokens`))}let d=await this.getService(t),m={sourceFiles:n,testType:r,framework:i,coverageTarget:s,patterns:c},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 y=u?Cc(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:Ec(h,l),antiPatterns:y.length>0?y:void 0}}}catch(d){return{success:!1,error:`Test generation failed: ${S(d)}`}}}resetInstanceCache(){this.testGeneratorService=null}},bc={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 Cc(o){let e=[],t=fa("fs");for(let n of o)try{let r;try{r=t.readFileSync(n,"utf-8")}catch{continue}let i=r.split(`
435
- `),a=/(?<![\w.])(\d{2,}|[2-9]\d*)(?![\w.])/g,s=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 y=g.match(a);if(y)for(let v of y){if(s.has(v))continue;let f=g.substring(0,g.indexOf(v)),C=(f.match(/'/g)||[]).length,b=(f.match(/"/g)||[]).length,E=(f.match(/`/g)||[]).length;if(!(C%2===1||b%2===1||E%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 c=/(?:it|test)\s*\(\s*['"`]([^'"`]+)['"`]\s*,/g,l;for(;(l=c.exec(r))!==null;){let g=l.index,h=l[1],y=r.substring(g),v=Tc(y);if(v){let f=/expect\s*\(/.test(v),C=/assert[\.\(]/.test(v),b=/\.should[\.\(]/.test(v),E=/\.toBe|\.toEqual|\.toMatch|\.toThrow|\.toContain/.test(v);if(!f&&!C&&!b&&!E){let w=r.substring(0,g).split(`
436
- `).length;e.push({name:"no-assertions",location:`${n}:${w}`,severity:"high",suggestion:`Test "${h}" has no assertions. Add expect() or assert() calls to verify behavior`})}}}let u=[{pattern:/let\s+\w+\s*=\s*(?!undefined|null)/g,name:"mutable-let-declaration"},{pattern:/(?:^|\s)var\s+\w+\s*=/g,name:"mutable-var-declaration"}],d=r.match(/describe\s*\([^)]+,\s*(?:function\s*\(\)|(?:\(\s*\))?\s*=>)\s*\{/g);if(d)for(let g of d){let h=r.indexOf(g),y=Sc(r.substring(h));if(y){let v=y.match(/^\s*let\s+(\w+)\s*(?::\s*\w+)?\s*(?:=|;)/m);if(v){let f=v[1];if((y.match(new RegExp(`(?:it|test)\\s*\\([^)]+,[^]*?${f}\\s*=`,"g"))||[]).length>=2){let b=r.substring(0,h+y.indexOf(v[0])).split(`
431
+ `).run(t)}catch(t){console.warn("[CoverageLearner] Retention cleanup failed:",S(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,a=n.functions-t.functions;return r*.4+i*.35+a*.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()}-${gc().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(s=>s.addressed).length,a=e.gapsTargeted.length;return`${r} for ${this.extractFilePattern(e.targetPath)} files. Achieved ${t.toFixed(1)}% improvement. Addressed ${i}/${a} 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(s=>t.includes(s.split("/").pop()||"")||s.includes(t.split("/").pop()||""))||i.filePatterns.length===0){let s=(Date.now()-i.lastUsedAt.getTime())/864e5,c=Math.max(.5,1-s/30),l=i.avgImprovement*i.confidence*c;l>r&&(r=l,n=i)}return n}getAllStrategies(){return Array.from(this.strategies.values())}getStrategiesByTechnique(e){return this.getAllStrategies().filter(t=>t.technique===e)}getSessionStats(){let e=this.sessionStore.getAll();if(e.length===0)return{totalSessions:0,successfulSessions:0,avgImprovement:0,byTechnique:new Map,strategiesLearned:0};let t=e.map(s=>this.calculateOverallImprovement(s)),n=t.filter(s=>s>=this.config.minCoverageImprovementToLearn).length,r=t.reduce((s,c)=>s+c,0)/t.length,i=new Map,a=new Map;for(let s of e){let c=a.get(s.technique)||[];c.push(s),a.set(s.technique,c)}for(let[s,c]of a){let l=c.map(u=>this.calculateOverallImprovement(u));i.set(s,{count:c.length,avgImprovement:l.reduce((u,d)=>u+d,0)/l.length})}return{totalSessions:e.length,successfulSessions:n,avgImprovement:r,byTechnique:i,strategiesLearned:this.strategies.size}}analyzeGapResolution(){let t=this.sessionStore.getAll().flatMap(i=>i.gapsTargeted);if(t.length===0)return{totalGapsTargeted:0,gapsAddressed:0,resolutionRate:0,byGapType:new Map};let n=t.filter(i=>i.addressed).length,r=new Map;for(let i of t){let a=r.get(i.type)||{targeted:0,addressed:0};a.targeted++,i.addressed&&a.addressed++,r.set(i.type,a)}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 ws(o){return new yr(o)}var vr=class{weights;historicalScores=[];maxHistory;constructor(e={},t=100){this.weights={...mr,...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((a,s)=>a+s,0)/e.length,r=t.reduce((a,s)=>a+s,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 a of e){let s=this.calculateDimensions(a);t.effectiveness+=s.effectiveness,t.coverage+=s.coverage,t.mutationKill+=s.mutationKill,t.stability+=s.stability,t.maintainability+=s.maintainability,t.performance+=s.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 Rs(o,e){return new vr(o,e)}var br=class{criteria;promotionHistory=[];demotionHistory=[];reasoningBank=null;config;constructor(e={}){this.config={...ge,...e},this.criteria={...pr}}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 a={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(a),a}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 a={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(a),a}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 a of this.promotionHistory)e[a.toTier]++;let t={"short-term":0,working:0,"long-term":0,permanent:0};for(let a of this.demotionHistory)t[a.toTier]++;let n=Date.now()-10080*60*1e3,r=this.promotionHistory.filter(a=>a.timestamp.getTime()>n).length,i=this.demotionHistory.filter(a=>a.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 Ps(o){return new br(o)}var Cr=class{outcomeTracker;coverageLearner;qualityCalculator;promotionManager;routingFeedback;reasoningBank=null;config;constructor(e={}){this.config={...ge,...e},this.outcomeTracker=Es(this.config),this.coverageLearner=ws(this.config),this.qualityCalculator=Rs(this.config.qualityWeights),this.promotionManager=Ps(this.config),this.routingFeedback=li(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,a=this.outcomeTracker.getPatternMetrics(e.patternId);if(a){let s=await this.promotionManager.processPatternChange(i,{patternId:e.patternId,successCount:a.successCount,failureCount:a.failureCount,successRate:a.successRate,qualityScore:a.avgQuality,ageDays:this.calculateAgeDays(i.createdAt),recentSuccessRate:this.calculateRecentSuccessRate(e.patternId),recentFailureCount:this.calculateRecentFailures(e.patternId)});n={action:s.action,tier:s.event&&"toTier"in s.event?s.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(),a=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:a.totalOutcomes,recommendationFollowRate:1-a.overrideRate,successRateWhenFollowed:a.recommendationSuccessRate,successRateWhenOverridden:a.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 xs(o){let e=new Cr(o);return await e.initialize(),As=e,e}var As=null;function ks(){return As}function Oe(){return`test-${_e()}`}function Is(o){return`${o}-${_e()}`}function Zt(o){return{enabled:!0,agentId:Is(o),message:"Experience captured asynchronously via learning pipeline"}}async function hc(o,e,t,n,r){let i=Is(o);try{let{kernel:a}=tt();if(!a)return{enabled:!1,agentId:i,message:"Learning engine not available - kernel not initialized"};let s=await yc();if(!s)return{enabled:!1,agentId:i,message:"Learning engine not available"};let c=s.getExperienceCaptureService();if(!c)return{enabled:!1,agentId:i,message:"Experience capture service not available"};let l=fc(e),u=c.startCapture(`${e}: ${JSON.stringify(t).slice(0,200)}`,{agent:o,domain:l||void 0,metadata:{tool:e,durationMs:r}});c.recordStep(u,{action:`execute-${e}`,result:typeof n=="object"?JSON.stringify(n).slice(0,500):String(n).slice(0,500),quality:.7});let d=await c.completeCapture(u,{success:!0,quality:.7});if(d.success){let m=d.value;return{enabled:!0,agentId:i,message:`Experience captured: ${m.id} (domain: ${l||"general"}, quality: ${m.quality})`,experienceId:m.id,domain:l||"general"}}return{enabled:!0,agentId:i,message:"Experience capture completed (no pattern extracted)"}}catch(a){return{enabled:!1,agentId:i,message:`Learning capture failed: ${S(a)}`}}}function fc(o){return{test_generate_enhanced:"test-generation",test_execute_parallel:"test-execution",coverage_analyze_sublinear:"coverage-analysis",quality_assess:"quality-assessment",security_scan_comprehensive:"security-compliance",contract_validate:"contract-testing",accessibility_test:"visual-accessibility",chaos_test:"chaos-resilience",defect_predict:"defect-intelligence",requirements_validate:"requirements-validation",code_index:"code-intelligence"}[o]||null}async function yc(){return Ls()}async function vc(o,e,t,n){let r=ks();if(!r&&Tr&&(r=await Tr),!!r){if(o==="test-generation"&&e){let i=e.tests||e.generatedTests||[];for(let a of i.slice(0,20)){let s={id:String(a.id||_e()),testId:String(a.id||a.name||_e()),testName:String(a.name||a.testName||"generated-test"),generatedBy:"qe-test-generation",patternId:a.patternId,framework:a.framework||n.framework||"vitest",language:a.language||n.language||"typescript",domain:"test-generation",passed:a.passed!==!1,coverage:{lines:Number(a.coverageLines||0),branches:Number(a.coverageBranches||0),functions:Number(a.coverageFunctions||0)},executionTimeMs:Number(a.executionTimeMs||t/Math.max(i.length,1)),flaky:!!a.flaky,maintainabilityScore:Number(a.qualityScore||a.maintainability||.7),timestamp:new Date};await r.recordTestOutcome(s)}}if(o==="coverage-analysis"&&e){let i={id:_e(),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((a,s)=>({id:String(a.id||`gap-${_e().slice(0,8)}-${s}`),type:["uncovered-line","uncovered-branch","uncovered-function","partial-branch"].includes(String(a.type))?String(a.type):"uncovered-line",filePath:String(a.file||a.filePath||""),startLine:Number(a.line||a.startLine||0),endLine:a.endLine?Number(a.endLine):void 0,riskScore:Number(a.riskScore||.5),addressed:!!a.addressed})),durationMs:t,startedAt:new Date(Date.now()-t),completedAt:new Date};await r.recordCoverageSession(i)}}}function Ds(o){let e=o.split(`
432
+ `).length,t=(o.match(/if|switch|for|while|catch/g)||[]).length;return{score:e+t*2,level:t>5?"high":t>2?"medium":"low"}}function _s(o,e){let t=[];return o.level==="high"&&(t.push("Consider refactoring complex functions"),t.push("Add unit tests for each branch")),t.push("Consider adding edge case tests"),t.push("Add error handling tests"),e==="integration"&&(t.push("Add mock external dependencies"),t.push("Test API contract boundaries")),{recommendations:t,estimatedTime:`${Math.round(o.score*.5)} minutes`,confidence:.85}}function Os(o,e,t,n){let r=[],i=/(?:function\s+(\w+)|const\s+(\w+)\s*=|def\s+(\w+)|func\s+(\w+))/g,a=[],s;for(;(s=i.exec(o))!==null;){let l=s[1]||s[2]||s[3]||s[4];l&&a.push(l)}for(let l=0;l<Math.min(a.length,n);l++){let u=a[l]||"exampleFunction";r.push({id:Oe(),name:`test_${u}_${l}`,type:e,parameters:[],assertions:[`${u}() === null`],expectedResult:null,estimatedDuration:e==="integration"?2e3:1e3,aiGenerated:!0})}(e==="integration"||n>a.length)&&r.push({id:Oe(),name:`integration_ComponentA_${r.length}`,type:"integration",parameters:[],assertions:["ComponentA integration test passes"],expectedResult:null,estimatedDuration:2e3,aiGenerated:!0});let c=["high-complexity","deep-nesting","null-handling","empty-input"];for(let l=r.length;l<n&&l-r.length<c.length;l++)r.push({id:Oe(),name:`edge_case_${c[l-r.length]}_${l}`,type:"unit",parameters:[],assertions:[`${c[l-r.length]} edge case handled`],expectedResult:null,estimatedDuration:1500,aiGenerated:!0});return r}function Ns(o,e){let t=[],n=o.split(`
433
+ `);return o.includes("eval(")&&t.push({type:"dangerous-eval",line:n.findIndex(r=>r.includes("eval("))+1,severity:"critical",suggestion:"Replace eval() with safer alternatives"}),o.includes("var ")&&(e==="javascript"||e==="typescript")&&t.push({type:"var-usage",line:n.findIndex(r=>r.includes("var "))+1,severity:"low",suggestion:"Use const or let instead of var"}),o.includes("any")&&e==="typescript"&&t.push({type:"any-type",line:n.findIndex(r=>r.includes("any"))+1,severity:"medium",suggestion:"Replace any with specific types"}),t}var et=null,Tr=null,ce=null,bc=Number(process.env.AQE_ROUTE_TIMEOUT_MS)||5e3;function Cc(o,e,t){return new Promise(n=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(t))},e);typeof i.unref=="function"&&i.unref(),o.then(a=>{r||(r=!0,clearTimeout(i),n(a))},()=>{r||(r=!0,clearTimeout(i),n(t))})})}function Tc(){if(!et){let{kernel:o}=tt();if(!o)throw new Error("Kernel not initialized");et=Ts(o);let e=et;Tr=xs().then(t=>(e.setQualityFeedbackLoop(t),t)).catch(t=>(console.warn("[HandlerFactory] Failed to initialize QualityFeedbackLoop:",t),null))}return et}function Fs(){if(et=null,ce){let o=ce;ce=null,o.dispose().catch(()=>{})}}async function Ls(){if(ce)return ce;try{let{kernel:o}=tt();if(!o)return null;let{createAQELearningEngine:e}=await import("./aqe-learning-engine-FGT474XB.js"),t=o.memory,n=e(t,{projectRoot:process.cwd(),enableClaudeFlow:!1});return await n.initialize(),ce=n,ce}catch(o){return console.debug("[HandlerFactory] Learning engine init failed:",S(o)),null}}async function Sc(o,e){try{let t=await Ls();if(!t)return[];let n=e,r=await t.searchPatterns(o,{limit:5,minConfidence:.4,domain:n,useVectorSearch:!0});return!r.success||r.value.length===0?[]:r.value.filter(i=>i.similarity>=.4).map(i=>({name:i.pattern.name,description:i.pattern.description,similarity:i.similarity,confidence:i.pattern.confidence,canReuse:i.canReuse,patternId:i.pattern.id}))}catch(t){return console.debug("[HandlerFactory] Pattern search failed:",S(t)),[]}}async function Ec(o,e,t){try{let n=await Sc(o,e);return n.length>0&&console.debug(`[HandlerFactory] Found ${n.length} relevant patterns for ${e}`),await(await Qt()).routeTask({task:o,domain:e,codeContext:t,agentType:`qe-${e}`,enablePatternSearch:!0,patternHints:n.length>0?n:void 0})}catch(n){return console.error(`[HandlerFactory] Routing failed for ${e}: ${n}`),null}}async function Ms(o,e,t,n){if(!(!o||o.length===0)&&ce)try{for(let r of o)r.patternId&&await ce.recordOutcome({patternId:r.patternId,success:e,metrics:{executionTimeMs:n},feedback:`Domain handler ${t} execution ${e?"succeeded":"failed"}`})}catch{}}function K(o){let{domain:e,taskType:t,priority:n="p1",defaultTimeout:r=18e4,buildTaskDescription:i,mapToPayload:a,mapToResult:s,calculateTimeout:c,includeCodeContext:l}=o;return async u=>{if(!Ne())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{queen:d}=tt(),m=null;try{let p=i(u),g=l?.(u);m=await Cc(Ec(p,e,g),bc,null);let h=a(u,m),y=c?.(u)??r,v=await d.submitTask({type:t,priority:n,targetDomains:[e],payload:h,timeout:y});if(!v.success)return{success:!1,error:v.error.message};let f=Tc(),C=d.getTaskStatus(v.value);if(!C)return{success:!1,error:"Task not found after submission"};let b=await f.execute(C.task);if(!b.success)return{success:!1,error:b.error||"Task execution failed"};let E=b.data,w=s(v.value,E,b.duration,b.savedFiles,u);Ms(m?.patternHints,!0,e,b.duration),hc(`qe-${e}`,t,u,E,b.duration).catch(()=>{});try{await vc(e,E,b.duration,u)}catch{}return{success:!0,data:w}}catch(p){let g=S(p);return Ms(m?.patternHints,!1,e,0),{success:!1,error:`Failed to ${t.replace(/-/g," ")}: ${g}`}}}}var en=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(s=>s.success).length/this.taskMetrics.length,r=this.taskMetrics.reduce((s,c)=>s+c.retries,0)/this.taskMetrics.length,i=Math.min(.2,r*.1),a=t*(1-i);return Math.min(1,Math.max(0,a))}getLoadBalanceScore(){if(this.workerLoads.size===0)return .9;let e=Array.from(this.workerLoads.values()).map(s=>s.completedTaskCount);if(e.length<=1)return 1;let t=e.reduce((s,c)=>s+c,0)/e.length;if(t===0)return 1;let n=e.reduce((s,c)=>s+Math.pow(c-t,2),0)/e.length,a=1/(1+Math.sqrt(n)/t);return Math.min(1,Math.max(0,a))}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()}},ye=new en;Ia();var Sr="^(?:UNKNOWN|[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,255})$",Er="(?:^|[._:/@+\\-])(?:(?:[sS][kK]|[rR][kK]|[gG][hH][pPoOuUsSrR]|[gG][iI][tT][hH][uU][bB]_[pP][aA][tT]|[xX][oO][xX][bBaApPrRsS]|[nN][pP][mM]|[gG][lL][pP][aA][tT]|[pP][aA][tT])(?:[-_][A-Za-z0-9_-]*|(?=$|[.:/@+\\-]))|(?:[aA][kK][iI][aA]|[aA][sS][iI][aA]|[aA][iI][zZ][aA])[A-Za-z0-9]*)",wr="(?:^|[^A-Za-z0-9_-])(?:eyJ[A-Za-z0-9_-]*|e30|ew[A-Za-z0-9_-]*)\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+(?:$|[^A-Za-z0-9_-])",Rr="(?:^|[._:/@+\\-])[A-Za-z0-9]{32,}(?:$|[._:/@+\\-])",Pr="(?:(?:^|[.:@\\-])[A-Za-z0-9+/]{32,}={0,2}(?:$|[.:@\\-])|(?:^|[.:/@+\\-])[A-Za-z0-9_-]{48,}(?:$|[.:/@+\\-]))",xr="^\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d{1,9})?Z$",Yg=new RegExp(Sr),Jg=new RegExp(Er),Zg=new RegExp(wr),eh=new RegExp(Rr),th=new RegExp(Pr),nh=new RegExp(xr);function wc(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function Rc(o){return Array.isArray(o)&&o.every(e=>typeof e=="string")}function Pc(o){return typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1}function Gs(o){let e=[];return wc(o)?(o.contract!=="risk-decision@1"&&e.push('contract must be "risk-decision@1"'),["approve","block","escalate"].includes(o.decision)||e.push("decision must be approve|block|escalate"),Rc(o.riskFactors)||e.push("riskFactors must be string[]"),Pc(o.confidence)||e.push("confidence must be a number in [0,1]"),(typeof o.rationale!="string"||o.rationale.length===0)&&e.push("rationale must be a non-empty string"),{valid:e.length===0,errors:e}):{valid:!1,errors:["not an object"]}}function $s(o){let{passed:e,qualityScore:t,recommendations:n=[]}=o,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 xc={type:"number",minimum:0,maximum:1},qs={type:"array",items:{type:"string"}};function Fe(o){return{type:"string",pattern:Sr,allOf:[{not:{pattern:Er}},{not:{pattern:wr}},{not:{pattern:o==="provider"||o==="requestedModel"||o==="resolvedModel"?Rr:Pr}}]}}var Le={type:"string",pattern:"^(?:UNKNOWN|sha256:[a-f0-9]{64})$"},X={type:"string",pattern:"^sha256:[a-f0-9]{64}$"};var oh={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://agentic-qe.dev/schemas/finding-verdict.schema.json",title:"FindingVerdict",type:"object",required:["contract","id","title","severity","confidence","evidence","verdict","refutations"],additionalProperties:!0,properties:{contract:{const:"finding-verdict@1"},id:{type:"string",minLength:1},title:{type:"string",minLength:1},file:{type:"string"},severity:{enum:["critical","high","medium","low","info"]},confidence:xc,evidence:qs,verdict:{enum:["upheld","refuted","uncertain"]},refutations:qs,measurementReceipts:{type:"array",items:{type:"object",required:["contract","provider","requestedModel","resolvedModel","endpointClass","snapshotIdentity","semantics","fingerprint","requestHash","promptHash","configHash","parserSchemaHash","outputHash","parsedVoteHash","temperature","topP","seed","deterministic","cacheStatus","retryCount","timestamp","windowId","latencyMs","requestId"],additionalProperties:!1,properties:{contract:{const:"judge-measurement@1"},provider:Fe("provider"),requestedModel:Fe("requestedModel"),resolvedModel:Fe("resolvedModel"),endpointClass:{enum:["shared","dedicated","local","UNKNOWN"]},snapshotIdentity:{enum:["L0_UNKNOWN","L1_NAMED","L2_CONTENT_BOUND"]},semantics:{enum:["verified","provider-asserted","UNKNOWN"]},fingerprint:Fe("fingerprint"),requestHash:Le,promptHash:Le,configHash:Le,parserSchemaHash:Le,outputHash:Le,parsedVoteHash:Le,temperature:{type:["number","null"],minimum:0},topP:{type:["number","null"],minimum:0,maximum:1},seed:{type:["integer","null"],minimum:Number.MIN_SAFE_INTEGER,maximum:Number.MAX_SAFE_INTEGER},deterministic:{type:["boolean","null"]},cacheStatus:{enum:["hit","miss","bypass","UNKNOWN"]},retryCount:{type:"integer",minimum:0,maximum:Number.MAX_SAFE_INTEGER},timestamp:{anyOf:[{const:"UNKNOWN"},{type:"string",pattern:xr,format:"date-time"}]},windowId:Fe("windowId"),latencyMs:{type:["number","null"],minimum:0},requestId:Fe("requestId")},allOf:[{if:{properties:{snapshotIdentity:{const:"L2_CONTENT_BOUND"}}},then:{properties:{fingerprint:{not:{const:"UNKNOWN"}},requestHash:X,promptHash:X,configHash:X,parserSchemaHash:X,outputHash:X,parsedVoteHash:X}}},{if:{properties:{snapshotIdentity:{const:"L1_NAMED"}}},then:{properties:{resolvedModel:{not:{const:"UNKNOWN"}}}}},{if:{properties:{semantics:{const:"verified"}}},then:{properties:{snapshotIdentity:{const:"L2_CONTENT_BOUND"},fingerprint:{not:{const:"UNKNOWN"}},requestHash:X,promptHash:X,configHash:X,parserSchemaHash:X,outputHash:X,parsedVoteHash:X}}},{if:{properties:{semantics:{enum:["verified","provider-asserted"]}}},then:{properties:{snapshotIdentity:{not:{const:"L0_UNKNOWN"}},fingerprint:{not:{const:"UNKNOWN"}}}}}]}}}};var zs=Object.keys(xt);function Ac(o){if(!o)return"typescript";let e=o.toLowerCase().trim(),t={ts:"typescript",js:"javascript",py:"python","c#":"csharp","c-sharp":"csharp",cs:"csharp",golang:"go",rs:"rust",kt:"kotlin"};return t[e]?t[e]:zs.includes(e)?e:null}var js={domain:"test-generation",taskType:"generate-tests",priority:"p1",defaultTimeout:12e4,buildTaskDescription:o=>`Generate ${o.testType||"unit"} tests for ${o.language||"typescript"} code`,includeCodeContext:o=>o.sourceCode,mapToPayload:(o,e)=>{let t=Ac(o.language);if(t===null)throw new Error(`Unsupported language '${o.language}'. Supported languages: ${zs.join(", ")}. Open a feature request for additional language support.`);let n;if(o.framework){n=o.framework;let r=ui[n];if(r&&r!==t){let i=a=>a==="javascript"||a==="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 (${xt[t]}).`)}}else n=xt[t];return{sourceCode:o.sourceCode,filePath:o.filePath,language:t,framework:n,testType:o.testType||"unit",coverageGoal:o.coverageGoal||80,aiEnhancement:o.aiEnhancement!==!1,detectAntiPatterns:o.detectAntiPatterns||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}},mapToResult:(o,e,t,n,r)=>{let i=r?.sourceCode||"",a=r?.language||"typescript",s=r?.testType||"unit",c=e.testsGenerated||6,l=Ds(i),u=r?.aiEnhancement!==!1?_s(l,s):{recommendations:[],estimatedTime:"0 minutes",confidence:0},d=r?.detectAntiPatterns?Ns(i,a):[],m=Zt("test-generator"),p=e.tests,g=Array.isArray(p)&&p.length>0&&p[0].testCode,h=e.llmEnhanced===!0,y=g?p.map((v,f)=>({id:Oe(),name:v.name||`test_${f}`,type:v.type||s,parameters:[],assertions:v.testCode?kc(v.testCode):[`test assertion ${f}`],expectedResult:null,estimatedDuration:v.type==="integration"?2e3:1e3,aiGenerated:h,testCode:v.testCode,sourceFile:v.sourceFile,testFile:v.testFile||v.file})):Os(i,s,a,c);return{tests:y,antiPatterns:d,suggestions:d.map(v=>`Fix: ${v.type} - ${v.suggestion}`),aiInsights:u,coverage:{predicted:e.coverageEstimate||r?.coverageGoal||80,confidence:h?.9:.3,achievable:!0},properties:y.filter(v=>v.type==="property").map(v=>({name:v.name,invariant:"output_matches_expectation"})),language:a,complexity:l,learning:m,taskId:o,status:"completed",testsGenerated:y.length,coverageEstimate:e.coverageEstimate||r?.coverageGoal||80,patternsUsed:e.patternsUsed||["assertion-patterns","mock-generation","edge-case-detection"],duration:t,savedFiles:n,llmEnhanced:h,...e.generationMode?{generationMode:e.generationMode}:{},...e.note?{note:e.note}:{}}}},Bs={domain:"test-execution",taskType:"execute-tests",priority:"p1",defaultTimeout:3e5,buildTaskDescription:o=>`Execute ${o.testFiles?.length||0} test files with ${o.parallel!==!1?"parallel":"sequential"} execution`,mapToPayload:(o,e)=>({testFiles:o.testFiles||[],testSuites:o.testSuites||[],parallel:o.parallel!==!1,parallelism:o.parallelism||4,retryCount:o.retryCount||3,timeout:o.timeout||6e4,collectCoverage:o.collectCoverage||!1,reportFormat:o.reportFormat||"json",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:o=>o.timeout||3e5,mapToResult:(o,e,t,n,r)=>{let i=e.total||0,a=e.passed||0,s=e.failed||0,c=e.coverage,l=r?.parallelism||4,u=ye.getRetryStats(),d=ye.getWorkersUsed(),m={workersUsed:d>0?d:Math.min(l,i||1),efficiency:ye.getWorkerEfficiency(),loadBalance:ye.getLoadBalanceScore(),avgExecutionTime:t/Math.max(i,1)},p={totalRetries:u.totalRetries,successfulRetries:u.successfulRetries,maxRetriesReached:u.maxRetriesReached},g=Zt("test-executor");return{workerStats:m,retryStats:p,results:(()=>{let h=ye.getTestDurations(i);return Array.from({length:i},(y,v)=>({id:Oe(),name:`test_case_${v}`,status:v<a?"passed":"failed",duration:h[v]||200,retries:0}))})(),summary:{totalTests:i,passRate:i>0?a/i*100:0,avgDuration:t/Math.max(i,1),parallelEfficiency:m.efficiency},learning:g,taskId:o,status:"completed",total:i,passed:a,failed:s,duration:t,coverage:c,savedFiles:n}}},Us={domain:"coverage-analysis",taskType:"analyze-coverage",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Analyze coverage for ${o.target||"project"} with gap detection`,mapToPayload:(o,e)=>({target:o.target||".",includeRisk:o.includeRisk||!1,detectGaps:o.detectGaps!==!1,mlPowered:o.mlPowered||!1,prioritization:o.prioritization||"complexity",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>{let r=e.summary,i=r?.files??e.totalFiles??0,a=e.gaps||[],s=e.branchDataCollected===!0,c=e.functionDataCollected===!0,l=s?r?.branch??e.branchCoverage??null:null,u=c?r?.function??e.functionCoverage??null:null,d=e.estimated===!0,m=e.measured===!0,g=r?.line??e.lineCoverage??null,y=r?.statement??e.statementCoverage??g,v=Zt("coverage-analyzer"),f=a.map((E,w)=>{let T=E;return T?.file?{id:`gap-${Date.now()}-${w}`,file:T.file,line:T.lines?.[0]||0,uncoveredLines:T.lines||[],type:T.type||"uncovered-line",severity:T.severity||"medium",reason:T.reason||"Missing test case",priority:T.priority||"medium",suggestion:T.suggestedTest||"Add test coverage",suggestedTest:T.suggestedTest||"Add test coverage",riskScore:T.riskScore||.5,confidence:T.confidence??(m?.7:.2),estimated:T.estimated===!0||d}:null}).filter(E=>E!==null),C=e.coverageByFile;return{coverageByFile:C?C.map(E=>({file:E.file,lineCoverage:E.lineCoverage||0,branchCoverage:E.branchCoverage??null,functionCoverage:E.functionCoverage??null})):[],gapAnalysis:{totalGaps:f.length,highPriority:f.filter(E=>E.priority==="high").length,gaps:f},trends:{lineCoverageTrend:i>0?"stable":"no-data",branchCoverageTrend:i>0?"stable":"no-data",weeklyChange:0},aiInsights:i>0?{recommendations:d?["ESTIMATED RESULT \u2014 no instrumentation ran. The figures below are a static guess from source shape, not measured coverage. Do not act on individual gaps without running real instrumentation first.",...e.recommendations||[]]:e.recommendations||["Run tests with coverage enabled to get accurate metrics"],riskAssessment:d||!m||g===null?"unknown":g<70?"high":g<85?"medium":"low",confidence:d?.2:m?.88:0}:{recommendations:["No coverage data found. Run tests with coverage first (e.g., npm test -- --coverage, or pytest --cov)"],riskAssessment:"unknown",confidence:0},learning:v,taskId:o,status:"completed",lineCoverage:g,branchCoverage:l,functionCoverage:u,statementCoverage:y,totalFiles:i,gaps:f,duration:t,savedFiles:n,estimated:d,measured:m,coverageMethod:e.coverageMethod??"unknown",branchDataCollected:s,functionDataCollected:c,...e.warning?{warning:e.warning}:{}}}},Hs={domain:"quality-assessment",taskType:"assess-quality",priority:"p0",defaultTimeout:18e4,buildTaskDescription:o=>`Assess quality with ${o.runGate?"quality gate":"metrics analysis"}`,mapToPayload:(o,e)=>({runGate:o.runGate||!1,threshold:o.threshold||80,metrics:o.metrics||["coverage","complexity","maintainability"],routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>{let r=$s({passed:typeof e.passed=="boolean"?e.passed:void 0,qualityScore:e.qualityScore,recommendations:e.recommendations||[]});return{taskId:o,status:"completed",qualityScore:e.qualityScore||0,passed:e.passed||!1,metrics:e.metrics||{},recommendations:e.recommendations||[],duration:t,savedFiles:n,...Gs(r).valid?{riskDecision:r}:{}}}},Vs={domain:"security-compliance",taskType:"scan-security",priority:"p0",defaultTimeout:6e5,buildTaskDescription:o=>{let e=[];return o.sast!==!1&&e.push("SAST"),o.dast&&e.push("DAST"),`Security scan (${e.join(", ")}) for ${o.target||"project"}`},mapToPayload:(o,e)=>({sast:o.sast!==!1,dast:o.dast||!1,compliance:o.compliance||[],target:o.target||".",routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,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})},Qs={domain:"contract-testing",taskType:"validate-contracts",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Validate API contract at ${o.contractPath}`,mapToPayload:(o,e)=>({contractPath:o.contractPath,providerUrl:o.providerUrl,consumerName:o.consumerName,checkBreakingChanges:o.checkBreakingChanges!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",valid:e.valid||!1,breakingChanges:e.breakingChanges||[],warnings:e.warnings||[],duration:t,savedFiles:n})},Ws={domain:"visual-accessibility",taskType:"test-accessibility",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Test accessibility for ${o.url} against ${o.standard||"WCAG 2.1 AA"} standard`,mapToPayload:(o,e)=>({url:o.url,standard:o.standard||"wcag21-aa",includeScreenReader:o.includeScreenReader||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",passed:e.passed||!1,score:e.score||0,violations:e.violations||[],warnings:e.warnings||[],duration:t,savedFiles:n})},Ks={domain:"chaos-resilience",taskType:"run-chaos",priority:"p2",defaultTimeout:9e4,buildTaskDescription:o=>`Run chaos test with ${o.faultType||"latency"} fault injection on ${o.target}`,mapToPayload:(o,e)=>({faultType:o.faultType||"latency",target:o.target,duration:o.duration||3e4,intensity:o.intensity||50,dryRun:o.dryRun!==!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),calculateTimeout:o=>(o.duration||3e4)+6e4,mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",faultType:e.faultType||"latency",resilience:e.resilience||{recovered:!1,recoveryTime:0,dataLoss:!1},duration:t,savedFiles:n})},Xs={domain:"defect-intelligence",taskType:"predict-defects",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Predict defects in ${o.target||"codebase"} with ${o.lookback||30} day lookback`,mapToPayload:(o,e)=>({target:o.target||".",lookback:o.lookback||30,minConfidence:o.minConfidence||.7,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",predictedDefects:e.predictedDefects||[],riskScore:e.riskScore||0,recommendations:e.recommendations||[],duration:t,savedFiles:n})},Ys={domain:"requirements-validation",taskType:"validate-requirements",priority:"p1",defaultTimeout:18e4,buildTaskDescription:o=>`Validate requirements${o.generateBDD?" and generate BDD scenarios":""}`,mapToPayload:(o,e)=>({requirementsPath:o.requirementsPath,testPath:o.testPath,generateBDD:o.generateBDD||!1,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",requirementsAnalyzed:e.requirementsAnalyzed||0,testable:e.testable||0,coverage:e.coverage||0,bddScenarios:e.bddScenarios||[],duration:t,savedFiles:n})},Js={domain:"code-intelligence",taskType:"index-code",priority:"p2",defaultTimeout:3e5,buildTaskDescription:o=>`Index code in ${o.target||"codebase"}${o.incremental?" incrementally":""}`,mapToPayload:(o,e)=>({target:o.target||".",incremental:o.incremental||!1,gitSince:o.gitSince,routingTier:e?.decision.tier,useAgentBooster:e?.useAgentBooster,compiledContext:e?.compiledContext}),mapToResult:(o,e,t,n)=>({taskId:o,status:"completed",filesIndexed:e.filesIndexed||0,symbolsExtracted:e.symbolsExtracted||0,relationsFound:e.relationsFound||0,duration:t,savedFiles:n})};function kc(o){let e=[],t=o.split(`
434
+ `);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 a=r.match(/assert\w*\((.+)\)/);if(a){e.push(a[0]);continue}let s=r.match(/(?:it|test)\s*\(\s*['"`](.+?)['"`]/);s&&e.push(s[1])}return e.length>0?e:["test generated from source analysis"]}function Zs(){Fs()}var Ih=K(js),Dh=K(Bs),_h=K(Us),Oh=K(Hs),Nh=K(Vs),Fh=K(Qs),Lh=K(Ws),qh=K(Ks),Gh=K(Xs),$h=K(Ys),zh=K(Js);k();var tn=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:Mc,streaming:!0,timeout:12e4};testGeneratorService=null;async getService(e){if(!this.testGeneratorService){let t=await N(),n=await z(e);this.testGeneratorService=di({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:a="typescript",coverageTarget:s=80,patterns:c=[],aiEnhancement:l=!0,detectAntiPatterns:u=!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(qn.isEnabled()){let v=`Generate ${r} tests for ${n.length} files using ${i}`,f=await qn.checkTaskEarlyExit(v,"test-generation");f.canExit&&f.reusedPattern&&(this.emitStream(t,{status:"pattern-reuse",message:`Reusing pattern: ${f.reusedPattern.name}`,tokensSaved:f.estimatedTokensSaved}),console.log(`[TestGenerateTool] Early exit: reusing pattern ${f.reusedPattern.name}, saving ~${f.estimatedTokensSaved} tokens`))}let d=await this.getService(t),m={sourceFiles:n,testType:r,framework:i,coverageTarget:s,patterns:c},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 y=u?Ic(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:Oc(h,l),antiPatterns:y.length>0?y:void 0}}}catch(d){return{success:!1,error:`Test generation failed: ${S(d)}`}}}resetInstanceCache(){this.testGeneratorService=null}},Mc={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 Ic(o){let e=[],t=Pa("fs");for(let n of o)try{let r;try{r=t.readFileSync(n,"utf-8")}catch{continue}let i=r.split(`
435
+ `),a=/(?<![\w.])(\d{2,}|[2-9]\d*)(?![\w.])/g,s=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 y=g.match(a);if(y)for(let v of y){if(s.has(v))continue;let f=g.substring(0,g.indexOf(v)),C=(f.match(/'/g)||[]).length,b=(f.match(/"/g)||[]).length,E=(f.match(/`/g)||[]).length;if(!(C%2===1||b%2===1||E%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 c=/(?:it|test)\s*\(\s*['"`]([^'"`]+)['"`]\s*,/g,l;for(;(l=c.exec(r))!==null;){let g=l.index,h=l[1],y=r.substring(g),v=Dc(y);if(v){let f=/expect\s*\(/.test(v),C=/assert[\.\(]/.test(v),b=/\.should[\.\(]/.test(v),E=/\.toBe|\.toEqual|\.toMatch|\.toThrow|\.toContain/.test(v);if(!f&&!C&&!b&&!E){let w=r.substring(0,g).split(`
436
+ `).length;e.push({name:"no-assertions",location:`${n}:${w}`,severity:"high",suggestion:`Test "${h}" has no assertions. Add expect() or assert() calls to verify behavior`})}}}let u=[{pattern:/let\s+\w+\s*=\s*(?!undefined|null)/g,name:"mutable-let-declaration"},{pattern:/(?:^|\s)var\s+\w+\s*=/g,name:"mutable-var-declaration"}],d=r.match(/describe\s*\([^)]+,\s*(?:function\s*\(\)|(?:\(\s*\))?\s*=>)\s*\{/g);if(d)for(let g of d){let h=r.indexOf(g),y=_c(r.substring(h));if(y){let v=y.match(/^\s*let\s+(\w+)\s*(?::\s*\w+)?\s*(?:=|;)/m);if(v){let f=v[1];if((y.match(new RegExp(`(?:it|test)\\s*\\([^)]+,[^]*?${f}\\s*=`,"g"))||[]).length>=2){let b=r.substring(0,h+y.indexOf(v[0])).split(`
437
437
  `).length;e.push({name:"test-interdependence",location:`${n}:${b}`,severity:"high",suggestion:`Shared mutable variable '${f}' 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(`
438
438
  `).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 y=r.substring(0,r.indexOf(h[0])).split(`
439
- `).length;e.push({name:"real-timers-in-tests",location:`${n}:${y}`,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 Tc(o){let e=0,t=-1,n=-1;for(let r=0;r<o.length;r++)if(o[r]==="{")t===-1&&(t=r),e++;else if(o[r]==="}"&&(e--,e===0&&t!==-1)){n=r;break}return t!==-1&&n!==-1?o.substring(t+1,n):null}function Sc(o){let e=0,t=-1,n=-1;for(let r=0;r<o.length;r++)if(o[r]==="{")t===-1&&(t=r),e++;else if(o[r]==="}"&&(e--,e===0&&t!==-1)){n=r;break}return t!==-1&&n!==-1?o.substring(t+1,n):null}function Ec(o,e){let t=[];return o.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();Qe();var Zt=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:wc,streaming:!0,timeout:3e5};async execute(e,t){let{testFiles:n=[],testSuites:r=[],pattern:i,parallel:a=!0,parallelism:s=4,retryCount:c=3,timeout:l=6e4,collectCoverage:u=!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:a,parallelism:s}),this.isAborted(t))return{success:!1,error:"Test execution aborted"};let h=[],y=[];for(let b=0;b<g.length;b++){let E=g[b];this.emitStream(t,{status:"running",message:`Executing ${E}`,progress:Math.round(b/g.length*100)});let w=te()>.1,T={id:`test-${b}`,name:`Test suite for ${E.split("/").pop()}`,file:E,status:w?"passed":"failed",duration:te()*5e3,error:w?void 0:"Assertion failed",retries:w?0:Math.min(c,2)};if(h.push(T),!w&&te()>.7&&y.push({name:T.name,file:T.file,flakinessScore:ne(.5,1),failurePattern:"intermittent-timeout"}),m&&!w)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 f=u?{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:f,flakyTests:y.length>0?y:void 0,duration:C}}}catch(g){return{success:!1,error:`Test execution failed: ${S(g)}`}}}},wc={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}}};Q();import*as X from"fs/promises";import*as M from"path";async function vr(o,e){let t=await X.readFile(o,"utf-8");return Xs(t,e||M.dirname(o))}function Xs(o,e){let t=new Map,n=o.split(`
440
- `),r=null,i=new Map,a=[],s=[],c=0,l=0,u=0,d=0,m=0,p=0;for(let g of n){let h=g.trim();if(h.startsWith("SF:")){let y=h.slice(3);r={path:y,relativePath:M.relative(e,y)},i=new Map,a=[],s=[],c=0,l=0,u=0,d=0,m=0,p=0}else if(h.startsWith("DA:")){let[y,v]=h.slice(3).split(",").map(Number);!isNaN(y)&&!isNaN(v)&&(i.set(y,v),c++,v>0&&l++)}else if(h.startsWith("LF:")){let y=parseInt(h.slice(3),10);isNaN(y)||(c=y)}else if(h.startsWith("LH:")){let y=parseInt(h.slice(3),10);isNaN(y)||(l=y)}else if(h.startsWith("BRDA:")){let y=h.slice(5).split(",");if(y.length>=4){let v=parseInt(y[0],10),f=parseInt(y[1],10),C=parseInt(y[2],10),b=y[3]==="-"?0:parseInt(y[3],10);a.push({line:v,block:f,branch:C,taken:b>0,hits:b}),u++,b>0&&d++}}else if(h.startsWith("BRF:")){let y=parseInt(h.slice(4),10);isNaN(y)||(u=y)}else if(h.startsWith("BRH:")){let y=parseInt(h.slice(4),10);isNaN(y)||(d=y)}else if(h.startsWith("FN:")){let y=h.indexOf(",",3);if(y>0){let v=parseInt(h.slice(3,y),10),f=h.slice(y+1);s.find(b=>b.name===f)||s.push({name:f,line:v,hits:0})}}else if(h.startsWith("FNDA:")){let y=h.indexOf(",",5);if(y>0){let v=parseInt(h.slice(5,y),10),f=h.slice(y+1),C=s.find(b=>b.name===f);C?C.hits=v:s.push({name:f,line:0,hits:v}),m++,v>0&&p++}}else if(h.startsWith("FNF:")){let y=parseInt(h.slice(4),10);isNaN(y)||(m=y)}else if(h.startsWith("FNH:")){let y=parseInt(h.slice(4),10);isNaN(y)||(p=y)}else if(h==="end_of_record"&&r?.path){let y=Array.from(i.entries()).filter(([,b])=>b===0).map(([b])=>b).sort((b,E)=>b-E),v=a.filter(b=>!b.taken),f=s.filter(b=>b.hits===0).map(b=>b.name),C={path:r.path,relativePath:r.relativePath||r.path,lines:{total:c,covered:l,percentage:c>0?l/c*100:0,details:i,uncoveredLines:y},branches:{total:u,covered:d,percentage:u>0?d/u*100:0,uncoveredBranches:v},functions:{total:m,covered:p,percentage:m>0?p/m*100:0,details:s,uncoveredFunctions:f},statements:{total:c,covered:l,percentage:c>0?l/c*100:0},coveragePercentage:Tr(l,c,d,u)};t.set(r.path,C),r=null}}return{timestamp:new Date,format:"lcov",files:t,summary:ye(t)}}async function br(o,e){let t=await X.readFile(o,"utf-8"),n=A(t),r=e||M.dirname(o),i=new Map;for(let[a,s]of Object.entries(n)){if(typeof s!="object"||!s.statementMap)continue;let c=new Map,l=[],u=0,d=0;for(let[b,E]of Object.entries(s.s||{})){let w=s.statementMap[b];if(w?.start?.line){let T=w.start.line,P=c.get(T)||0;c.set(T,P+E)}u++,E>0&&d++}for(let[b,E]of c.entries())E===0&&l.push(b);let m=[],p=0,g=0;for(let[b,E]of Object.entries(s.branchMap||{})){let w=s.b?.[b]||[];for(let T=0;T<w.length;T++)m.push({line:E.loc?.start?.line||0,block:parseInt(b,10),branch:T,taken:w[T]>0,hits:w[T]}),p++,w[T]>0&&g++}let h=[],y=0,v=0;for(let[b,E]of Object.entries(s.fnMap||{})){let w=s.f?.[b]||0;h.push({name:E.name||`anonymous_${b}`,line:E.loc?.start?.line||E.decl?.start?.line||0,hits:w}),y++,w>0&&v++}let f=c.size,C=Array.from(c.values()).filter(b=>b>0).length;i.set(a,{path:a,relativePath:M.relative(r,a),lines:{total:f,covered:C,percentage:f>0?C/f*100:0,details:c,uncoveredLines:l.sort((b,E)=>b-E)},branches:{total:p,covered:g,percentage:p>0?g/p*100:0,uncoveredBranches:m.filter(b=>!b.taken)},functions:{total:y,covered:v,percentage:y>0?v/y*100:0,details:h,uncoveredFunctions:h.filter(b=>b.hits===0).map(b=>b.name)},statements:{total:u,covered:d,percentage:u>0?d/u*100:0},coveragePercentage:Tr(C,f,g,p)})}return{timestamp:new Date,format:"json",files:i,summary:ye(i)}}async function Us(o,e){let t=await X.readFile(o,"utf-8");return en(t,e||M.dirname(o))}function en(o,e){let t=new Map,n=/<package\s+name="([^"]*)">([\s\S]*?)<\/package>/g,r;for(;(r=n.exec(o))!==null;){let i=r[1].replace(/\//g,M.sep),a=r[2],s=/<sourcefile\s+name="([^"]*)">([\s\S]*?)<\/sourcefile>/g,c;for(;(c=s.exec(a))!==null;){let l=c[1],u=c[2],d=M.join(e,i,l),m=Rc(u),p=new Map,g=/<line\s+nr="(\d+)"\s+mi="(\d+)"\s+ci="(\d+)"/g,h;for(;(h=g.exec(u))!==null;){let v=parseInt(h[1],10),f=parseInt(h[3],10);p.set(v,f)}let y=Array.from(p.entries()).filter(([,v])=>v===0).map(([v])=>v).sort((v,f)=>v-f);t.set(d,{path:d,relativePath:M.join(i,l),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:y},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:Tr(m.LINE.covered,m.LINE.total,m.BRANCH.covered,m.BRANCH.total)})}}return{timestamp:new Date,format:"jacoco",language:"java",files:t,summary:ye(t)}}function Rc(o){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(o))!==null;){let r=n[1],i=parseInt(n[2],10),a=parseInt(n[3],10);e[r]&&(e[r].covered+=a,e[r].total+=i+a)}return e}async function Hs(o,e){let t=await X.readFile(o,"utf-8");return Ys(t,e||M.dirname(o))}function Ys(o,e){let t=new Map,n=new Map,r=/<File\s+Index="(\d+)"\s+Name="([^"]*)"\s*\/>/g,i;for(;(i=r.exec(o))!==null;)n.set(i[1],i[2]);let a=/<Statement\s+FileIndex="(\d+)"\s+Line="(\d+)"\s+Column="\d+"\s+EndLine="\d+"\s+EndColumn="\d+"\s+Covered="(\w+)"\s*\/>/g,s=new Map,c;for(;(c=a.exec(o))!==null;){let l=c[1],u=parseInt(c[2],10),d=c[3]==="True",m=n.get(l)||`file-${l}`;s.has(m)||s.set(m,{lineDetails:new Map,total:0,covered:0});let p=s.get(m);p.lineDetails.set(u,d?1:0),p.total++,d&&p.covered++}if(s.size===0){let u=/CoveredStatements="(\d+)"\s+TotalStatements="(\d+)"/.exec(o);if(u){let d=parseInt(u[1],10),m=parseInt(u[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[l,u]of s.entries()){let d=Array.from(u.lineDetails.entries()).filter(([,m])=>m===0).map(([m])=>m).sort((m,p)=>m-p);t.set(l,{path:l,relativePath:M.relative(e,l),lines:{total:u.lineDetails.size,covered:Array.from(u.lineDetails.values()).filter(m=>m>0).length,percentage:u.lineDetails.size>0?Array.from(u.lineDetails.values()).filter(m=>m>0).length/u.lineDetails.size*100:0,details:u.lineDetails,uncoveredLines:d},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:u.total,covered:u.covered,percentage:u.total>0?u.covered/u.total*100:0},coveragePercentage:u.total>0?u.covered/u.total*100:0})}return{timestamp:new Date,format:"dotcover",language:"csharp",files:t,summary:ye(t)}}async function Vs(o,e){let t=await X.readFile(o,"utf-8"),n=e||M.dirname(o);if(t.includes("SF:")&&t.includes("end_of_record")){let r=Xs(t,n);return r.format="tarpaulin",r.language="rust",r}return Js(t,n)}function Js(o,e){let t=new Map,n=A(o);for(let r of n?.files||[]){let i=r.path||"",a=new Map,s=0,c=0;for(let u of r.traces||[]){let d=u.line,m=u.stats?.Line??u.stats?.line??0;typeof d=="number"&&(a.set(d,m),s++,m>0&&c++)}let l=Array.from(a.entries()).filter(([,u])=>u===0).map(([u])=>u).sort((u,d)=>u-d);t.set(i,{path:i,relativePath:M.relative(e,i),lines:{total:s,covered:c,percentage:s>0?c/s*100:0,details:a,uncoveredLines:l},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:s,covered:c,percentage:s>0?c/s*100:0},coveragePercentage:s>0?c/s*100:0})}return{timestamp:new Date,format:"tarpaulin",language:"rust",files:t,summary:ye(t)}}async function Qs(o,e){let t=await X.readFile(o,"utf-8");return Zs(t,e||M.dirname(o))}function Zs(o,e){let t=new Map,n=new Map,r=o.split(`
441
- `);for(let i of r){let a=i.trim();if(!a||a.startsWith("mode:"))continue;let s=a.match(/^(.+):(\d+)\.\d+,(\d+)\.\d+\s+(\d+)\s+(\d+)$/);if(!s)continue;let c=s[1],l=parseInt(s[2],10),u=parseInt(s[3],10),d=parseInt(s[4],10),m=parseInt(s[5],10);n.has(c)||n.set(c,{lineDetails:new Map,stmtTotal:0,stmtCovered:0});let p=n.get(c);for(let g=l;g<=u;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,a]of n.entries()){let s=a.lineDetails.size,c=Array.from(a.lineDetails.values()).filter(u=>u>0).length,l=Array.from(a.lineDetails.entries()).filter(([,u])=>u===0).map(([u])=>u).sort((u,d)=>u-d);t.set(i,{path:i,relativePath:M.relative(e,i),lines:{total:s,covered:c,percentage:s>0?c/s*100:0,details:a.lineDetails,uncoveredLines:l},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:a.stmtTotal,covered:a.stmtCovered,percentage:a.stmtTotal>0?a.stmtCovered/a.stmtTotal*100:0},coveragePercentage:a.stmtTotal>0?a.stmtCovered/a.stmtTotal*100:0})}return{timestamp:new Date,format:"gocover",language:"go",files:t,summary:ye(t)}}async function Ws(o,e){let t=await X.readFile(o,"utf-8"),n=en(t,e||M.dirname(o));return n.format="kover",n.language="kotlin",n}async function Ks(o,e){let t=await X.readFile(o,"utf-8");return ea(t,e||M.dirname(o))}function ea(o,e){let t=new Map,r=A(o)?.targets||[];for(let i of r)for(let a of i.files||[]){let s=a.path||"",c=a.executableLines||0,l=a.coveredLines||0,u=a.lineCoverage||0,d=[],m=0,p=0;for(let g of a.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(s,{path:s,relativePath:M.relative(e,s),lines:{total:c,covered:l,percentage:u*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:c,covered:l,percentage:u*100},coveragePercentage:u*100})}return{timestamp:new Date,format:"xcresult",language:"swift",files:t,summary:ye(t)}}var Pc={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 Ze(o,e,t,n){if(t)switch(t){case"lcov":return vr(o,e);case"json":return br(o,e);case"jacoco":return Us(o,e);case"dotcover":return Hs(o,e);case"tarpaulin":return Vs(o,e);case"gocover":return Qs(o,e);case"kover":return Ws(o,e);case"xcresult":return Ks(o,e);default:break}let r=M.extname(o).toLowerCase(),i=M.basename(o).toLowerCase();if(r===".json"||i.includes("coverage-final"))return br(o,e);if(i==="lcov.info"||r===".info"||i.includes("lcov"))return vr(o,e);if(i.includes("jacoco")&&r===".xml")return Us(o,e);if(i.includes("dotcover")&&r===".xml")return Hs(o,e);if(i.includes("tarpaulin"))return Vs(o,e);if(i.includes("kover")&&r===".xml")return Ws(o,e);if(i.includes("coverage")&&r===".out")return Qs(o,e);if(i.includes("xcresult")||i.includes("xccov"))return Ks(o,e);let a=await X.readFile(o,"utf-8"),s=a.trim();if(s.startsWith("{"))return s.includes('"files"')&&s.includes('"traces"')?Js(a,e||M.dirname(o)):s.includes('"targets"')&&s.includes('"lineCoverage"')?ea(a,e||M.dirname(o)):br(o,e);if(a.includes("SF:")&&a.includes("end_of_record"))return vr(o,e);if(s.startsWith("mode:"))return Zs(a,e||M.dirname(o));if(s.startsWith("<?xml")||s.startsWith("<")){if(a.includes('<counter type="')||a.includes("<report ")){if(n==="kotlin"){let c=en(a,e||M.dirname(o));return c.format="kover",c.language="kotlin",c}return en(a,e||M.dirname(o))}if(a.includes("CoveredStatements=")||a.includes("<Root"))return Ys(a,e||M.dirname(o))}if(n){let c=n.toLowerCase(),l=Pc[c];if(l&&l.length>0)try{return await Ze(o,e,l[0])}catch{}}throw new Error(`Unknown coverage format: ${o}`)}async function Cr(o,e){let t=e||o,n=[M.join(o,"coverage","lcov.info"),M.join(o,"coverage","coverage-final.json"),M.join(o,"lcov.info"),M.join(o,".nyc_output","coverage.json"),M.join(o,"target","site","jacoco","jacoco.xml"),M.join(o,"build","reports","jacoco","test","jacocoTestReport.xml"),M.join(o,"dotcover-report.xml"),M.join(o,"tarpaulin-report.json"),M.join(o,"cobertura.xml"),M.join(o,"coverage.out"),M.join(o,"cover.out"),M.join(o,"build","reports","kover","report.xml"),M.join(o,"coverage.json")];for(let r of n)try{return await X.access(r),Ze(r,t)}catch{}return null}function Tr(o,e,t,n){let r=e>0?o/e*100:0,i=n>0?t/n*100:0;return n===0?r:r*.7+i*.3}function ye(o){let e=0,t=0,n=0,r=0,i=0,a=0,s=0,c=0;for(let l of o.values())e+=l.lines.total,t+=l.lines.covered,n+=l.branches.total,r+=l.branches.covered,i+=l.functions.total,a+=l.functions.covered,s+=l.statements.total,c+=l.statements.covered;return{totalFiles:o.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:a,percentage:i>0?a/i*100:0},statements:{total:s,covered:c,percentage:s>0?c/s*100:0}}}k();function ta(o){let e=0,t=0,n=0,r=0,i=0,a=0,s=0,c=0;for(let l of o)e+=l.lines.total,t+=l.lines.covered,n+=l.branches.total,r+=l.branches.covered,i+=l.functions.total,a+=l.functions.covered,s+=l.statements.total,c+=l.statements.covered;return{line:e>0?t/e*100:0,branch:n>0?r/n*100:0,function:i>0?a/i*100:0,statement:s>0?c/s*100:0,files:o.length}}function na(o){let e=[];for(let[t,n]of o.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 tn=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:xc,streaming:!0,timeout:18e4};analyzerService=null;async getService(e){if(!this.analyzerService){let t=e.memory??await F(),n=await z(e);this.analyzerService=new ri({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:a=!1,includeRiskScoring:s=!1,dryRun:c=!1,coverageFormat:l,language:u}=e,d=a||s;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)||c)return this.markAsDemoData(t,"Demo mode explicitly requested"),this.getDemoResult(n,i,d,t);let m=null;if(r)try{m=await Ze(r,n,l,u)}catch(P){return{success:!1,error:`Failed to parse coverage file '${r}': ${S(P)}`}}else m=await Cr(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=na(m),h=await(await this.getService(t)).analyze({coverageData:{files:p,summary:ta(p)},threshold:i.lines||80,includeFileDetails:!0});if(!h.success)return{success:!1,error:`Analysis failed: ${h.error?.message||"Unknown error"}`};let y=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}},f=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((V,se)=>V+se.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 E;y.delta&&(E={direction:y.delta.trend,delta:Math.round((y.delta.line+y.delta.branch+y.delta.function)/3*100)/100,history:[{date:new Date(Date.now()-10080*60*1e3).toISOString().split("T")[0],coverage:v.lines.percentage-(y.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 w=e.language||m.language,T=m.format;return{success:!0,data:{summary:v,byFile:f,thresholdsPassed:C,riskScore:b,trends:E,language:w,format:T}}}catch(m){return{success:!1,error:`Coverage analysis failed: ${S(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}},a=[{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]}],s=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:a,thresholdsPassed:s,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}},nn=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:Ac,streaming:!0,timeout:12e4};gapService=null;async getService(e){if(!this.gapService){let t=e.memory??await F(),n=await z(e);this.gapService=new ii({memory:t,llmRouter:n})}return this.gapService}async execute(e,t){let{target:n=".",coverageFile:r,minRisk:i=.3,limit:a=20,prioritization:s="complexity",coverageFormat:c,language:l}=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 u=null;if(r)try{u=await Ze(r,n,c,l)}catch(C){return{success:!1,error:`Failed to parse coverage file: ${S(C)}`}}else u=await Cr(n);if(this.isDemoMode(t))return this.markAsDemoData(t,"Demo mode explicitly requested"),this.getDemoGapsResult(n,i,a,t);if(!u||u.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=na(u),m=await this.getService(t),p=s==="change-frequency"?"recent-changes":"risk",g=await m.detectGaps({coverageData:{files:d,summary:ta(d)},minCoverage:80,prioritize:p});if(!g.success)return{success:!1,error:`Gap detection failed: ${g.error?.message||"Unknown error"}`};let h=g.value,y=h.gaps.filter(C=>C.riskScore>=i).slice(0,a).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=y.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})),f;if(e.includeGhost)try{let C=await At(t);if(C?.getDomainAPIAsync){let b=await C.getDomainAPIAsync("coverage-analysis");if(b?.analyzeGhostCoverage){let E=await b.analyzeGhostCoverage(d.map(w=>w.path),n);E?.success&&E.value&&(f=(E.value.gaps||[]).map(w=>({category:w.category,severity:w.severity,description:w.description,confidence:w.confidence})))}}}catch{}return this.emitStream(t,{status:"complete",message:`Found ${y.length} coverage gaps (${h.totalUncoveredLines} uncovered lines)`,progress:100}),{success:!0,data:{gaps:y,totalGaps:h.gaps.length,criticalGaps:y.filter(C=>C.severity==="critical").length,suggestedTests:v,...f?{ghostGaps:f}:{}}}}catch(u){return{success:!1,error:`Gap detection failed: ${S(u)}`}}}getDemoGapsResult(e,t,n,r){let a=[{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(c=>c.riskScore>=t).slice(0,n),s=a.slice(0,5).map((c,l)=>({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/50*100*100)/100,priority:l+1}));return this.emitStream(r,{status:"complete",message:`Found ${a.length} coverage gaps (sample data)`,progress:100}),{success:!0,data:{gaps:a,totalGaps:a.length,criticalGaps:a.filter(c=>c.severity==="critical").length,suggestedTests:s}}}resetInstanceCache(){this.gapService=null}},xc={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"]}}},Ac={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 rn=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:kc,streaming:!0,timeout:12e4};async execute(e,t){let{metrics:n,gateName:r="default",thresholds:i=Mc(),includeAdvice:a=!0,riskTolerance:s="medium"}=e;try{let c=await xt(t);if(n&&!e.evidence)return{success:!1,error:"Timestamped evidence provenance is required when supplying quality metrics."};n&&e.evidence&&await Rt(c,n,e.evidence);let l=n??await ni(c),d=[["coverage",i.coverage],["testsPassing",i.testsPassing],["criticalBugs",i.criticalBugs],["codeSmells",i.codeSmells],["securityVulnerabilities",i.securityVulnerabilities],["technicalDebt",i.technicalDebt],["duplications",i.duplications]].filter(([b,E])=>E!==void 0&&l[b]===void 0).map(([b])=>b);if(d.length>0)return{success:!1,error:`Measured quality evidence missing configured metrics: ${d.join(", ")}.`};if(this.emitStream(t,{status:"evaluating",message:`Evaluating quality gate: ${r}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let m=[];i.coverage&&l.coverage!==void 0&&m.push({name:"Coverage",passed:l.coverage>=i.coverage.min,value:l.coverage,threshold:i.coverage.min,severity:"high",message:l.coverage>=i.coverage.min?`Coverage ${l.coverage}% meets threshold`:`Coverage ${l.coverage}% below ${i.coverage.min}% threshold`}),i.testsPassing&&l.testsPassing!==void 0&&m.push({name:"Tests Passing",passed:l.testsPassing>=i.testsPassing.min,value:l.testsPassing,threshold:i.testsPassing.min,severity:"critical",message:l.testsPassing>=i.testsPassing.min?`${l.testsPassing}% tests passing`:`Only ${l.testsPassing}% tests passing`}),i.criticalBugs&&l.criticalBugs!==void 0&&m.push({name:"Critical Bugs",passed:l.criticalBugs<=i.criticalBugs.max,value:l.criticalBugs,threshold:i.criticalBugs.max,severity:"critical",message:l.criticalBugs<=i.criticalBugs.max?`${l.criticalBugs} critical bugs within threshold`:`${l.criticalBugs} critical bugs exceed threshold of ${i.criticalBugs.max}`}),i.securityVulnerabilities&&l.securityVulnerabilities!==void 0&&m.push({name:"Security Vulnerabilities",passed:l.securityVulnerabilities<=i.securityVulnerabilities.max,value:l.securityVulnerabilities,threshold:i.securityVulnerabilities.max,severity:"critical",message:l.securityVulnerabilities<=i.securityVulnerabilities.max?`${l.securityVulnerabilities} vulnerabilities within threshold`:`${l.securityVulnerabilities} vulnerabilities found`}),i.codeSmells&&l.codeSmells!==void 0&&m.push({name:"Code Smells",passed:l.codeSmells<=i.codeSmells.max,value:l.codeSmells,threshold:i.codeSmells.max,severity:"medium",message:l.codeSmells<=i.codeSmells.max?`${l.codeSmells} code smells within threshold`:`${l.codeSmells} code smells detected`}),i.technicalDebt&&l.technicalDebt!==void 0&&m.push({name:"Technical Debt",passed:l.technicalDebt<=i.technicalDebt.max,value:l.technicalDebt,threshold:i.technicalDebt.max,severity:"medium",message:l.technicalDebt<=i.technicalDebt.max?`${l.technicalDebt}h technical debt within threshold`:`${l.technicalDebt}h technical debt exceeds threshold of ${i.technicalDebt.max}h`}),i.duplications&&l.duplications!==void 0&&m.push({name:"Duplications",passed:l.duplications<=i.duplications.max,value:l.duplications,threshold:i.duplications.max,severity:"low",message:l.duplications<=i.duplications.max?`${l.duplications}% duplication within threshold`:`${l.duplications}% duplication exceeds threshold of ${i.duplications.max}%`});let p=m.filter(b=>b.passed).length,g=m.length,h=g>0?Math.round(p/g*100):100,y=Dc(h,m),v=m.every(b=>b.passed),f=a?Ic(v,h,m,s):void 0,C=_c(m,l);return this.emitStream(t,{status:"complete",message:`Quality evaluation complete: ${y} (${h}%)`,progress:100}),{success:!0,data:{passed:v,score:h,grade:y,checks:m,deploymentAdvice:f,recommendations:C}}}catch(c){return{success:!1,error:`Quality evaluation failed: ${S(c)}`}}}},kc={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"},evidence:{type:"object",description:"Provenance required to persist supplied metrics as canonical measured evidence",properties:{measuredAt:{type:"string",description:"ISO-8601 measurement timestamp"},source:{type:"string",description:"Scanner or analyzer that produced the metrics"}}}}};function Mc(){return{coverage:{min:de.coverage.value},testsPassing:{min:de.testsPassing.value},criticalBugs:{max:de.criticalBugs.value},securityVulnerabilities:{max:de.securityVulnerabilities.value},codeSmells:{max:de.codeSmells.value},technicalDebt:{max:de.technicalDebt.value},duplications:{max:de.duplications.value}}}function Dc(o,e){return e.some(n=>!n.passed&&n.severity==="critical")?"F":o>=90?"A":o>=80?"B":o>=70?"C":o>=60?"D":"F"}function Ic(o,e,t,n){let r=t.filter(d=>!d.passed&&d.severity==="critical"),i=t.filter(d=>!d.passed&&d.severity==="high"),a=r.length*.4+i.length*.2+(100-e)/100,s=Math.min(a,1),c,u={low:{block:.2,warn:.1},medium:{block:.4,warn:.2},high:{block:.6,warn:.4}}[n];return s>=u.block||r.length>0?c="blocked":s>=u.warn?c="warning":c="approved",{decision:c,confidence:Math.round((1-s)*100)/100,riskScore:Math.round(s*100)/100,reasons:[...r.map(d=>`Critical: ${d.name} - ${d.message}`),...i.map(d=>`High: ${d.name} - ${d.message}`)],conditions:c==="warning"?["Monitor closely after deployment","Prepare rollback plan"]:void 0,rollbackPlan:c!=="approved"?"Revert to previous version if issues detected":void 0}}function _c(o,e){let t=[],n=o.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 sn=class extends x{config={name:"qe/quality/gate",description:"Two-gate, three-valued quality verdict (ADR-119): mechanical oracle gate plus a frontier judge grading the artifact against a pinned ADR-117 checklist. Returns pass|fail|inconclusive.",domain:"quality-assessment",schema:Oc,streaming:!1,timeout:12e4};async execute(e,t){try{if(!e.checklistId)return{success:!1,error:"checklistId is required"};if(typeof e.artifact!="string"||e.artifact.length===0)return{success:!1,error:"artifact (non-empty string) is required"};let n=await z(t),r=n?ai(n,{...e.model?{model:e.model}:{},logger:a=>this.logger.warn(a,{requestId:t.requestId})}):oi("no LLM provider configured \u2014 set a frontier provider API key");return n||this.markAsDemoData(t,"no LLM router \u2014 frontier judge unavailable, verdict will be inconclusive"),{success:!0,data:await si({oracleResult:e.oracle??null,artifact:e.artifact,checklistId:e.checklistId,judge:r,anchorPath:e.anchorPath})}}catch(n){return{success:!1,error:`Quality gate failed: ${S(n)}`}}}},Oc={type:"object",properties:{checklistId:{type:"string",description:'Pinned ADR-117 anchor checklist id (e.g. "A1-inRange")'},artifact:{type:"string",description:"The artifact under judgement (produced test source / spec output)"},oracle:{type:"object",description:"ADR-113 mechanical oracle result. Omit \u21D2 mechanical fail (test did not execute).",properties:{passed:{type:"boolean",description:"Mutation score met threshold"},baselinePassed:{type:"boolean",description:"Tests executed against the reference impl"}}},anchorPath:{type:"string",description:"Override the frozen anchor path (ADR-117)"},model:{type:"string",description:"Frontier judge model id (ADR-111: always frontier-tier)"}},required:["checklistId","artifact"]};k();var an={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"},on=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:Fc,streaming:!0,timeout:18e4};predictorService=null;async getService(e){if(!this.predictorService){let t=e.memory??await F(),n=await z(e);this.predictorService=new ci({memory:t,llmRouter:n})}return this.predictorService}async execute(e,t){let{files:n=[],threshold:r=.5,minConfidence:i=.7,features:a=[{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 s=await this.getService(t),c=await s.predictDefects({files:n,features:a.map(g=>({name:g.name,weight:g.weight??.25})),threshold:r});if(!c.success)return{success:!1,error:`Defect prediction failed: ${c.error?.message||"Service unavailable"}. Ensure the defect-intelligence domain is properly initialized.`};this.markAsRealData();let d=c.value.predictions.filter(g=>g.probability>=1-i).map(g=>({file:g.file,probability:Math.round(g.probability*100)/100,riskLevel:Lc(g.riskLevel),factors:g.factors.map(h=>({name:h.name,contribution:h.contribution,description:an[h.name]||`${h.name} contributes to defect risk`})),recommendations:g.recommendations}));d.sort((g,h)=>h.probability-g.probability);let m=Nc(d),p=await s.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:c.value.modelConfidence,topRiskFactors:m,recommendations:Gc(d),modelMetrics:{accuracy:p.accuracy,precision:p.precision,recall:p.recall,f1Score:p.f1Score}}}}catch(s){return{success:!1,error:`Defect prediction failed: ${S(s)}`}}}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:an.codeComplexity},{name:"changeFrequency",contribution:.25,description:an.changeFrequency},{name:"testCoverage",contribution:.2,description:an.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}},Fc={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 Lc(o){switch(o){case"critical":return"critical";case"high":return"high";case"medium":return"medium";default:return"low"}}function Nc(o){let e=new Map;for(let n of o)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:qc(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 qc(o){return{codeComplexity:"High Complexity",changeFrequency:"Frequent Changes",bugHistory:"Bug History",testCoverage:"Low Coverage",developerExperience:"Developer Experience",codeAge:"Code Age"}[o]||o.replace(/([A-Z])/g," $1").trim()}function Gc(o){let e=[],t=o.filter(i=>i.riskLevel==="critical").length,n=o.filter(i=>i.riskLevel==="high").length,r=o.length>0?o.reduce((i,a)=>i+a.probability,0)/o.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 cn=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:$c,streaming:!0,timeout:12e4};async execute(e,t){let{requirements:n,generateBDD:r=!1,checkAmbiguity:i=!0,minTestability:a=60}=e;try{if(this.emitStream(t,{status:"validating",message:`Validating ${n.length} requirements`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let s=[],c=[];for(let u of n){this.emitStream(t,{status:"processing",message:`Analyzing: ${u.title}`});let d=zc(u),m=jc(u,a,d),p=i?Bc(u):void 0;s.push({requirementId:u.id,isValid:m.filter(g=>g.severity==="error").length===0,testabilityScore:d,errors:m,ambiguityReport:p}),r&&d.value>=a&&c.push(...Hc(u))}let l={total:n.length,valid:s.filter(u=>u.isValid).length,invalid:s.filter(u=>!u.isValid).length,avgTestability:s.reduce((u,d)=>u+d.testabilityScore.value,0)/n.length,blockers:s.filter(u=>u.errors.some(d=>d.severity==="error")).length};return this.emitStream(t,{status:"complete",message:`Validation complete: ${l.valid}/${l.total} valid`,progress:100}),{success:!0,data:{validationResults:s,summary:l,bddScenarios:c.length>0?c:void 0,recommendations:Vc(s)}}}catch(s){return{success:!1,error:`Validation failed: ${S(s)}`}}}},$c={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 zc(o){let e=[],t=o.acceptanceCriteria&&o.acceptanceCriteria.length>0?90:40;e.push({name:"Acceptance Criteria",score:t,issues:t<70?["Missing or incomplete acceptance criteria"]:[]});let n=o.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 s=["should","must","when","then","verify","validate"].some(l=>o.description.toLowerCase().includes(l))?80:50;e.push({name:"Measurability",score:s,issues:s<70?["Requirement lacks measurable criteria"]:[]});let c=Math.round(e.reduce((l,u)=>l+u.score,0)/e.length);return{value:c,category:c>=80?"excellent":c>=70?"good":c>=50?"fair":"poor",factors:e}}function jc(o,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"}),(!o.acceptanceCriteria||o.acceptanceCriteria.length===0)&&n.push({code:"MISSING_AC",message:"No acceptance criteria defined",severity:"warning",suggestion:"Define specific, testable acceptance criteria"}),o.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 Bc(o){let e=[],t=["some","few","many","fast","slow","good","better","appropriate"];for(let n of t)o.description.toLowerCase().includes(n)&&e.push({term:n,context:`Found in: "${o.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(o){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"]}[o]||["Be more specific"]}function Hc(o){let e=[];return e.push({id:`scenario-${o.id}-1`,feature:o.title,scenario:`Verify ${o.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",`@${o.type||"functional"}`]}),o.acceptanceCriteria&&o.acceptanceCriteria.length>0&&o.acceptanceCriteria.forEach((t,n)=>{e.push({id:`scenario-${o.id}-ac${n+1}`,feature:o.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 Vc(o){let e=[],t=o.filter(r=>r.testabilityScore.value<60).length,n=o.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.`),o.every(r=>r.isValid)&&e.push("All requirements are valid and testable."),e}import{existsSync as Sr,readFileSync as ra}from"fs";import{join as Er,dirname as Qc}from"path";import{fileURLToPath as Wc}from"url";var Fe=["Capability","Reliability","Usability","Charisma","Security","Scalability","Compatibility","Performance","Installability","Development"],Le=["Capability","Reliability","Security","Performance","Development"];var Kc=Wc(import.meta.url),Xc=Qc(Kc),et=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=[Er(process.cwd(),".claude/helpers/v3/quality-criteria/quality-criteria-reference-template.html"),Er(process.cwd(),"node_modules/agentic-qe/assets/agents/v3/helpers/quality-criteria/quality-criteria-reference-template.html"),Er(Xc,"../../../../../assets/agents/v3/helpers/quality-criteria/quality-criteria-reference-template.html")];for(let t of e)if(Sr(t))return t;return e[0]}analyze(e){let t=e.epicContent||"";if(e.epicPath&&Sr(e.epicPath)&&(t=ra(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:a,outputPath:s}=e,c=i&&i.length>0?`
439
+ `).length;e.push({name:"real-timers-in-tests",location:`${n}:${y}`,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 Dc(o){let e=0,t=-1,n=-1;for(let r=0;r<o.length;r++)if(o[r]==="{")t===-1&&(t=r),e++;else if(o[r]==="}"&&(e--,e===0&&t!==-1)){n=r;break}return t!==-1&&n!==-1?o.substring(t+1,n):null}function _c(o){let e=0,t=-1,n=-1;for(let r=0;r<o.length;r++)if(o[r]==="{")t===-1&&(t=r),e++;else if(o[r]==="}"&&(e--,e===0&&t!==-1)){n=r;break}return t!==-1&&n!==-1?o.substring(t+1,n):null}function Oc(o,e){let t=[];return o.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();Xe();var nn=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:Nc,streaming:!0,timeout:3e5};async execute(e,t){let{testFiles:n=[],testSuites:r=[],pattern:i,parallel:a=!0,parallelism:s=4,retryCount:c=3,timeout:l=6e4,collectCoverage:u=!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:a,parallelism:s}),this.isAborted(t))return{success:!1,error:"Test execution aborted"};let h=[],y=[];for(let b=0;b<g.length;b++){let E=g[b];this.emitStream(t,{status:"running",message:`Executing ${E}`,progress:Math.round(b/g.length*100)});let w=ne()>.1,T={id:`test-${b}`,name:`Test suite for ${E.split("/").pop()}`,file:E,status:w?"passed":"failed",duration:ne()*5e3,error:w?void 0:"Assertion failed",retries:w?0:Math.min(c,2)};if(h.push(T),!w&&ne()>.7&&y.push({name:T.name,file:T.file,flakinessScore:re(.5,1),failurePattern:"intermittent-timeout"}),m&&!w)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 f=u?{lines:re(70,100),branches:re(60,80),functions:re(65,90),statements:re(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:f,flakyTests:y.length>0?y:void 0,duration:C}}}catch(g){return{success:!1,error:`Test execution failed: ${S(g)}`}}}},Nc={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}}};Q();import*as Y from"fs/promises";import*as M from"path";async function Ar(o,e){let t=await Y.readFile(o,"utf-8");return aa(t,e||M.dirname(o))}function aa(o,e){let t=new Map,n=o.split(`
440
+ `),r=null,i=new Map,a=[],s=[],c=0,l=0,u=0,d=0,m=0,p=0;for(let g of n){let h=g.trim();if(h.startsWith("SF:")){let y=h.slice(3);r={path:y,relativePath:M.relative(e,y)},i=new Map,a=[],s=[],c=0,l=0,u=0,d=0,m=0,p=0}else if(h.startsWith("DA:")){let[y,v]=h.slice(3).split(",").map(Number);!isNaN(y)&&!isNaN(v)&&(i.set(y,v),c++,v>0&&l++)}else if(h.startsWith("LF:")){let y=parseInt(h.slice(3),10);isNaN(y)||(c=y)}else if(h.startsWith("LH:")){let y=parseInt(h.slice(3),10);isNaN(y)||(l=y)}else if(h.startsWith("BRDA:")){let y=h.slice(5).split(",");if(y.length>=4){let v=parseInt(y[0],10),f=parseInt(y[1],10),C=parseInt(y[2],10),b=y[3]==="-"?0:parseInt(y[3],10);a.push({line:v,block:f,branch:C,taken:b>0,hits:b}),u++,b>0&&d++}}else if(h.startsWith("BRF:")){let y=parseInt(h.slice(4),10);isNaN(y)||(u=y)}else if(h.startsWith("BRH:")){let y=parseInt(h.slice(4),10);isNaN(y)||(d=y)}else if(h.startsWith("FN:")){let y=h.indexOf(",",3);if(y>0){let v=parseInt(h.slice(3,y),10),f=h.slice(y+1);s.find(b=>b.name===f)||s.push({name:f,line:v,hits:0})}}else if(h.startsWith("FNDA:")){let y=h.indexOf(",",5);if(y>0){let v=parseInt(h.slice(5,y),10),f=h.slice(y+1),C=s.find(b=>b.name===f);C?C.hits=v:s.push({name:f,line:0,hits:v}),m++,v>0&&p++}}else if(h.startsWith("FNF:")){let y=parseInt(h.slice(4),10);isNaN(y)||(m=y)}else if(h.startsWith("FNH:")){let y=parseInt(h.slice(4),10);isNaN(y)||(p=y)}else if(h==="end_of_record"&&r?.path){let y=Array.from(i.entries()).filter(([,b])=>b===0).map(([b])=>b).sort((b,E)=>b-E),v=a.filter(b=>!b.taken),f=s.filter(b=>b.hits===0).map(b=>b.name),C={path:r.path,relativePath:r.relativePath||r.path,lines:{total:c,covered:l,percentage:c>0?l/c*100:0,details:i,uncoveredLines:y},branches:{total:u,covered:d,percentage:u>0?d/u*100:0,uncoveredBranches:v},functions:{total:m,covered:p,percentage:m>0?p/m*100:0,details:s,uncoveredFunctions:f},statements:{total:c,covered:l,percentage:c>0?l/c*100:0},coveragePercentage:Ir(l,c,d,u)};t.set(r.path,C),r=null}}return{timestamp:new Date,format:"lcov",files:t,summary:ve(t)}}async function kr(o,e){let t=await Y.readFile(o,"utf-8"),n=A(t),r=e||M.dirname(o),i=new Map;for(let[a,s]of Object.entries(n)){if(typeof s!="object"||!s.statementMap)continue;let c=new Map,l=[],u=0,d=0;for(let[b,E]of Object.entries(s.s||{})){let w=s.statementMap[b];if(w?.start?.line){let T=w.start.line,P=c.get(T)||0;c.set(T,P+E)}u++,E>0&&d++}for(let[b,E]of c.entries())E===0&&l.push(b);let m=[],p=0,g=0;for(let[b,E]of Object.entries(s.branchMap||{})){let w=s.b?.[b]||[];for(let T=0;T<w.length;T++)m.push({line:E.loc?.start?.line||0,block:parseInt(b,10),branch:T,taken:w[T]>0,hits:w[T]}),p++,w[T]>0&&g++}let h=[],y=0,v=0;for(let[b,E]of Object.entries(s.fnMap||{})){let w=s.f?.[b]||0;h.push({name:E.name||`anonymous_${b}`,line:E.loc?.start?.line||E.decl?.start?.line||0,hits:w}),y++,w>0&&v++}let f=c.size,C=Array.from(c.values()).filter(b=>b>0).length;i.set(a,{path:a,relativePath:M.relative(r,a),lines:{total:f,covered:C,percentage:f>0?C/f*100:0,details:c,uncoveredLines:l.sort((b,E)=>b-E)},branches:{total:p,covered:g,percentage:p>0?g/p*100:0,uncoveredBranches:m.filter(b=>!b.taken)},functions:{total:y,covered:v,percentage:y>0?v/y*100:0,details:h,uncoveredFunctions:h.filter(b=>b.hits===0).map(b=>b.name)},statements:{total:u,covered:d,percentage:u>0?d/u*100:0},coveragePercentage:Ir(C,f,g,p)})}return{timestamp:new Date,format:"json",files:i,summary:ve(i)}}async function ea(o,e){let t=await Y.readFile(o,"utf-8");return rn(t,e||M.dirname(o))}function rn(o,e){let t=new Map,n=/<package\s+name="([^"]*)">([\s\S]*?)<\/package>/g,r;for(;(r=n.exec(o))!==null;){let i=r[1].replace(/\//g,M.sep),a=r[2],s=/<sourcefile\s+name="([^"]*)">([\s\S]*?)<\/sourcefile>/g,c;for(;(c=s.exec(a))!==null;){let l=c[1],u=c[2],d=M.join(e,i,l),m=Fc(u),p=new Map,g=/<line\s+nr="(\d+)"\s+mi="(\d+)"\s+ci="(\d+)"/g,h;for(;(h=g.exec(u))!==null;){let v=parseInt(h[1],10),f=parseInt(h[3],10);p.set(v,f)}let y=Array.from(p.entries()).filter(([,v])=>v===0).map(([v])=>v).sort((v,f)=>v-f);t.set(d,{path:d,relativePath:M.join(i,l),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:y},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:Ir(m.LINE.covered,m.LINE.total,m.BRANCH.covered,m.BRANCH.total)})}}return{timestamp:new Date,format:"jacoco",language:"java",files:t,summary:ve(t)}}function Fc(o){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(o))!==null;){let r=n[1],i=parseInt(n[2],10),a=parseInt(n[3],10);e[r]&&(e[r].covered+=a,e[r].total+=i+a)}return e}async function ta(o,e){let t=await Y.readFile(o,"utf-8");return oa(t,e||M.dirname(o))}function oa(o,e){let t=new Map,n=new Map,r=/<File\s+Index="(\d+)"\s+Name="([^"]*)"\s*\/>/g,i;for(;(i=r.exec(o))!==null;)n.set(i[1],i[2]);let a=/<Statement\s+FileIndex="(\d+)"\s+Line="(\d+)"\s+Column="\d+"\s+EndLine="\d+"\s+EndColumn="\d+"\s+Covered="(\w+)"\s*\/>/g,s=new Map,c;for(;(c=a.exec(o))!==null;){let l=c[1],u=parseInt(c[2],10),d=c[3]==="True",m=n.get(l)||`file-${l}`;s.has(m)||s.set(m,{lineDetails:new Map,total:0,covered:0});let p=s.get(m);p.lineDetails.set(u,d?1:0),p.total++,d&&p.covered++}if(s.size===0){let u=/CoveredStatements="(\d+)"\s+TotalStatements="(\d+)"/.exec(o);if(u){let d=parseInt(u[1],10),m=parseInt(u[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[l,u]of s.entries()){let d=Array.from(u.lineDetails.entries()).filter(([,m])=>m===0).map(([m])=>m).sort((m,p)=>m-p);t.set(l,{path:l,relativePath:M.relative(e,l),lines:{total:u.lineDetails.size,covered:Array.from(u.lineDetails.values()).filter(m=>m>0).length,percentage:u.lineDetails.size>0?Array.from(u.lineDetails.values()).filter(m=>m>0).length/u.lineDetails.size*100:0,details:u.lineDetails,uncoveredLines:d},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:u.total,covered:u.covered,percentage:u.total>0?u.covered/u.total*100:0},coveragePercentage:u.total>0?u.covered/u.total*100:0})}return{timestamp:new Date,format:"dotcover",language:"csharp",files:t,summary:ve(t)}}async function na(o,e){let t=await Y.readFile(o,"utf-8"),n=e||M.dirname(o);if(t.includes("SF:")&&t.includes("end_of_record")){let r=aa(t,n);return r.format="tarpaulin",r.language="rust",r}return ca(t,n)}function ca(o,e){let t=new Map,n=A(o);for(let r of n?.files||[]){let i=r.path||"",a=new Map,s=0,c=0;for(let u of r.traces||[]){let d=u.line,m=u.stats?.Line??u.stats?.line??0;typeof d=="number"&&(a.set(d,m),s++,m>0&&c++)}let l=Array.from(a.entries()).filter(([,u])=>u===0).map(([u])=>u).sort((u,d)=>u-d);t.set(i,{path:i,relativePath:M.relative(e,i),lines:{total:s,covered:c,percentage:s>0?c/s*100:0,details:a,uncoveredLines:l},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:s,covered:c,percentage:s>0?c/s*100:0},coveragePercentage:s>0?c/s*100:0})}return{timestamp:new Date,format:"tarpaulin",language:"rust",files:t,summary:ve(t)}}async function ra(o,e){let t=await Y.readFile(o,"utf-8");return la(t,e||M.dirname(o))}function la(o,e){let t=new Map,n=new Map,r=o.split(`
441
+ `);for(let i of r){let a=i.trim();if(!a||a.startsWith("mode:"))continue;let s=a.match(/^(.+):(\d+)\.\d+,(\d+)\.\d+\s+(\d+)\s+(\d+)$/);if(!s)continue;let c=s[1],l=parseInt(s[2],10),u=parseInt(s[3],10),d=parseInt(s[4],10),m=parseInt(s[5],10);n.has(c)||n.set(c,{lineDetails:new Map,stmtTotal:0,stmtCovered:0});let p=n.get(c);for(let g=l;g<=u;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,a]of n.entries()){let s=a.lineDetails.size,c=Array.from(a.lineDetails.values()).filter(u=>u>0).length,l=Array.from(a.lineDetails.entries()).filter(([,u])=>u===0).map(([u])=>u).sort((u,d)=>u-d);t.set(i,{path:i,relativePath:M.relative(e,i),lines:{total:s,covered:c,percentage:s>0?c/s*100:0,details:a.lineDetails,uncoveredLines:l},branches:{total:0,covered:0,percentage:0,uncoveredBranches:[]},functions:{total:0,covered:0,percentage:0,details:[],uncoveredFunctions:[]},statements:{total:a.stmtTotal,covered:a.stmtCovered,percentage:a.stmtTotal>0?a.stmtCovered/a.stmtTotal*100:0},coveragePercentage:a.stmtTotal>0?a.stmtCovered/a.stmtTotal*100:0})}return{timestamp:new Date,format:"gocover",language:"go",files:t,summary:ve(t)}}async function ia(o,e){let t=await Y.readFile(o,"utf-8"),n=rn(t,e||M.dirname(o));return n.format="kover",n.language="kotlin",n}async function sa(o,e){let t=await Y.readFile(o,"utf-8");return ua(t,e||M.dirname(o))}function ua(o,e){let t=new Map,r=A(o)?.targets||[];for(let i of r)for(let a of i.files||[]){let s=a.path||"",c=a.executableLines||0,l=a.coveredLines||0,u=a.lineCoverage||0,d=[],m=0,p=0;for(let g of a.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(s,{path:s,relativePath:M.relative(e,s),lines:{total:c,covered:l,percentage:u*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:c,covered:l,percentage:u*100},coveragePercentage:u*100})}return{timestamp:new Date,format:"xcresult",language:"swift",files:t,summary:ve(t)}}var Lc={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 nt(o,e,t,n){if(t)switch(t){case"lcov":return Ar(o,e);case"json":return kr(o,e);case"jacoco":return ea(o,e);case"dotcover":return ta(o,e);case"tarpaulin":return na(o,e);case"gocover":return ra(o,e);case"kover":return ia(o,e);case"xcresult":return sa(o,e);default:break}let r=M.extname(o).toLowerCase(),i=M.basename(o).toLowerCase();if(r===".json"||i.includes("coverage-final"))return kr(o,e);if(i==="lcov.info"||r===".info"||i.includes("lcov"))return Ar(o,e);if(i.includes("jacoco")&&r===".xml")return ea(o,e);if(i.includes("dotcover")&&r===".xml")return ta(o,e);if(i.includes("tarpaulin"))return na(o,e);if(i.includes("kover")&&r===".xml")return ia(o,e);if(i.includes("coverage")&&r===".out")return ra(o,e);if(i.includes("xcresult")||i.includes("xccov"))return sa(o,e);let a=await Y.readFile(o,"utf-8"),s=a.trim();if(s.startsWith("{"))return s.includes('"files"')&&s.includes('"traces"')?ca(a,e||M.dirname(o)):s.includes('"targets"')&&s.includes('"lineCoverage"')?ua(a,e||M.dirname(o)):kr(o,e);if(a.includes("SF:")&&a.includes("end_of_record"))return Ar(o,e);if(s.startsWith("mode:"))return la(a,e||M.dirname(o));if(s.startsWith("<?xml")||s.startsWith("<")){if(a.includes('<counter type="')||a.includes("<report ")){if(n==="kotlin"){let c=rn(a,e||M.dirname(o));return c.format="kover",c.language="kotlin",c}return rn(a,e||M.dirname(o))}if(a.includes("CoveredStatements=")||a.includes("<Root"))return oa(a,e||M.dirname(o))}if(n){let c=n.toLowerCase(),l=Lc[c];if(l&&l.length>0)try{return await nt(o,e,l[0])}catch{}}throw new Error(`Unknown coverage format: ${o}`)}async function Mr(o,e){let t=e||o,n=[M.join(o,"coverage","lcov.info"),M.join(o,"coverage","coverage-final.json"),M.join(o,"lcov.info"),M.join(o,".nyc_output","coverage.json"),M.join(o,"target","site","jacoco","jacoco.xml"),M.join(o,"build","reports","jacoco","test","jacocoTestReport.xml"),M.join(o,"dotcover-report.xml"),M.join(o,"tarpaulin-report.json"),M.join(o,"cobertura.xml"),M.join(o,"coverage.out"),M.join(o,"cover.out"),M.join(o,"build","reports","kover","report.xml"),M.join(o,"coverage.json")];for(let r of n)try{return await Y.access(r),nt(r,t)}catch{}return null}function Ir(o,e,t,n){let r=e>0?o/e*100:0,i=n>0?t/n*100:0;return n===0?r:r*.7+i*.3}function ve(o){let e=0,t=0,n=0,r=0,i=0,a=0,s=0,c=0;for(let l of o.values())e+=l.lines.total,t+=l.lines.covered,n+=l.branches.total,r+=l.branches.covered,i+=l.functions.total,a+=l.functions.covered,s+=l.statements.total,c+=l.statements.covered;return{totalFiles:o.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:a,percentage:i>0?a/i*100:0},statements:{total:s,covered:c,percentage:s>0?c/s*100:0}}}k();function da(o){let e=0,t=0,n=0,r=0,i=0,a=0,s=0,c=0;for(let l of o)e+=l.lines.total,t+=l.lines.covered,n+=l.branches.total,r+=l.branches.covered,i+=l.functions.total,a+=l.functions.covered,s+=l.statements.total,c+=l.statements.covered;return{line:e>0?t/e*100:0,branch:n>0?r/n*100:0,function:i>0?a/i*100:0,statement:s>0?c/s*100:0,files:o.length}}function ma(o){let e=[];for(let[t,n]of o.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 sn=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:qc,streaming:!0,timeout:18e4};analyzerService=null;async getService(e){if(!this.analyzerService){let t=e.memory??await N(),n=await z(e);this.analyzerService=new pi({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:a=!1,includeRiskScoring:s=!1,dryRun:c=!1,coverageFormat:l,language:u}=e,d=a||s;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)||c)return this.markAsDemoData(t,"Demo mode explicitly requested"),this.getDemoResult(n,i,d,t);let m=null;if(r)try{m=await nt(r,n,l,u)}catch(P){return{success:!1,error:`Failed to parse coverage file '${r}': ${S(P)}`}}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=ma(m),h=await(await this.getService(t)).analyze({coverageData:{files:p,summary:da(p)},threshold:i.lines||80,includeFileDetails:!0});if(!h.success)return{success:!1,error:`Analysis failed: ${h.error?.message||"Unknown error"}`};let y=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}},f=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((V,ae)=>V+ae.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 E;y.delta&&(E={direction:y.delta.trend,delta:Math.round((y.delta.line+y.delta.branch+y.delta.function)/3*100)/100,history:[{date:new Date(Date.now()-10080*60*1e3).toISOString().split("T")[0],coverage:v.lines.percentage-(y.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 w=e.language||m.language,T=m.format;return{success:!0,data:{summary:v,byFile:f,thresholdsPassed:C,riskScore:b,trends:E,language:w,format:T}}}catch(m){return{success:!1,error:`Coverage analysis failed: ${S(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}},a=[{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]}],s=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:a,thresholdsPassed:s,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}},an=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:Gc,streaming:!0,timeout:12e4};gapService=null;async getService(e){if(!this.gapService){let t=e.memory??await N(),n=await z(e);this.gapService=new gi({memory:t,llmRouter:n})}return this.gapService}async execute(e,t){let{target:n=".",coverageFile:r,minRisk:i=.3,limit:a=20,prioritization:s="complexity",coverageFormat:c,language:l}=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 u=null;if(r)try{u=await nt(r,n,c,l)}catch(C){return{success:!1,error:`Failed to parse coverage file: ${S(C)}`}}else u=await Mr(n);if(this.isDemoMode(t))return this.markAsDemoData(t,"Demo mode explicitly requested"),this.getDemoGapsResult(n,i,a,t);if(!u||u.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=ma(u),m=await this.getService(t),p=s==="change-frequency"?"recent-changes":"risk",g=await m.detectGaps({coverageData:{files:d,summary:da(d)},minCoverage:80,prioritize:p});if(!g.success)return{success:!1,error:`Gap detection failed: ${g.error?.message||"Unknown error"}`};let h=g.value,y=h.gaps.filter(C=>C.riskScore>=i).slice(0,a).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=y.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})),f;if(e.includeGhost)try{let C=await It(t);if(C?.getDomainAPIAsync){let b=await C.getDomainAPIAsync("coverage-analysis");if(b?.analyzeGhostCoverage){let E=await b.analyzeGhostCoverage(d.map(w=>w.path),n);E?.success&&E.value&&(f=(E.value.gaps||[]).map(w=>({category:w.category,severity:w.severity,description:w.description,confidence:w.confidence})))}}}catch{}return this.emitStream(t,{status:"complete",message:`Found ${y.length} coverage gaps (${h.totalUncoveredLines} uncovered lines)`,progress:100}),{success:!0,data:{gaps:y,totalGaps:h.gaps.length,criticalGaps:y.filter(C=>C.severity==="critical").length,suggestedTests:v,...f?{ghostGaps:f}:{}}}}catch(u){return{success:!1,error:`Gap detection failed: ${S(u)}`}}}getDemoGapsResult(e,t,n,r){let a=[{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(c=>c.riskScore>=t).slice(0,n),s=a.slice(0,5).map((c,l)=>({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/50*100*100)/100,priority:l+1}));return this.emitStream(r,{status:"complete",message:`Found ${a.length} coverage gaps (sample data)`,progress:100}),{success:!0,data:{gaps:a,totalGaps:a.length,criticalGaps:a.filter(c=>c.severity==="critical").length,suggestedTests:s}}}resetInstanceCache(){this.gapService=null}},qc={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"]}}},Gc={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 on=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:$c,streaming:!0,timeout:12e4};async execute(e,t){let{metrics:n,gateName:r="default",thresholds:i=zc(),includeAdvice:a=!0,riskTolerance:s="medium"}=e;try{let c=await Mt(t);if(n&&!e.evidence)return{success:!1,error:"Timestamped evidence provenance is required when supplying quality metrics."};n&&e.evidence&&await At(c,n,e.evidence);let l=n??await mi(c),d=[["coverage",i.coverage],["testsPassing",i.testsPassing],["criticalBugs",i.criticalBugs],["codeSmells",i.codeSmells],["securityVulnerabilities",i.securityVulnerabilities],["technicalDebt",i.technicalDebt],["duplications",i.duplications]].filter(([b,E])=>E!==void 0&&l[b]===void 0).map(([b])=>b);if(d.length>0)return{success:!1,error:`Measured quality evidence missing configured metrics: ${d.join(", ")}.`};if(this.emitStream(t,{status:"evaluating",message:`Evaluating quality gate: ${r}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let m=[];i.coverage&&l.coverage!==void 0&&m.push({name:"Coverage",passed:l.coverage>=i.coverage.min,value:l.coverage,threshold:i.coverage.min,severity:"high",message:l.coverage>=i.coverage.min?`Coverage ${l.coverage}% meets threshold`:`Coverage ${l.coverage}% below ${i.coverage.min}% threshold`}),i.testsPassing&&l.testsPassing!==void 0&&m.push({name:"Tests Passing",passed:l.testsPassing>=i.testsPassing.min,value:l.testsPassing,threshold:i.testsPassing.min,severity:"critical",message:l.testsPassing>=i.testsPassing.min?`${l.testsPassing}% tests passing`:`Only ${l.testsPassing}% tests passing`}),i.criticalBugs&&l.criticalBugs!==void 0&&m.push({name:"Critical Bugs",passed:l.criticalBugs<=i.criticalBugs.max,value:l.criticalBugs,threshold:i.criticalBugs.max,severity:"critical",message:l.criticalBugs<=i.criticalBugs.max?`${l.criticalBugs} critical bugs within threshold`:`${l.criticalBugs} critical bugs exceed threshold of ${i.criticalBugs.max}`}),i.securityVulnerabilities&&l.securityVulnerabilities!==void 0&&m.push({name:"Security Vulnerabilities",passed:l.securityVulnerabilities<=i.securityVulnerabilities.max,value:l.securityVulnerabilities,threshold:i.securityVulnerabilities.max,severity:"critical",message:l.securityVulnerabilities<=i.securityVulnerabilities.max?`${l.securityVulnerabilities} vulnerabilities within threshold`:`${l.securityVulnerabilities} vulnerabilities found`}),i.codeSmells&&l.codeSmells!==void 0&&m.push({name:"Code Smells",passed:l.codeSmells<=i.codeSmells.max,value:l.codeSmells,threshold:i.codeSmells.max,severity:"medium",message:l.codeSmells<=i.codeSmells.max?`${l.codeSmells} code smells within threshold`:`${l.codeSmells} code smells detected`}),i.technicalDebt&&l.technicalDebt!==void 0&&m.push({name:"Technical Debt",passed:l.technicalDebt<=i.technicalDebt.max,value:l.technicalDebt,threshold:i.technicalDebt.max,severity:"medium",message:l.technicalDebt<=i.technicalDebt.max?`${l.technicalDebt}h technical debt within threshold`:`${l.technicalDebt}h technical debt exceeds threshold of ${i.technicalDebt.max}h`}),i.duplications&&l.duplications!==void 0&&m.push({name:"Duplications",passed:l.duplications<=i.duplications.max,value:l.duplications,threshold:i.duplications.max,severity:"low",message:l.duplications<=i.duplications.max?`${l.duplications}% duplication within threshold`:`${l.duplications}% duplication exceeds threshold of ${i.duplications.max}%`});let p=m.filter(b=>b.passed).length,g=m.length,h=g>0?Math.round(p/g*100):100,y=jc(h,m),v=m.every(b=>b.passed),f=a?Bc(v,h,m,s):void 0,C=Uc(m,l);return this.emitStream(t,{status:"complete",message:`Quality evaluation complete: ${y} (${h}%)`,progress:100}),{success:!0,data:{passed:v,score:h,grade:y,checks:m,deploymentAdvice:f,recommendations:C}}}catch(c){return{success:!1,error:`Quality evaluation failed: ${S(c)}`}}}},$c={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"},evidence:{type:"object",description:"Provenance required to persist supplied metrics as canonical measured evidence",properties:{measuredAt:{type:"string",description:"ISO-8601 measurement timestamp"},source:{type:"string",description:"Scanner or analyzer that produced the metrics"}}}}};function zc(){return{coverage:{min:me.coverage.value},testsPassing:{min:me.testsPassing.value},criticalBugs:{max:me.criticalBugs.value},securityVulnerabilities:{max:me.securityVulnerabilities.value},codeSmells:{max:me.codeSmells.value},technicalDebt:{max:me.technicalDebt.value},duplications:{max:me.duplications.value}}}function jc(o,e){return e.some(n=>!n.passed&&n.severity==="critical")?"F":o>=90?"A":o>=80?"B":o>=70?"C":o>=60?"D":"F"}function Bc(o,e,t,n){let r=t.filter(d=>!d.passed&&d.severity==="critical"),i=t.filter(d=>!d.passed&&d.severity==="high"),a=r.length*.4+i.length*.2+(100-e)/100,s=Math.min(a,1),c,u={low:{block:.2,warn:.1},medium:{block:.4,warn:.2},high:{block:.6,warn:.4}}[n];return s>=u.block||r.length>0?c="blocked":s>=u.warn?c="warning":c="approved",{decision:c,confidence:Math.round((1-s)*100)/100,riskScore:Math.round(s*100)/100,reasons:[...r.map(d=>`Critical: ${d.name} - ${d.message}`),...i.map(d=>`High: ${d.name} - ${d.message}`)],conditions:c==="warning"?["Monitor closely after deployment","Prepare rollback plan"]:void 0,rollbackPlan:c!=="approved"?"Revert to previous version if issues detected":void 0}}function Uc(o,e){let t=[],n=o.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 cn=class extends x{config={name:"qe/quality/gate",description:"Two-gate, three-valued quality verdict (ADR-119): mechanical oracle gate plus a frontier judge grading plus failure-mode verification reach. Returns pass|fail|inconclusive.",domain:"quality-assessment",schema:Hc,streaming:!1,timeout:12e4};async execute(e,t){try{if(!e.checklistId)return{success:!1,error:"checklistId is required"};if(typeof e.artifact!="string"||e.artifact.length===0)return{success:!1,error:"artifact (non-empty string) is required"};let n=await z(t),r=n?fi(n,{...e.model?{model:e.model}:{},logger:a=>this.logger.warn(a,{requestId:t.requestId})}):yi("no LLM provider configured \u2014 set a frontier provider API key");return n||this.markAsDemoData(t,"no LLM router \u2014 frontier judge unavailable, verdict will be inconclusive"),{success:!0,data:await hi({oracleResult:e.oracle??null,artifact:e.artifact,checklistId:e.checklistId,judge:r,anchorPath:e.anchorPath,verificationManifest:e.verificationManifest})}}catch(n){return{success:!1,error:`Quality gate failed: ${S(n)}`}}}},Hc={type:"object",properties:{checklistId:{type:"string",description:'Pinned ADR-117 anchor checklist id (e.g. "A1-inRange")'},artifact:{type:"string",description:"The artifact under judgement (produced test source / spec output)"},oracle:{type:"object",description:"ADR-113 mechanical oracle result. Omit \u21D2 mechanical fail (test did not execute).",properties:{passed:{type:"boolean",description:"Mutation score met threshold"},baselinePassed:{type:"boolean",description:"Tests executed against the reference impl"}}},anchorPath:{type:"string",description:"Override the frozen anchor path (ADR-117)"},verificationManifest:{type:"object",description:"Hashed, revision-bound failure-mode verification reach manifest (#651)"},model:{type:"string",description:"Frontier judge model id (ADR-111: always frontier-tier)"}},required:["checklistId","artifact"]};k();var ln={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"},un=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:Vc,streaming:!0,timeout:18e4};predictorService=null;async getService(e){if(!this.predictorService){let t=e.memory??await N(),n=await z(e);this.predictorService=new vi({memory:t,llmRouter:n})}return this.predictorService}async execute(e,t){let{files:n=[],threshold:r=.5,minConfidence:i=.7,features:a=[{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 s=await this.getService(t),c=await s.predictDefects({files:n,features:a.map(g=>({name:g.name,weight:g.weight??.25})),threshold:r});if(!c.success)return{success:!1,error:`Defect prediction failed: ${c.error?.message||"Service unavailable"}. Ensure the defect-intelligence domain is properly initialized.`};this.markAsRealData();let d=c.value.predictions.filter(g=>g.probability>=1-i).map(g=>({file:g.file,probability:Math.round(g.probability*100)/100,riskLevel:Qc(g.riskLevel),factors:g.factors.map(h=>({name:h.name,contribution:h.contribution,description:ln[h.name]||`${h.name} contributes to defect risk`})),recommendations:g.recommendations}));d.sort((g,h)=>h.probability-g.probability);let m=Wc(d),p=await s.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:c.value.modelConfidence,topRiskFactors:m,recommendations:Xc(d),modelMetrics:{accuracy:p.accuracy,precision:p.precision,recall:p.recall,f1Score:p.f1Score}}}}catch(s){return{success:!1,error:`Defect prediction failed: ${S(s)}`}}}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:ln.codeComplexity},{name:"changeFrequency",contribution:.25,description:ln.changeFrequency},{name:"testCoverage",contribution:.2,description:ln.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}},Vc={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 Qc(o){switch(o){case"critical":return"critical";case"high":return"high";case"medium":return"medium";default:return"low"}}function Wc(o){let e=new Map;for(let n of o)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:Kc(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 Kc(o){return{codeComplexity:"High Complexity",changeFrequency:"Frequent Changes",bugHistory:"Bug History",testCoverage:"Low Coverage",developerExperience:"Developer Experience",codeAge:"Code Age"}[o]||o.replace(/([A-Z])/g," $1").trim()}function Xc(o){let e=[],t=o.filter(i=>i.riskLevel==="critical").length,n=o.filter(i=>i.riskLevel==="high").length,r=o.length>0?o.reduce((i,a)=>i+a.probability,0)/o.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 dn=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:Yc,streaming:!0,timeout:12e4};async execute(e,t){let{requirements:n,generateBDD:r=!1,checkAmbiguity:i=!0,minTestability:a=60}=e;try{if(this.emitStream(t,{status:"validating",message:`Validating ${n.length} requirements`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let s=[],c=[];for(let u of n){this.emitStream(t,{status:"processing",message:`Analyzing: ${u.title}`});let d=Jc(u),m=Zc(u,a,d),p=i?el(u):void 0;s.push({requirementId:u.id,isValid:m.filter(g=>g.severity==="error").length===0,testabilityScore:d,errors:m,ambiguityReport:p}),r&&d.value>=a&&c.push(...nl(u))}let l={total:n.length,valid:s.filter(u=>u.isValid).length,invalid:s.filter(u=>!u.isValid).length,avgTestability:s.reduce((u,d)=>u+d.testabilityScore.value,0)/n.length,blockers:s.filter(u=>u.errors.some(d=>d.severity==="error")).length};return this.emitStream(t,{status:"complete",message:`Validation complete: ${l.valid}/${l.total} valid`,progress:100}),{success:!0,data:{validationResults:s,summary:l,bddScenarios:c.length>0?c:void 0,recommendations:rl(s)}}}catch(s){return{success:!1,error:`Validation failed: ${S(s)}`}}}},Yc={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 Jc(o){let e=[],t=o.acceptanceCriteria&&o.acceptanceCriteria.length>0?90:40;e.push({name:"Acceptance Criteria",score:t,issues:t<70?["Missing or incomplete acceptance criteria"]:[]});let n=o.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 s=["should","must","when","then","verify","validate"].some(l=>o.description.toLowerCase().includes(l))?80:50;e.push({name:"Measurability",score:s,issues:s<70?["Requirement lacks measurable criteria"]:[]});let c=Math.round(e.reduce((l,u)=>l+u.score,0)/e.length);return{value:c,category:c>=80?"excellent":c>=70?"good":c>=50?"fair":"poor",factors:e}}function Zc(o,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"}),(!o.acceptanceCriteria||o.acceptanceCriteria.length===0)&&n.push({code:"MISSING_AC",message:"No acceptance criteria defined",severity:"warning",suggestion:"Define specific, testable acceptance criteria"}),o.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 el(o){let e=[],t=["some","few","many","fast","slow","good","better","appropriate"];for(let n of t)o.description.toLowerCase().includes(n)&&e.push({term:n,context:`Found in: "${o.description.substring(0,50)}..."`,alternatives:tl(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 tl(o){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"]}[o]||["Be more specific"]}function nl(o){let e=[];return e.push({id:`scenario-${o.id}-1`,feature:o.title,scenario:`Verify ${o.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",`@${o.type||"functional"}`]}),o.acceptanceCriteria&&o.acceptanceCriteria.length>0&&o.acceptanceCriteria.forEach((t,n)=>{e.push({id:`scenario-${o.id}-ac${n+1}`,feature:o.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 rl(o){let e=[],t=o.filter(r=>r.testabilityScore.value<60).length,n=o.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.`),o.every(r=>r.isValid)&&e.push("All requirements are valid and testable."),e}import{existsSync as Dr,readFileSync as pa}from"fs";import{join as _r,dirname as il}from"path";import{fileURLToPath as sl}from"url";var qe=["Capability","Reliability","Usability","Charisma","Security","Scalability","Compatibility","Performance","Installability","Development"],Ge=["Capability","Reliability","Security","Performance","Development"];var al=sl(import.meta.url),ol=il(al),rt=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=[_r(process.cwd(),".claude/helpers/v3/quality-criteria/quality-criteria-reference-template.html"),_r(process.cwd(),"node_modules/agentic-qe/assets/agents/v3/helpers/quality-criteria/quality-criteria-reference-template.html"),_r(ol,"../../../../../assets/agents/v3/helpers/quality-criteria/quality-criteria-reference-template.html")];for(let t of e)if(Dr(t))return t;return e[0]}analyze(e){let t=e.epicContent||"";if(e.epicPath&&Dr(e.epicPath)&&(t=pa(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:a,outputPath:s}=e,c=i&&i.length>0?`
442
442
  ## Source Paths to Analyze
443
443
  ${i.map(u=>`- ${u}`).join(`
444
444
  `)}
@@ -466,11 +466,11 @@ ${c}
466
466
  Perform HTSM v6.3 Quality Criteria analysis on the above requirements.
467
467
 
468
468
  ### HTSM Categories to Analyze
469
- ${Fe.map((u,d)=>`${d+1}. ${u}`).join(`
469
+ ${qe.map((u,d)=>`${d+1}. ${u}`).join(`
470
470
  `)}
471
471
 
472
472
  ### Categories That CANNOT Be Omitted
473
- ${Le.map(u=>`- ${u}`).join(`
473
+ ${Ge.map(u=>`- ${u}`).join(`
474
474
  `)}
475
475
 
476
476
  ### Evidence Classification
@@ -511,7 +511,7 @@ Return a complete QualityCriteriaAnalysis object with:
511
511
  ${l}
512
512
  ## Begin Analysis
513
513
 
514
- 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&&Sr(this.config.templatePath)&&(this.templateCache=ra(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>
514
+ 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&&Dr(this.config.templatePath)&&(this.templateCache=pa(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>
515
515
  <html lang="en">
516
516
  <head>
517
517
  <meta charset="UTF-8">
@@ -545,7 +545,7 @@ Analyze the requirements above and return the complete QualityCriteriaAnalysis.`
545
545
  </footer>
546
546
  </body>
547
547
  </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(`
548
- `)}};function ln(o){return new et(o)}k();k();import{existsSync as Jc,readFileSync as Zc}from"fs";var tt=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:el,streaming:!0,timeout:12e4};service=null;getService(){return this.service||(this.service=ln()),this.service}async execute(e,t){let{assessmentName:n,epicPath:r,epicContent:i,sourcePaths:a,outputFormat:s="html",outputPath:c,evidencePoints:l,completedAnalysis:u,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(!l||l.length===0)return{success:!1,error:"validate-evidence action requires evidencePoints array"};this.emitStream(t,{status:"validating",message:`Validating ${l.length} evidence points`});let y=m.validateEvidence(l);return{success:!0,data:{evidenceValidation:y,message:y.valid?`All ${l.length} evidence points are valid`:`Validation failed with ${y.errors.length} errors`}}}if(d==="format"){if(!u)return{success:!1,error:"format action requires completedAnalysis object"};this.emitStream(t,{status:"formatting",message:`Formatting analysis as ${s}`});let y,v,f;switch(s){case"html":y=m.generateHTML(u);break;case"json":v=JSON.stringify(u,null,2);break;case"markdown":f=m.generateMarkdown(u);break}return{success:!0,data:{html:y,json:v,markdown:f,message:`Analysis formatted as ${s}`}}}this.emitStream(t,{status:"preparing",message:"Preparing agent invocation for semantic HTSM analysis"});let p=i||"";if(r&&Jc(r)&&(p=Zc(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:a,outputFormat:s,outputPath:c}),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: ${S(m)}`}}}buildAgentPrompt(e){let{assessmentName:t,epicContent:n,epicPath:r,sourcePaths:i,outputFormat:a,outputPath:s}=e,c=i&&i.length>0?`
548
+ `)}};function mn(o){return new rt(o)}k();k();import{existsSync as ll,readFileSync as ul}from"fs";var it=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:dl,streaming:!0,timeout:12e4};service=null;getService(){return this.service||(this.service=mn()),this.service}async execute(e,t){let{assessmentName:n,epicPath:r,epicContent:i,sourcePaths:a,outputFormat:s="html",outputPath:c,evidencePoints:l,completedAnalysis:u,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(!l||l.length===0)return{success:!1,error:"validate-evidence action requires evidencePoints array"};this.emitStream(t,{status:"validating",message:`Validating ${l.length} evidence points`});let y=m.validateEvidence(l);return{success:!0,data:{evidenceValidation:y,message:y.valid?`All ${l.length} evidence points are valid`:`Validation failed with ${y.errors.length} errors`}}}if(d==="format"){if(!u)return{success:!1,error:"format action requires completedAnalysis object"};this.emitStream(t,{status:"formatting",message:`Formatting analysis as ${s}`});let y,v,f;switch(s){case"html":y=m.generateHTML(u);break;case"json":v=JSON.stringify(u,null,2);break;case"markdown":f=m.generateMarkdown(u);break}return{success:!0,data:{html:y,json:v,markdown:f,message:`Analysis formatted as ${s}`}}}this.emitStream(t,{status:"preparing",message:"Preparing agent invocation for semantic HTSM analysis"});let p=i||"";if(r&&ll(r)&&(p=ul(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:a,outputFormat:s,outputPath:c}),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: ${S(m)}`}}}buildAgentPrompt(e){let{assessmentName:t,epicContent:n,epicPath:r,sourcePaths:i,outputFormat:a,outputPath:s}=e,c=i&&i.length>0?`
549
549
  ## Source Paths to Analyze
550
550
  ${i.map(u=>`- ${u}`).join(`
551
551
  `)}
@@ -574,11 +574,11 @@ ${c}
574
574
  Perform HTSM v6.3 Quality Criteria analysis on the above requirements.
575
575
 
576
576
  ### HTSM Categories to Analyze
577
- ${Fe.map((u,d)=>`${d+1}. ${u}`).join(`
577
+ ${qe.map((u,d)=>`${d+1}. ${u}`).join(`
578
578
  `)}
579
579
 
580
580
  ### Categories That CANNOT Be Omitted
581
- ${Le.map(u=>`- ${u}`).join(`
581
+ ${Ge.map(u=>`- ${u}`).join(`
582
582
  `)}
583
583
 
584
584
  ### Evidence Classification
@@ -619,19 +619,19 @@ Return a complete QualityCriteriaAnalysis object with:
619
619
  ${l}
620
620
  ## Begin Analysis
621
621
 
622
- Analyze the requirements above and return the complete QualityCriteriaAnalysis.`}resetInstanceCache(){this.service=null}},el={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"]},gy=new tt;k();import*as wr from"fs";import*as ge from"path";var un=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:tl,streaming:!0,timeout:3e5};knowledgeGraph=null;semanticAnalyzer=null;impactAnalyzer=null;async getKnowledgeGraph(e){if(!this.knowledgeGraph){let t=e.memory??await F(),n=await z(e);this.knowledgeGraph=new Pt({memory:t,llmRouter:n})}return this.knowledgeGraph}async getSemanticAnalyzer(e){if(!this.semanticAnalyzer){let t=e.memory;this.semanticAnalyzer=new li(t||await F())}return this.semanticAnalyzer}async getImpactAnalyzer(e){if(!this.impactAnalyzer){let t=e.memory,n=await this.getKnowledgeGraph(e);this.impactAnalyzer=new ui(t||await F(),n)}return this.impactAnalyzer}async execute(e,t){let{action:n,paths:r=["."],query:i,changedFiles:a=[],depth:s=3,incremental:c=!1}=e;try{if(this.emitStream(t,{status:"processing",message:`Executing ${n} action`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let l={action:n};switch(n){case"index":l.indexResult=await this.executeIndex(r,c,t);break;case"search":if(!i)return{success:!1,error:"Query is required for search action"};l.searchResult=await this.executeSearch(i,r,t);break;case"impact":if(a.length===0)return{success:!1,error:"changedFiles is required for impact action"};l.impactResult=await this.executeImpact(a,s,t);break;case"dependencies":l.dependencyResult=await this.executeDependencies(r,s,t);break;default:return{success:!1,error:`Unknown action: ${n}`}}return this.emitStream(t,{status:"complete",message:`${n} complete`,progress:100}),{success:!0,data:l}}catch(l){return{success:!1,error:`Code analysis failed: ${S(l)}`}}}async executeIndex(e,t,n){this.emitStream(n,{status:"indexing",message:`Indexing ${e.length} paths (${t?"incremental":"full"})`});let r=await this.getKnowledgeGraph(n),i=await this.expandPaths(e),a=await r.index({paths:i,incremental:t,includeTests:!0,languages:["typescript","javascript"]});if(!a.success)throw new Error(a.error?.message||"Indexing failed");return{filesIndexed:a.value.filesIndexed,nodesCreated:a.value.nodesCreated,edgesCreated:a.value.edgesCreated,duration:a.value.duration,errors:a.value.errors}}async executeSearch(e,t,n){let r=Date.now();if(this.isDemoMode(n)){let l=Date.now()-r;return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoSearchResult(e,l)}this.emitStream(n,{status:"searching",message:`Searching for: ${e}`});let a=await(await this.getSemanticAnalyzer(n)).search({query:e,type:"semantic",limit:20,scope:t.length>0&&t[0]!=="."?t:void 0}),s=Date.now()-r;return a.success?a.value.results.length===0?(this.markAsRealData(),{results:[],total:0,searchTime:s}):(this.markAsRealData(),{results:a.value.results.map(l=>({file:l.file,line:l.line,snippet:l.snippet.substring(0,200)+(l.snippet.length>200?"...":""),score:l.score,highlights:nl(l.snippet,e)})),total:a.value.total,searchTime:s}):{results:[],total:0,searchTime:s}}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 a=i.value;return{directImpact:a.directImpact,transitiveImpact:a.transitiveImpact,impactedTests:a.impactedTests,riskLevel:a.riskLevel,recommendations:a.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),a=await r.mapDependencies({files:i,direction:"both",depth:t});if(!a.success)throw new Error(a.error?.message||"Dependency mapping failed");let s=a.value,c=s.nodes.map(u=>({id:u.id,path:u.path,type:u.type,inDegree:u.inDegree,outDegree:u.outDegree})),l=s.edges.map(u=>({source:u.source,target:u.target,type:u.type}));return{nodes:c,edges:l,cycles:s.cycles,metrics:{totalNodes:s.metrics.totalNodes,totalEdges:s.metrics.totalEdges,avgDegree:s.metrics.avgDegree,maxDepth:s.metrics.maxDepth}}}async expandPaths(e){let t=[];for(let n of e){let r=ge.isAbsolute(n)?n:ge.resolve(process.cwd(),n);try{let i=await wr.promises.stat(r);if(i.isDirectory()){let a=await this.findSourceFiles(r);t.push(...a)}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 wr.promises.readdir(e,{withFileTypes:!0});for(let a of i){let s=ge.join(e,a.name);if(a.isDirectory()){if(!r.includes(a.name)){let c=await this.findSourceFiles(s);t.push(...c)}}else if(a.isFile()){let c=ge.extname(a.name);n.includes(c)&&t.push(s)}}}catch{}return t}},tl={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 nl(o,e){let t=[],n=e.toLowerCase().split(/\s+/),r=o.toLowerCase();for(let i of n){if(i.length<2)continue;let a=0;for(;(a=r.indexOf(i,a))!==-1;){let s=Math.max(0,a-20),c=Math.min(o.length,a+i.length+20),l=o.substring(s,c);if(t.includes(l)||t.push(l),a+=i.length,t.length>=3)break}if(t.length>=3)break}return t}k();var Rr=(o,e)=>o==="all"||o===e,dn=class extends x{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:rl,streaming:!1,timeout:3e5};bridge=null;searchService=null;async getBridge(e){if(!this.bridge){let t=e.memory??await F();this.bridge=new mi(new Gr,t,{publishEvents:!1,enableC4Embeddings:!0,relationshipResolver:pi(n=>new Pt(t,{basePath:n}))})}return this.bridge}async getSearchService(e){if(!this.searchService){let t=e.memory??await F();this.searchService=new di(t,{enableEmbeddings:!0})}return this.searchService}async execute(e,t){let{action:n,projectPath:r=".",level:i="all",query:a,limit:s=10}=e;try{if(this.isAborted(t))return{success:!1,error:"Operation aborted"};let c={action:n};switch(n){case"generate":{let u=await(await this.getBridge(t)).requestC4Diagrams({projectPath:r,includeContext:Rr(i,"context"),includeContainer:Rr(i,"container"),includeComponent:Rr(i,"component"),includeDependency:i==="all",analyzeComponents:!0,detectExternalSystems:!0,analyzeCoupling:!0});if(!u.success)return{success:!1,error:S(u.error)};let d=u.value;c.generateResult={diagrams:d.diagrams,confidence:d.metadata.analysisMetadata?.confidence,componentsDetected:d.components.length,externalSystemsDetected:d.externalSystems.length,relationshipsDetected:d.relationships.length,circularDependencies:(d.couplingAnalysis??[]).filter(m=>m.isCircular).length};break}case"search":{if(!a)return{success:!1,error:"Query is required for search action"};let u=await(await this.getSearchService(t)).searchDiagrams(a,s);if(!u.success)return{success:!1,error:S(u.error)};c.searchResult={results:u.value.map(d=>({key:d.key,type:d.type,title:d.title,score:d.score,preview:d.preview})),total:u.value.length};break}default:return{success:!1,error:`Unknown action: ${n}`}}return{success:!0,data:c}}catch(c){return{success:!1,error:S(c)}}}},rl={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();Q();var ia=[{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"}],mn=class extends x{config={name:"qe/security/scan",description:"Comprehensive security scanning including SAST, DAST, dependency analysis, and compliance validation.",domain:"security-compliance",schema:il,streaming:!0,timeout:6e5};async execute(e,t){let{target:n=".",scanType:r=["sast","dependency"],compliance:i=[],dastUrl:a,depth:s="standard",failOnSeverity:c="critical"}=e,l=Date.now();try{if(this.emitStream(t,{status:"scanning",message:`Starting security scan (${r.join(", ")})`,depth:s}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let u=await ol(n,s);this.emitStream(t,{status:"discovered",message:`Found ${u.length} files to scan`});let d=[];if(r.includes("sast")||r.includes("secret")){this.emitStream(t,{status:"sast",message:"Running static analysis"});let f=await cl(u,r);d.push(...f)}if(r.includes("dependency")){this.emitStream(t,{status:"dependency",message:"Scanning dependencies"});let f=await ll(n);d.push(...f)}r.includes("dast")&&a&&(this.emitStream(t,{status:"dast",message:`Scanning ${a}`}),d.push(...fl(a)));let m=i.map(f=>yl(f,d)),p={critical:d.filter(f=>f.severity==="critical").length,high:d.filter(f=>f.severity==="high").length,medium:d.filter(f=>f.severity==="medium").length,low:d.filter(f=>f.severity==="low").length,informational:d.filter(f=>f.severity==="informational").length,totalFiles:u.length,scanDurationMs:Date.now()-l},g=["critical","high","medium","low","informational"],h=g.indexOf(c),v=(d.length>0?Math.min(...d.map(f=>g.indexOf(f.severity))):g.length)>h;return await Rt(await xt(t),{securityVulnerabilities:d.length},{measuredAt:new Date().toISOString(),source:"qe/security/scan"}),this.emitStream(t,{status:"complete",message:`Scan complete: ${d.length} vulnerabilities found in ${u.length} files`,progress:100}),{success:!0,data:{scanId:t.requestId,summary:p,vulnerabilities:d,complianceResults:m.length>0?m:void 0,recommendations:vl(d,p),passed:v}}}catch(u){return{success:!1,error:`Security scan failed: ${S(u)}`}}}},il={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"}}},sl=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"]),al=new Set(["node_modules",".git","__pycache__",".venv","venv","dist","build",".next",".nuxt","coverage",".tox"]);async function ol(o,e){let t=await import("fs"),n=await import("path"),r=n.resolve(o),i=[],a=e==="quick"?50:e==="standard"?500:2e3,s=e==="quick"?3:e==="standard"?8:20;function c(l,u){if(i.length>=a||u>s)return;let d;try{d=t.readdirSync(l,{withFileTypes:!0})}catch{return}for(let m of d){if(i.length>=a)break;let p=n.join(l,m.name);if(m.isDirectory()){let g=new Set([".github",".docker",".aws",".circleci",".gitlab"]);al.has(m.name)||m.name.startsWith(".")&&!g.has(m.name)||c(p,u+1)}else if(m.isFile()){let g=n.extname(m.name).toLowerCase();(sl.has(g)||m.name==="Dockerfile"||m.name==="Makefile"||m.name.startsWith(".env"))&&i.push(p)}}}try{t.statSync(r).isFile()?i.push(r):c(r,0)}catch{}return i}async function cl(o,e){let t=await import("fs"),n=await import("path"),r=[],i=0,a=[];if(e.includes("sast")){for(let s of hi)a.push({id:s.id,pattern:new RegExp(s.pattern.source,s.pattern.flags),severity:s.severity,title:s.title,description:s.description,cweId:s.cweId,remediation:s.remediation,category:s.category});for(let s of ia)a.push({id:s.id,pattern:new RegExp(s.pattern.source,s.pattern.flags),severity:s.severity,title:s.title,description:s.description,cweId:s.cweId,remediation:s.remediation,category:"sensitive-data"})}if(e.includes("secret")){for(let s of gi)a.some(c=>c.id===s.id)||a.push({id:s.id,pattern:new RegExp(s.pattern.source,s.pattern.flags),severity:s.severity,title:s.title,description:s.description,cweId:s.cweId,remediation:s.remediation,category:s.category});for(let s of ia)a.some(c=>c.id===s.id)||a.push({...s,category:"sensitive-data"})}for(let s of o){let c;try{c=t.readFileSync(s,"utf-8")}catch{continue}if(c.includes("\0")||c.length>1e6)continue;let l=c.split(`
622
+ Analyze the requirements above and return the complete QualityCriteriaAnalysis.`}resetInstanceCache(){this.service=null}},dl={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"]},Gy=new it;k();import*as Or from"fs";import*as he from"path";var pn=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:ml,streaming:!0,timeout:3e5};knowledgeGraph=null;semanticAnalyzer=null;impactAnalyzer=null;async getKnowledgeGraph(e){if(!this.knowledgeGraph){let t=e.memory??await N(),n=await z(e);this.knowledgeGraph=new kt({memory:t,llmRouter:n})}return this.knowledgeGraph}async getSemanticAnalyzer(e){if(!this.semanticAnalyzer){let t=e.memory;this.semanticAnalyzer=new bi(t||await N())}return this.semanticAnalyzer}async getImpactAnalyzer(e){if(!this.impactAnalyzer){let t=e.memory,n=await this.getKnowledgeGraph(e);this.impactAnalyzer=new Ci(t||await N(),n)}return this.impactAnalyzer}async execute(e,t){let{action:n,paths:r=["."],query:i,changedFiles:a=[],depth:s=3,incremental:c=!1}=e;try{if(this.emitStream(t,{status:"processing",message:`Executing ${n} action`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let l={action:n};switch(n){case"index":l.indexResult=await this.executeIndex(r,c,t);break;case"search":if(!i)return{success:!1,error:"Query is required for search action"};l.searchResult=await this.executeSearch(i,r,t);break;case"impact":if(a.length===0)return{success:!1,error:"changedFiles is required for impact action"};l.impactResult=await this.executeImpact(a,s,t);break;case"dependencies":l.dependencyResult=await this.executeDependencies(r,s,t);break;default:return{success:!1,error:`Unknown action: ${n}`}}return this.emitStream(t,{status:"complete",message:`${n} complete`,progress:100}),{success:!0,data:l}}catch(l){return{success:!1,error:`Code analysis failed: ${S(l)}`}}}async executeIndex(e,t,n){this.emitStream(n,{status:"indexing",message:`Indexing ${e.length} paths (${t?"incremental":"full"})`});let r=await this.getKnowledgeGraph(n),i=await this.expandPaths(e),a=await r.index({paths:i,incremental:t,includeTests:!0,languages:["typescript","javascript"]});if(!a.success)throw new Error(a.error?.message||"Indexing failed");return{filesIndexed:a.value.filesIndexed,nodesCreated:a.value.nodesCreated,edgesCreated:a.value.edgesCreated,duration:a.value.duration,errors:a.value.errors}}async executeSearch(e,t,n){let r=Date.now();if(this.isDemoMode(n)){let l=Date.now()-r;return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoSearchResult(e,l)}this.emitStream(n,{status:"searching",message:`Searching for: ${e}`});let a=await(await this.getSemanticAnalyzer(n)).search({query:e,type:"semantic",limit:20,scope:t.length>0&&t[0]!=="."?t:void 0}),s=Date.now()-r;return a.success?a.value.results.length===0?(this.markAsRealData(),{results:[],total:0,searchTime:s}):(this.markAsRealData(),{results:a.value.results.map(l=>({file:l.file,line:l.line,snippet:l.snippet.substring(0,200)+(l.snippet.length>200?"...":""),score:l.score,highlights:pl(l.snippet,e)})),total:a.value.total,searchTime:s}):{results:[],total:0,searchTime:s}}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 a=i.value;return{directImpact:a.directImpact,transitiveImpact:a.transitiveImpact,impactedTests:a.impactedTests,riskLevel:a.riskLevel,recommendations:a.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),a=await r.mapDependencies({files:i,direction:"both",depth:t});if(!a.success)throw new Error(a.error?.message||"Dependency mapping failed");let s=a.value,c=s.nodes.map(u=>({id:u.id,path:u.path,type:u.type,inDegree:u.inDegree,outDegree:u.outDegree})),l=s.edges.map(u=>({source:u.source,target:u.target,type:u.type}));return{nodes:c,edges:l,cycles:s.cycles,metrics:{totalNodes:s.metrics.totalNodes,totalEdges:s.metrics.totalEdges,avgDegree:s.metrics.avgDegree,maxDepth:s.metrics.maxDepth}}}async expandPaths(e){let t=[];for(let n of e){let r=he.isAbsolute(n)?n:he.resolve(process.cwd(),n);try{let i=await Or.promises.stat(r);if(i.isDirectory()){let a=await this.findSourceFiles(r);t.push(...a)}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 Or.promises.readdir(e,{withFileTypes:!0});for(let a of i){let s=he.join(e,a.name);if(a.isDirectory()){if(!r.includes(a.name)){let c=await this.findSourceFiles(s);t.push(...c)}}else if(a.isFile()){let c=he.extname(a.name);n.includes(c)&&t.push(s)}}}catch{}return t}},ml={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 pl(o,e){let t=[],n=e.toLowerCase().split(/\s+/),r=o.toLowerCase();for(let i of n){if(i.length<2)continue;let a=0;for(;(a=r.indexOf(i,a))!==-1;){let s=Math.max(0,a-20),c=Math.min(o.length,a+i.length+20),l=o.substring(s,c);if(t.includes(l)||t.push(l),a+=i.length,t.length>=3)break}if(t.length>=3)break}return t}k();var Nr=(o,e)=>o==="all"||o===e,gn=class extends x{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:gl,streaming:!1,timeout:3e5};bridge=null;searchService=null;async getBridge(e){if(!this.bridge){let t=e.memory??await N();this.bridge=new Si(new Kr,t,{publishEvents:!1,enableC4Embeddings:!0,relationshipResolver:Ei(n=>new kt(t,{basePath:n}))})}return this.bridge}async getSearchService(e){if(!this.searchService){let t=e.memory??await N();this.searchService=new Ti(t,{enableEmbeddings:!0})}return this.searchService}async execute(e,t){let{action:n,projectPath:r=".",level:i="all",query:a,limit:s=10}=e;try{if(this.isAborted(t))return{success:!1,error:"Operation aborted"};let c={action:n};switch(n){case"generate":{let u=await(await this.getBridge(t)).requestC4Diagrams({projectPath:r,includeContext:Nr(i,"context"),includeContainer:Nr(i,"container"),includeComponent:Nr(i,"component"),includeDependency:i==="all",analyzeComponents:!0,detectExternalSystems:!0,analyzeCoupling:!0});if(!u.success)return{success:!1,error:S(u.error)};let d=u.value;c.generateResult={diagrams:d.diagrams,confidence:d.metadata.analysisMetadata?.confidence,componentsDetected:d.components.length,externalSystemsDetected:d.externalSystems.length,relationshipsDetected:d.relationships.length,circularDependencies:(d.couplingAnalysis??[]).filter(m=>m.isCircular).length};break}case"search":{if(!a)return{success:!1,error:"Query is required for search action"};let u=await(await this.getSearchService(t)).searchDiagrams(a,s);if(!u.success)return{success:!1,error:S(u.error)};c.searchResult={results:u.value.map(d=>({key:d.key,type:d.type,title:d.title,score:d.score,preview:d.preview})),total:u.value.length};break}default:return{success:!1,error:`Unknown action: ${n}`}}return{success:!0,data:c}}catch(c){return{success:!1,error:S(c)}}}},gl={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();Q();var ga=[{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"}],hn=class extends x{config={name:"qe/security/scan",description:"Comprehensive security scanning including SAST, DAST, dependency analysis, and compliance validation.",domain:"security-compliance",schema:hl,streaming:!0,timeout:6e5};async execute(e,t){let{target:n=".",scanType:r=["sast","dependency"],compliance:i=[],dastUrl:a,depth:s="standard",failOnSeverity:c="critical"}=e,l=Date.now();try{if(this.emitStream(t,{status:"scanning",message:`Starting security scan (${r.join(", ")})`,depth:s}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let u=await vl(n,s);this.emitStream(t,{status:"discovered",message:`Found ${u.length} files to scan`});let d=[];if(r.includes("sast")||r.includes("secret")){this.emitStream(t,{status:"sast",message:"Running static analysis"});let f=await bl(u,r);d.push(...f)}if(r.includes("dependency")){this.emitStream(t,{status:"dependency",message:"Scanning dependencies"});let f=await Cl(n);d.push(...f)}r.includes("dast")&&a&&(this.emitStream(t,{status:"dast",message:`Scanning ${a}`}),d.push(...xl(a)));let m=i.map(f=>Al(f,d)),p={critical:d.filter(f=>f.severity==="critical").length,high:d.filter(f=>f.severity==="high").length,medium:d.filter(f=>f.severity==="medium").length,low:d.filter(f=>f.severity==="low").length,informational:d.filter(f=>f.severity==="informational").length,totalFiles:u.length,scanDurationMs:Date.now()-l},g=["critical","high","medium","low","informational"],h=g.indexOf(c),v=(d.length>0?Math.min(...d.map(f=>g.indexOf(f.severity))):g.length)>h;return await At(await Mt(t),{securityVulnerabilities:d.length},{measuredAt:new Date().toISOString(),source:"qe/security/scan"}),this.emitStream(t,{status:"complete",message:`Scan complete: ${d.length} vulnerabilities found in ${u.length} files`,progress:100}),{success:!0,data:{scanId:t.requestId,summary:p,vulnerabilities:d,complianceResults:m.length>0?m:void 0,recommendations:kl(d,p),passed:v}}}catch(u){return{success:!1,error:`Security scan failed: ${S(u)}`}}}},hl={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"}}},fl=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"]),yl=new Set(["node_modules",".git","__pycache__",".venv","venv","dist","build",".next",".nuxt","coverage",".tox"]);async function vl(o,e){let t=await import("fs"),n=await import("path"),r=n.resolve(o),i=[],a=e==="quick"?50:e==="standard"?500:2e3,s=e==="quick"?3:e==="standard"?8:20;function c(l,u){if(i.length>=a||u>s)return;let d;try{d=t.readdirSync(l,{withFileTypes:!0})}catch{return}for(let m of d){if(i.length>=a)break;let p=n.join(l,m.name);if(m.isDirectory()){let g=new Set([".github",".docker",".aws",".circleci",".gitlab"]);yl.has(m.name)||m.name.startsWith(".")&&!g.has(m.name)||c(p,u+1)}else if(m.isFile()){let g=n.extname(m.name).toLowerCase();(fl.has(g)||m.name==="Dockerfile"||m.name==="Makefile"||m.name.startsWith(".env"))&&i.push(p)}}}try{t.statSync(r).isFile()?i.push(r):c(r,0)}catch{}return i}async function bl(o,e){let t=await import("fs"),n=await import("path"),r=[],i=0,a=[];if(e.includes("sast")){for(let s of Ri)a.push({id:s.id,pattern:new RegExp(s.pattern.source,s.pattern.flags),severity:s.severity,title:s.title,description:s.description,cweId:s.cweId,remediation:s.remediation,category:s.category});for(let s of ga)a.push({id:s.id,pattern:new RegExp(s.pattern.source,s.pattern.flags),severity:s.severity,title:s.title,description:s.description,cweId:s.cweId,remediation:s.remediation,category:"sensitive-data"})}if(e.includes("secret")){for(let s of wi)a.some(c=>c.id===s.id)||a.push({id:s.id,pattern:new RegExp(s.pattern.source,s.pattern.flags),severity:s.severity,title:s.title,description:s.description,cweId:s.cweId,remediation:s.remediation,category:s.category});for(let s of ga)a.some(c=>c.id===s.id)||a.push({...s,category:"sensitive-data"})}for(let s of o){let c;try{c=t.readFileSync(s,"utf-8")}catch{continue}if(c.includes("\0")||c.length>1e6)continue;let l=c.split(`
623
623
  `),u=n.relative(process.cwd(),s);for(let d of a){let m=new RegExp(d.pattern.source,d.pattern.flags),p;for(;(p=m.exec(c))!==null;){i++;let g=c.substring(0,p.index).split(`
624
- `).length,h=l[g-1]||"",y=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:u,line:g,snippet:y},description:d.description,remediation:d.remediation,cweId:d.cweId,references:[]}),i>200)break}}}return r}async function ll(o){let e=await import("fs"),t=await import("path"),n=[],r=t.resolve(o),i=t.join(r,"package.json");if(e.existsSync(i))try{let c=A(e.readFileSync(i,"utf-8")),l={...c.dependencies,...c.devDependencies};n.push(...dl(l,"package.json"))}catch{}let a=t.join(r,"pyproject.toml");if(e.existsSync(a))try{let c=e.readFileSync(a,"utf-8"),l=pl(c);n.push(...sa(l,"pyproject.toml"))}catch{}let s=t.join(r,"requirements.txt");if(e.existsSync(s))try{let c=e.readFileSync(s,"utf-8"),l=gl(c);n.push(...sa(l,"requirements.txt"))}catch{}if(n.length===0){let c=[i,a,s].filter(l=>e.existsSync(l));c.length>0&&n.push({id:"DEP-INFO-001",title:"Dependency audit recommended",severity:"informational",category:"vulnerable-components",location:{file:t.relative(process.cwd(),c[0])},description:`Found ${t.basename(c[0])} \u2014 run language-specific dependency audit for comprehensive results`,remediation:"Run npm audit, pip-audit, or equivalent for full vulnerability check",references:[]})}return n}var ul={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 dl(o,e){let t=[];for(let[n,r]of Object.entries(o)){let i=ul[n];if(i){let a=r.replace(/^[\^~>=<]+/,"");hl(a,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:a}},description:i.desc,remediation:`Upgrade ${n} to >= ${i.maxSafe}`,cveId:i.cve,references:[`https://nvd.nist.gov/vuln/detail/${i.cve}`]})}}return t}var ml={"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 pl(o){let e=[],t=o.match(/dependencies\s*=\s*\[([\s\S]*?)\]/);if(t){let n=t[1].matchAll(/["']([a-zA-Z0-9_-]+)/g);for(let r of n)e.push(r[1].toLowerCase())}return e}function gl(o){return o.split(`
625
- `).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")).map(e=>e.split(/[>=<!~\[]/)[0].trim().toLowerCase()).filter(Boolean)}function sa(o,e){let t=[];for(let n of o){let r=ml[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 hl(o,e){let t=o.split(".").map(Number),n=e.split(".").map(Number);for(let r=0;r<3;r++){let i=t[r]||0,a=n[r]||0;if(i<a)return-1;if(i>a)return 1}return 0}function fl(o){return[{id:"DAST-INFO-001",title:"DAST scan target noted",severity:"informational",category:"security-misconfiguration",location:{file:o},description:`DAST target ${o} recorded. Full DAST requires integration with a dynamic scanner (e.g., ZAP, Burp).`,remediation:"Configure a DAST tool to scan the live application",references:["https://owasp.org/www-project-zap/"]}]}function yl(o,e){let t=e.filter(n=>o==="owasp"?!0:o==="pci-dss"?n.category==="injection"||n.category==="sensitive-data":o==="gdpr"?n.category==="sensitive-data":!1);return{standard:o,passed:t.filter(n=>n.severity==="critical"||n.severity==="high").length===0,score:Math.max(0,100-t.length*15),violations:t.map(n=>({ruleId:n.id,ruleName:n.title,location:n.location,details:n.description,remediation:n.remediation}))}}function vl(o,e){let t=[];return e.critical>0&&t.push("URGENT: Address critical vulnerabilities immediately"),e.high>0&&t.push("Prioritize high-severity issues in next sprint"),o.some(n=>n.category==="injection")&&t.push("Review input validation across the application"),o.some(n=>n.category==="sensitive-data")&&t.push("Implement proper secrets management"),o.some(n=>n.category==="vulnerable-components")&&t.push("Run full dependency audit and update vulnerable packages"),t.length===0&&t.push("No critical issues found. Continue regular security reviews."),t}Q();k();function aa(o){try{let e=new URL(o);if(!["http:","https:"].includes(e.protocol))return{valid:!1,error:`Invalid protocol: ${e.protocol}. Only http/https allowed.`};let t=e.hostname.toLowerCase(),n=[/^localhost$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2[0-9]|3[01])\./,/^192\.168\./,/^0\.0\.0\.0$/,/^\[::1\]$/,/^169\.254\./];for(let r of n)if(r.test(t))return{valid:!1,error:`Blocked hostname: ${t}. Cannot access internal/private addresses.`};return{valid:!0}}catch{return{valid:!1,error:`Invalid URL format: ${o}`}}}var pn=class extends x{config={name:"qe/contracts/validate",description:"Validate API contracts, detect breaking changes, and verify provider-consumer compatibility.",domain:"contract-testing",schema:bl,streaming:!0,timeout:18e4};contractValidator=null;apiCompatibility=null;async getServices(e){if(!this.contractValidator||!this.apiCompatibility){let t=e.memory||await F(),n=await z(e);this.contractValidator=new fi({memory:t,llmRouter:n}),this.apiCompatibility=new yi(t)}return{contractValidator:this.contractValidator,apiCompatibility:this.apiCompatibility}}async execute(e,t){let{contractPath:n,contractContent:r,providerUrl:i,consumerName:a,baselineVersion:s,baselineContent:c,checkBreakingChanges:l=!0,format:u="openapi"}=e,{contractValidator:d,apiCompatibility:m}=await this.getServices(t);try{if(!n&&!r)return{success:!1,error:"Either contractPath or contractContent is required"};if(this.emitStream(t,{status:"validating",message:`Validating ${u} contract`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let p=r||n||"",g=[],h,y,v;if(u==="openapi"){let b=await d.validateOpenAPI(p);if(b.success){let E=b.value;for(let w of E.errors)g.push({path:w.path,message:w.message,code:w.code,severity:"error"});for(let w of E.warnings)g.push({path:"",message:w,code:"WARNING",severity:"warning"});this.emitStream(t,{status:"analyzed",message:`Found ${E.endpointCount} endpoints, ${E.schemaCount} schemas`})}}else{let b=this.buildContractFromContent(p,u,a),E=await d.validateContract(b);if(E.success){let w=E.value;for(let T of w.errors)g.push(this.convertValidationError(T));for(let T of w.warnings)g.push({path:"",message:T,code:"WARNING",severity:"warning"})}}if(l&&(s||c)){this.emitStream(t,{status:"comparing",message:"Detecting breaking changes"});let b=this.buildContractFromContent(p,u,a),E=this.buildContractFromContent(c||p,u,a,s),w=await m.compareVersions(E,b);w.success?(h=w.value.breakingChanges.map(T=>this.convertBreakingChange(T)),v={isBackwardCompatible:w.value.isCompatible,breakingChangeCount:w.value.breakingChanges.length,nonBreakingChangeCount:w.value.nonBreakingChanges.length,deprecations:w.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"}),y=await this.verifyAgainstProvider(i,a||"default",p,u,d));let f=g.filter(b=>b.severity==="error").length===0,C=this.generateRecommendations(g,h,y);return this.emitStream(t,{status:"complete",message:f?"Contract is valid":`Found ${g.length} issues`,progress:100}),{success:!0,data:{isValid:f,validationErrors:g,breakingChanges:h,verificationResult:y,compatibility:v,recommendations:C}}}catch(p){return{success:!1,error:`Contract validation failed: ${S(p)}`}}}buildContractFromContent(e,t,n,r){let i=`contract-${Date.now()}`,a=Jr.parse(r||"1.0.0"),s=[],c=[];if(t==="openapi")try{let l=A(e),d=l.components?.schemas||{};for(let[p,g]of Object.entries(d))s.push({id:p,name:p,type:"openapi",content:JSON.stringify(g)});let m=l.paths||{};for(let[p,g]of Object.entries(m))if(typeof g=="object"&&g!==null){let h=g,y=["get","post","put","patch","delete","head","options"];for(let v of y)v in h&&c.push({path:p,method:v.toUpperCase(),examples:[]})}}catch{}else if(t==="graphql")s.push({id:"graphql-schema",name:"GraphQL Schema",type:"graphql",content:e});else if(t==="pact")try{let u=A(e).interactions||[];for(let d of u){let m=d.request;m&&c.push({path:m.path||"/",method:(m.method||"GET").toUpperCase(),examples:[]})}}catch{}return{id:i,name:`${t}-contract`,version:a,type:t,provider:{name:"provider",version:"1.0.0"},consumers:[{name:n||"default",version:"1.0.0"}],endpoints:c,schemas:s}}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 a=[],s=[],c=aa(e);if(!c.valid)return{provider:e,consumer:t,passed:!1,failures:[{endpoint:e,type:"validation-error",expected:"Valid HTTP/HTTPS URL",actual:c.error||"Invalid URL",message:`Provider URL validation failed: ${c.error}`}],warnings:[]};let l=this.buildContractFromContent(n,r,t);for(let u of l.endpoints)try{let d=`${e}${u.path}`,m=aa(d);if(!m.valid){a.push({endpoint:`${u.method} ${u.path}`,type:"validation-error",expected:"Valid URL",actual:m.error||"Invalid URL",message:`URL validation failed: ${m.error}`});continue}let p=await fetch(d,{method:u.method==="GET"?"GET":"OPTIONS",headers:{Accept:"application/json"}});if(!p.ok&&p.status!==405&&(p.status===404?a.push({endpoint:`${u.method} ${u.path}`,type:"missing-endpoint",expected:"Endpoint should exist",actual:`Got ${p.status}`,message:"Endpoint not found at provider"}):s.push({endpoint:`${u.method} ${u.path}`,message:`Unexpected status ${p.status}`,severity:"medium"})),u.responseSchema&&p.ok){let g=await p.json(),h=l.schemas.find(y=>y.id===u.responseSchema);if(h){let y=await i.validateResponse(g,h);if(y.success&&!y.value.isValid)for(let v of y.value.errors)a.push({endpoint:`${u.method} ${u.path}`,type:"schema-mismatch",expected:`Schema ${u.responseSchema}`,actual:v.message,message:`Response does not match schema: ${v.message}`})}}}catch(d){s.push({endpoint:`${u.method} ${u.path}`,message:`Failed to verify: ${S(d)}`,severity:"high"})}return{provider:e,consumer:t,passed:a.length===0,failures:a,warnings:s}}generateRecommendations(e,t,n){let r=[],i=e.filter(s=>s.severity==="error").length;if(i>0&&r.push(`Fix ${i} validation error${i>1?"s":""} before deploying`),t&&t.length>0){let s=t.filter(c=>c.impact==="high").length;s>0&&r.push(`Address ${s} high-impact breaking change${s>1?"s":""} before release`),r.push("Coordinate with affected consumers before releasing breaking changes"),r.push("Consider versioning the API to maintain backward compatibility")}n&&(n.passed||(r.push(`Provider verification failed with ${n.failures.length} failure${n.failures.length>1?"s":""}`),n.failures.filter(l=>l.type==="missing-endpoint").length>0&&r.push("Ensure all contract endpoints are implemented in the provider"),n.failures.filter(l=>l.type==="schema-mismatch").length>0&&r.push("Update provider responses to match the contract schema")),n.warnings.length>0&&n.warnings.filter(c=>c.severity==="high").length>0&&r.push("Investigate high-severity verification warnings"));let a=e.filter(s=>s.severity==="warning").length;return a>0&&r.push(`Review ${a} warning${a>1?"s":""} for potential issues`),r.length===0&&r.push("Contract is valid and backward compatible"),r}},bl={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 gn=class extends x{config={name:"qe/visual/compare",description:"Visual regression testing with screenshot comparison, diff detection, and baseline management.",domain:"visual-accessibility",schema:Cl,streaming:!0,timeout:3e5};visualTester=null;async getService(e){if(!this.visualTester){let t=e.memory??await F(),n=await z(e);this.visualTester=vi({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:a=.1,fullPage:s=!0}=e;try{if(this.emitStream(t,{status:"capturing",message:`Capturing ${n.length} URLs across ${r.length} viewports`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};this.markAsRealData();let c=await this.getService(t),l=[],u=[];for(let m of n)for(let p of r){this.emitStream(t,{status:"comparing",message:`Comparing ${m} at ${p.width}x${p.height}`});let g={width:p.width,height:p.height,deviceScaleFactor:1,isMobile:p.isMobile||!1,hasTouch:p.isMobile||!1},h=await c.captureScreenshot(m,{viewport:g,fullPage:s});if(!h.success){l.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let y=h.value,v=await c.getBaseline(m,g);if(!v)await c.setBaseline(y),u.push(y.path.value),l.push({url:m,viewport:p,status:"new",diffPercentage:0,diffPixels:0,screenshotPath:y.path.value});else{let f=await c.compare(y,v.id);if(!f.success){l.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let C=f.value,b=C.diffPercentage<=a;l.push({url:m,viewport:p,status:b?"passed":"failed",diffPercentage:C.diffPercentage,diffPixels:C.diffPixels,screenshotPath:y.path.value,baselinePath:v.path.value,diffImagePath:C.diffImagePath?.value,regions:C.regions?.map(E=>({x:E.x,y:E.y,width:E.width,height:E.height,changeType:E.changeType,significance:E.significance}))})}}let d={total:l.length,passed:l.filter(m=>m.status==="passed").length,failed:l.filter(m=>m.status==="failed").length,new:l.filter(m=>m.status==="new").length,avgDiffPercentage:l.length>0?l.reduce((m,p)=>m+p.diffPercentage,0)/l.length:0};return this.emitStream(t,{status:"complete",message:`Visual comparison complete: ${d.passed}/${d.total} passed`,progress:100}),{success:!0,data:{comparisons:l,summary:d,newBaselines:u,recommendations:El(l,d)}}}catch(c){return{success:!1,error:`Visual comparison failed: ${S(c)}`}}}},hn=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:Tl,streaming:!0,timeout:18e4};accessibilityTester=null;async getService(e){if(!this.accessibilityTester){let t=e.memory;this.accessibilityTester=new bi(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:a=!0,checkKeyboard:s=!0}=e;try{if(this.emitStream(t,{status:"auditing",message:`Auditing ${n.length} URLs against ${r}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};this.markAsRealData();let c=await this.getService(t),l=[],u=Sl(r);for(let g of n){this.emitStream(t,{status:"scanning",message:`Scanning ${g}`});let h=await c.audit(g,{wcagLevel:u,includeWarnings:i});if(!h.success){l.push({url:g,score:0,passed:!1,violations:[],warnings:[],passedRules:0});continue}let y=h.value,v=[];if(a){let w=await c.checkContrast(g);if(w.success){let T=w.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 f=[];if(s){let w=await c.checkKeyboardNavigation(g);if(w.success){let T=w.value;for(let P of T.issues)f.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)f.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=[...y.violations.map(w=>({id:w.id,impact:w.impact,description:w.description,help:w.help,helpUrl:w.helpUrl,wcagCriteria:w.wcagCriteria.map(T=>T.id),nodes:w.nodes.map(T=>({selector:T.selector,html:T.html,failureSummary:T.failureSummary,fixSuggestion:T.fixSuggestion}))})),...v,...f],b=y.incomplete.map(w=>({id:w.id,description:w.description,nodes:w.nodes.length})),E=C.some(w=>w.impact==="critical"||w.impact==="serious");l.push({url:g,score:y.score,passed:!E,violations:C,warnings:b,passedRules:y.passes.length})}let d={totalUrls:l.length,passingUrls:l.filter(g=>g.passed).length,avgScore:l.length>0?Math.round(l.reduce((g,h)=>g+h.score,0)/l.length):0,criticalViolations:l.reduce((g,h)=>g+h.violations.filter(y=>y.impact==="critical").length,0),seriousViolations:l.reduce((g,h)=>g+h.violations.filter(y=>y.impact==="serious").length,0),totalViolations:l.reduce((g,h)=>g+h.violations.length,0)},m=wl(l),p=Rl(m);return this.emitStream(t,{status:"complete",message:`Audit complete: avg score ${d.avgScore}%`,progress:100}),{success:!0,data:{audits:l,summary:d,topIssues:m,remediationPlan:p}}}catch(c){return{success:!1,error:`Accessibility audit failed: ${S(c)}`}}}},Cl={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"]},Tl={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 Sl(o){return o==="wcag21-aaa"?"AAA":"AA"}function El(o,e){let t=[];return e.failed>0&&t.push(`Review ${e.failed} failed comparisons for intentional vs unintentional changes`),e.new>0&&t.push(`${e.new} new baselines created - review and approve if correct`),e.avgDiffPercentage>1&&t.push("Consider increasing diff threshold or reviewing major changes"),t.length>0?t:["All visual tests passed"]}function wl(o){let e=new Map;for(let t of o)for(let n of t.violations){let r=e.get(n.id);r?(r.occurrences++,r.affectedUrls.includes(t.url)||r.affectedUrls.push(t.url)):e.set(n.id,{ruleId:n.id,description:n.description,occurrences:1,impact:n.impact,affectedUrls:[t.url]})}return Array.from(e.values()).sort((t,n)=>n.occurrences-t.occurrences)}function Rl(o){return o.map((e,t)=>({violationId:e.ruleId,description:e.description,fix:`Fix ${e.ruleId} across ${e.occurrences} occurrences`,effort:e.occurrences>10?"moderate":"minor",priority:t+1}))}k();var fn=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:Pl,streaming:!0,timeout:3e5};chaosEngineer=null;async getService(e){if(!this.chaosEngineer){let t=e.memory||await F(),n=await z(e);this.chaosEngineer=new Ci({memory:t,llmRouter:n},{enableDryRun:!0,autoRollbackOnFailure:!0})}return this.chaosEngineer}async execute(e,t){let{faultType:n,target:r,duration:i=3e4,intensity:a=50,dryRun:s=!0,hypothesis:c,rollbackOnFailure:l=!0}=e,u=await this.getService(t);try{if(this.emitStream(t,{status:"preparing",message:`Preparing ${n} fault injection on ${r}`,dryRun:s}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let d=t.requestId||q(),m=this.buildExperiment(d,n,r,i,a,c,l);this.emitStream(t,{status:"verifying",message:"Verifying steady state"});let p=await u.verifySteadyState(m.steadyState),g=p.success&&p.value;if(!g&&!s)return{success:!1,error:"Steady state verification failed. System not in healthy state for chaos experiment."};let h=await u.createExperiment(m);if(!h.success)return{success:!1,error:`Failed to create experiment: ${h.error.message}`};this.emitStream(t,{status:"injecting",message:s?`[DRY RUN] Simulating ${n} fault`:`Injecting ${n} fault`});let y=!1,v,f="pending",C=[],b={faultDuration:i,targetAffected:!s};if(s)y=!1,f="completed",b=this.simulateMetrics(n,i,a),c&&(v=this.validateHypothesisText(c,b,C));else{let T=await u.runExperiment(d);if(T.success){let P=T.value;y=P.faultResults.some(O=>O.injected),v=P.hypothesisValidated,f=P.status;for(let O of P.incidents)C.push(this.convertIncident(O));b=this.extractMetrics(P,n,i)}else f="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 E=this.collectIntensityIncidents(n,a,s);C.push(...E),!s&&C.some(T=>T.severity==="critical"&&!T.resolved)&&(f=l?"rolled-back":"failed");let w=this.generateRecommendations(n,b,C,v);return this.emitStream(t,{status:"complete",message:`Chaos experiment ${f}`,progress:100}),{success:!0,data:{experimentId:d,status:f,faultInjected:y,hypothesisValidated:v,steadyStateVerified:g,metrics:b,incidents:C,recommendations:w}}}catch(d){return{success:!1,error:`Chaos injection failed: ${S(d)}`}}}buildExperiment(e,t,n,r,i,a,s=!0){let c={id:`fault-${e}`,type:t,target:{type:"service",selector:n},duration:r,parameters:this.buildFaultParameters(t,i)},l={description:`Steady state for ${n}`,probes:[{name:"target-health",type:n.startsWith("http")?"http":"command",target:n.startsWith("http")?n:`echo "checking ${n}"`,expected:n.startsWith("http")?200:"OK",timeout:5e3}]},u=a||`System should remain stable under ${t} fault`;return{id:e,name:`${t}-experiment-${Date.now()}`,description:`Chaos experiment: ${t} on ${n}`,hypothesis:{statement:u,metrics:[{metric:t==="latency"?"response_time":"error_rate",operator:"lt",value:t==="latency"?5e3:50}],tolerances:[{metric:"availability",maxDeviation:20,unit:"percent"}]},steadyState:l,faults:[c],blastRadius:{scope:"single",maxAffected:1,excludeProduction:!0},rollbackPlan:{automatic:s,triggerConditions:[{type:"error-rate",condition:"error_rate > 50%"}],steps:[{order:1,action:"remove-fault",target:c.id,timeout:1e4}]},schedule:{type:"once"}}}buildFaultParameters(e,t){let n={};switch(e){case"latency":n.latencyMs=100+t*20;break;case"error":n.errorCode=500,n.errorRate=t/100;break;case"timeout":n.timeoutMs=5e3+t*250;break;case"cpu-stress":n.cpuPercent=t,n.cores=Math.max(1,Math.floor(t/25));break;case"memory-stress":n.memoryBytes=t/100*512*1024*1024;break;case"network-partition":n.partitionPercent=t;break;case"packet-loss":n.packetLossPercent=t;break;case"dns-failure":n.failureRate=t/100;break;case"process-kill":n.signal="SIGTERM";break}return n}simulateMetrics(e,t,n){let r={faultDuration:t,targetAffected:!1,recoveryTime:5e3+n*100};switch(e){case"latency":r.latencyP99=100+n*25;break;case"error":case"timeout":r.errorRate=n*.5;break;case"cpu-stress":case"memory-stress":r.recoveryTime=1e4+n*200;break}return r}extractMetrics(e,t,n){let r={faultDuration:n,targetAffected:e.faultResults.some(c=>c.injected&&c.affectedTargets>0)},i=e.metrics;e.endTime&&e.startTime&&(r.recoveryTime=e.endTime.getTime()-e.startTime.getTime());let a=i.find(c=>c.name.includes("latency")||c.name.includes("response"));a&&(r.latencyP99=a.value);let s=i.find(c=>c.name.includes("error")||c.name.includes("failure"));return s&&(r.errorRate=s.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 a=parseInt(i[1])*1e3;return t.recoveryTime<=a}}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(a=>a.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}},Pl={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();Qe();var nt=class extends x{config={name:"qe/learning/optimize",description:"Cross-domain learning, pattern recognition, strategy optimization, and knowledge transfer.",domain:"learning-optimization",schema:xl,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 z(e);this.learningCoordinator=new Ti({memory:t,llmRouter:n}),this.metricsOptimizer=new Si(t),this.transferSpecialist=new Ei(t)}return{learningCoordinator:this.learningCoordinator,metricsOptimizer:this.metricsOptimizer,transferSpecialist:this.transferSpecialist}}async execute(e,t){let{action:n,domain:r,experienceIds:i,targetDomain:a,objective:s}=e;try{if(this.emitStream(t,{status:"processing",message:`Executing ${n} action`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let c={action:n};switch(n){case"learn":c.learnResult=await this.executeLearn(r,i,t);break;case"optimize":if(!s)return{success:!1,error:"Objective is required for optimize action"};c.optimizeResult=await this.executeOptimize(r,s,t);break;case"transfer":if(!r||!a)return{success:!1,error:"Both domain and targetDomain are required for transfer action"};c.transferResult=await this.executeTransfer(r,a,t);break;case"patterns":c.patternResult=await this.executePatterns(r,t);break;case"dashboard":c.dashboardResult=await this.executeDashboard(t);break;default:return{success:!1,error:`Unknown action: ${n}`}}return this.emitStream(t,{status:"complete",message:`${n} complete`,progress:100}),{success:!0,data:c}}catch(c){return{success:!1,error:`Learning optimization failed: ${S(c)}`}}}async executeLearn(e,t,n){let r=e||"learning-optimization";if(this.isDemoMode(n))return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoLearnResult(r);let{learningCoordinator:i}=await this.getServices(n);this.emitStream(n,{status:"learning",message:`Learning from ${t?.length||"recent"} experiences`});let a=We.lastNDays(7),s=await i.mineExperiences(r,a),c=[],l=0,u=0;if(s.success){l=s.value.experienceCount;for(let d of s.value.patterns)c.push({id:d.id,type:d.type,name:d.name,description:d.description,confidence:d.confidence,usageCount:d.usageCount,successRate:d.successRate});u=s.value.successRate>.5?(s.value.successRate-.5)*20:0}return t&&t.length>0&&(l=t.length),c.length===0?(this.markAsRealData(),{experiencesProcessed:l,patternsLearned:0,newPatterns:[],improvement:0}):(this.markAsRealData(),{experiencesProcessed:l,patternsLearned:c.length,newPatterns:c,improvement:u})}getDemoLearnResult(e){return{experiencesProcessed:150,patternsLearned:12,newPatterns:[{id:`pattern-${e}-001`,type:"optimization",name:"Parallel Execution Pattern",description:`Optimal parallelism settings discovered for ${e}`,confidence:.92,usageCount:45,successRate:.87},{id:`pattern-${e}-002`,type:"retry",name:"Exponential Backoff Pattern",description:"Effective retry strategy for flaky operations",confidence:.88,usageCount:32,successRate:.91},{id:`pattern-${e}-003`,type:"caching",name:"Result Caching Pattern",description:"Cache frequently computed results for faster access",confidence:.85,usageCount:28,successRate:.82}],improvement:15.5}}async executeOptimize(e,t,n){let{learningCoordinator:r,metricsOptimizer:i}=await this.getServices(n);this.emitStream(n,{status:"optimizing",message:`Optimizing for ${t.metric}`});let a=e||"learning-optimization",s=We.lastNDays(30),c=await r.mineExperiences(a,s),l=[];if(c.success&&c.value.experienceCount>0){let v={value:"optimizer-agent",domain:a,type:"optimizer"};for(let f=0;f<Math.min(c.value.experienceCount,20);f++)l.push({id:`exp-${f}`,agentId:v,domain:a,action:"optimize",state:{context:{},metrics:{}},result:{success:te()>.3,outcome:{[t.metric]:ne(70,100)},duration:ne(1e3,6e3)},reward:c.value.avgReward,timestamp:new Date})}let u={name:`${a}-current`,parameters:{parallelism:4,retryCount:3,timeout:3e4},expectedOutcome:{[t.metric]:70}},d=(t.constraints||[]).map(v=>({metric:v.metric,operator:v.operator,value:v.value})),m={metric:t.metric,direction:t.direction,constraints:d},p=u,g=0,h=.5,y=[];if(l.length>=20){let v=await i.optimizeStrategy(u,m,l);v.success&&(p={name:v.value.optimizedStrategy.name,parameters:v.value.optimizedStrategy.parameters,expectedOutcome:v.value.optimizedStrategy.expectedOutcome},g=v.value.improvement*100,h=v.value.confidence,y=v.value.validationResults)}else{let v={tags:[a,t.metric]},f=await i.recommendStrategy(v);f.success&&(p={name:f.value.name,parameters:f.value.parameters,expectedOutcome:f.value.expectedOutcome})}return{strategiesEvaluated:l.length>0?Math.min(l.length,12):1,bestStrategy:p,improvement:g,confidence:h,validationResults:y}}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}),a=0,s=0,c=0,l=0;if(i.success){a=i.value.length;for(let d of i.value){let m=await r.transferKnowledge(d,t);m.success&&(s++,l+=m.value.relevanceScore,Math.abs(m.value.relevanceScore-d.relevanceScore)>.1&&c++)}}let u=a>0?s/a:0;return{sourcePatterns:a,transferredPatterns:s,adaptedPatterns:c,successRate:u,targetDomainUpdated:s>0}}async executePatterns(e,t){let{learningCoordinator:n}=await this.getServices(t),r=await this.getSONASnapshot(t);this.emitStream(t,{status:"analyzing",message:`Analyzing patterns${e?` for ${e}`:""}`});let i=await n.getPatternStats(e);if(!i.success)return{totalPatterns:0,byType:{},byDomain:{},topPatterns:[],avgConfidence:0,avgSuccessRate:0,sona:r};let a=i.value,s=a.topPatterns.map(c=>({id:c.id,type:c.type,name:c.name,description:c.description,confidence:c.confidence,usageCount:c.usageCount,successRate:c.successRate}));return{totalPatterns:a.totalPatterns,byType:a.byType,byDomain:a.byDomain,topPatterns:s,avgConfidence:a.avgConfidence,avgSuccessRate:a.avgSuccessRate,sona:r}}async executeDashboard(e){let{learningCoordinator:t,transferSpecialist:n}=await this.getServices(e),r=await this.getSONASnapshot(e);this.emitStream(e,{status:"aggregating",message:"Aggregating learning metrics"});let i=await t.getPatternStats(),a=await n.queryKnowledge({minRelevance:0,limit:1e3}),s=We.lastNDays(1),c=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","learning-optimization"],l=0,u=[];for(let f of c){let C=await t.mineExperiences(f,s);C.success&&(l+=C.value.experienceCount,C.value.experienceCount>0&&u.push({domain:f,successRate:C.value.successRate}))}u.sort((f,C)=>C.successRate-f.successRate);let d=u.slice(0,3).map(f=>f.domain),m=i.success?i.value.totalPatterns:0,p=i.success?i.value.avgSuccessRate:0,g=p,h=[],y=new Date;for(let f=6;f>=0;f--){let C=new Date(y.getTime()-f*24*60*60*1e3),b=new Date(C.getTime()+1440*60*1e3),E=We.create(C,b),w=0;for(let T of c.slice(0,3)){let P=await t.mineExperiences(T,E);P.success&&(w+=P.value.patterns.length)}h.push({timestamp:C.toISOString(),metric:"patterns-learned",value:w})}let v=[];return m>=100&&v.push({name:`Reached ${Math.floor(m/50)*50} patterns`,achievedAt:new Date(y.getTime()-2880*60*1e3).toISOString(),domain:"learning-optimization"}),p>=.8&&v.push({name:`${Math.round(p*100)}% pattern success rate`,achievedAt:new Date(y.getTime()-7200*60*1e3).toISOString(),domain:d[0]||"learning-optimization"}),{overallLearningRate:g,totalPatterns:m,totalKnowledge:a.success?a.value.length:0,experiencesLast24h:l,topPerformingDomains:d.length>0?d:["test-generation"],learningTrend:h,recentMilestones:v,sona:r}}async getSONASnapshot(e){let t=e.kernel?.getDomainAPI("learning-optimization");if(!t?.isSONAAvailable())return{available:!1,stats:null};try{return{available:!0,stats:await t.getSONAPersistedStats()}}catch(n){return this.logger.warn("Failed to read persisted SONA statistics",{requestId:e.requestId,error:S(n)}),{available:!1,stats:null}}}},xl={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 Al={type:"object",properties:{action:{type:"string",enum:["dream","insights","apply","history","status"],description:"Action to perform: dream (run cycle), insights (view pending), apply (create pattern), history (view past), status (current state)"},durationMs:{type:"number",description:"Duration of dream cycle in milliseconds (default: 30000, max: 60000)",default:3e4},minPatterns:{type:"number",description:"Minimum patterns required to start dreaming (default: 10)",default:10},insightId:{type:"string",description:"Insight ID to apply (required for apply action)"},limit:{type:"number",description:"Maximum results to return (default: 20)",default:20},loadFromReasoningBank:{type:"boolean",description:"Load patterns from ReasoningBank before dreaming (default: true)",default:!0}},required:["action"]},rt=class extends 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:Al,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=wi(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=In(t);await n.initialize();try{let{getSharedRvfDualWriter:s}=await import("./shared-rvf-dual-writer-23X5PNY5.js"),c=await s();c&&n.setRvfDualWriter(c)}catch(s){process.env.DEBUG&&this.logger.info("RVF wiring skipped",{error:String(s)})}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(s=>({id:s.pattern.id,name:s.pattern.name,description:s.pattern.description||`${s.pattern.patternType} pattern`,domain:s.pattern.qeDomain||"learning-optimization",patternType:s.pattern.patternType,confidence:s.pattern.confidence,successRate:s.pattern.successRate||.5})),a=await e.loadPatternsAsConcepts(i);return this.logger.info(`Loaded ${a} patterns as concepts from ReasoningBank`),a}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=S(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 a=await this.getEngine({maxDurationMs:n,minConceptsRequired:r});if(i){let u=await this.loadPatternsFromReasoningBank(a);this.logger.info(`Loaded ${u} patterns from ReasoningBank`)}let s=await a.dream(n),c={cycleId:s.cycle.id,status:s.cycle.status,durationMs:s.cycle.durationMs||0,conceptsProcessed:s.cycle.conceptsProcessed,associationsFound:s.cycle.associationsFound,insightsGenerated:s.cycle.insightsGenerated,activationStats:s.activationStats,patternsCreated:s.patternsCreated},l=s.insights.map(u=>({id:u.id,type:u.type,description:u.description,noveltyScore:u.noveltyScore,confidenceScore:u.confidenceScore,actionable:u.actionable,applied:u.applied||!1,suggestedAction:u.suggestedAction,createdAt:u.createdAt?.toISOString()||new Date().toISOString()}));return this.logger.info(`Dream cycle complete: ${s.cycle.insightsGenerated} insights, ${s.cycle.associationsFound} associations found`),{success:!0,data:{action:"dream",success:!0,dreamResult:c,insights:l}}}async getPendingInsights(e,t){let n=e.limit||20;return{success:!0,data:{action:"insights",success:!0,insights:(await(await this.getEngine()).getPendingInsights(n)).map(s=>({id:s.id,type:s.type,description:s.description,noveltyScore:s.noveltyScore,confidenceScore:s.confidenceScore,actionable:s.actionable,applied:s.applied||!1,suggestedAction:s.suggestedAction,createdAt:s.createdAt?.toISOString()||new Date().toISOString()}))}}}async applyInsight(e,t){if(!e.insightId)return{success:!1,error:"insightId is required for apply action",data:{action:"apply",success:!1,error:"insightId is required for apply action"}};try{let r=await(await this.getEngine()).applyInsight(e.insightId);return r.success?(this.logger.info(`Applied insight ${e.insightId} \u2192 REAL pattern ${r.patternId} in ReasoningBank`),{success:!0,data:{action:"apply",success:!0,applyResult:{insightId:e.insightId,...r}}}):{success:!1,error:r.error,data:{action:"apply",success:!1,error:r.error}}}catch(n){let r=S(n);return{success:!1,error:r,data:{action:"apply",success:!1,error:r}}}}async getDreamHistory(e,t){let n=e.limit||20;return{success:!0,data:{action:"history",success:!0,history:(await(await this.getEngine()).getDreamHistory(n)).map(s=>({id:s.id,startTime:s.startTime.toISOString(),endTime:s.endTime?.toISOString(),durationMs:s.durationMs,status:s.status,conceptsProcessed:s.conceptsProcessed,associationsFound:s.associationsFound,insightsGenerated:s.insightsGenerated}))}}}async getDreamStatus(e,t){let n=await this.getEngine(),r=n.isDreaming(),i=n.getCurrentCycle(),a=await n.getDreamHistory(100),s=await n.getPendingInsights(100),c=a.reduce((d,m)=>d+m.insightsGenerated,0),l=a[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:a.length,totalInsights:c,pendingInsights:s.length,lastDreamTime:l?.startTime.toISOString()}}}}resetInstanceCache(){this.engine&&(this.engine.close().catch(console.error),this.engine=null)}};k();var yn=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:kl,streaming:!1,timeout:3e4};async execute(e,t){let{operation:n,timeframe:r,agentId:i,domain:a}=e;try{if(this.isAborted(t))return{success:!1,error:"Operation aborted"};let s;switch(n){case"session":s=this.getSessionUsage(r);break;case"agent":s=this.getAgentUsage(i,r);break;case"domain":s=this.getDomainUsage(a,r);break;case"task":s=this.getTaskUsage(r);break;case"efficiency":s=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:[Br()]}}};default:return{success:!1,error:`Unknown operation: ${n}`}}return{success:!0,data:s}}catch(s){return{success:!1,error:`Token usage analysis failed: ${S(s)}`}}}getSessionUsage(e){let t=J.getSessionSummary(e),n={};for(let[i,a]of t.byAgent)n[i]={tokens:a.totalTokens,cost:H(a.totalCost),tasks:a.tasksExecuted};let r={};for(let[i,a]of t.byDomain)r[i]={tokens:a.totalTokens,cost:H(a.estimatedCostUsd||0)};return{operation:"session",timeframe:e||"all",summary:{totalTokens:t.totalUsage.totalTokens,totalCost:H(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:H(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:H(d.totalCost),tasksExecuted:d.tasksExecuted,patternsReused:d.patternsReused,tokensSaved:d.estimatedTokensSaved,efficiency:Math.round(m*100)}}}}let i=Array.isArray(n)?n:[n],a={},s=0,c=0,l=0,u=0;for(let d of i)a[d.agentId]={tokens:d.totalTokens,cost:H(d.totalCost),tasks:d.tasksExecuted},s+=d.totalTokens,c+=d.totalCost,l+=d.estimatedTokensSaved,u+=d.patternsReused;return{operation:"agent",timeframe:t||"all",summary:{totalTokens:s,totalCost:H(c),tokensSaved:l,savingsPercentage:this.calculateSavingsPercentage(s,l)},breakdown:{byAgent:Object.keys(a).length>0?a:void 0},optimization:{patternsReused:u,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 l=n;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:l.totalTokens,totalCost:H(l.estimatedCostUsd||0),tokensSaved:r.optimizationStats.tokensSaved,savingsPercentage:r.optimizationStats.savingsPercentage},optimization:{patternsReused:r.optimizationStats.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateDomainRecommendations(e,l)},details:{domainMetrics:{domain:e,inputTokens:l.inputTokens,outputTokens:l.outputTokens,totalTokens:l.totalTokens,cost:H(l.estimatedCostUsd||0)}}}}let i=n instanceof Map?n:new Map,a={},s=0,c=0;for(let[l,u]of i)a[l]={tokens:u.totalTokens,cost:H(u.estimatedCostUsd||0)},s+=u.totalTokens,c+=u.estimatedCostUsd||0;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:s,totalCost:H(c),tokensSaved:r.optimizationStats.tokensSaved,savingsPercentage:r.optimizationStats.savingsPercentage},breakdown:{byDomain:Object.keys(a).length>0?a: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:H(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:H(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:H(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:a}=e.optimizationStats;return a<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."),a>25&&t.push(`Excellent token efficiency! ${a.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((a,s)=>s.totalTokens-a.totalTokens);n[0].totalTokens>0&&t.push(`Highest consumer: ${n[0].agentId} (${n[0].totalTokens.toLocaleString()} tokens)`);let r=e.reduce((a,s)=>a+s.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}},kl={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 it={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 Ml=[{name:"measure-coverage",description:"Run coverage analysis on the codebase to determine current coverage metrics",agentType:"qe-coverage-specialist",preconditions:{"coverage.measured":!1},effects:{"coverage.measured":!0},cost:2,estimatedDurationMs:3e4,successRate:.95,category:"coverage",qeDomain:"coverage-analysis",method:"analyze",params:{},implemented:!0},{name:"analyze-coverage-gaps",description:"Identify uncovered code paths and prioritize them by risk and complexity",agentType:"qe-gap-detector",preconditions:{"coverage.measured":!0},effects:{"coverage.gapsIdentified":!0},cost:1.5,estimatedDurationMs:15e3,successRate:.9,category:"coverage",qeDomain:"coverage-analysis",method:"detectGaps",params:{},implemented:!0},{name:"generate-coverage-tests",description:"Generate tests targeting identified coverage gaps using AI-powered analysis",agentType:"qe-test-generator",preconditions:{"coverage.gapsIdentified":!0},effects:{"coverage.line":{delta:10}},cost:4,estimatedDurationMs:6e4,successRate:.8,category:"coverage",qeDomain:"test-generation",method:"generateTests",params:{},implemented:!0},{name:"run-mutation-testing",description:"Run mutation testing to validate test effectiveness and find weak spots",agentType:"qe-mutation-tester",preconditions:{"coverage.line":{min:60}},effects:{"quality.mutationScore":{set:!0}},cost:5,estimatedDurationMs:12e4,successRate:.85,category:"coverage",qeDomain:"coverage-analysis",implemented:!1},{name:"prioritize-uncovered-paths",description:"Use sublinear O(log n) analysis to identify highest-risk uncovered paths",agentType:"qe-coverage-specialist",preconditions:{"coverage.gapsIdentified":!0},effects:{"coverage.riskPrioritized":!0},cost:1,estimatedDurationMs:1e4,successRate:.92,category:"coverage",qeDomain:"coverage-analysis",method:"calculateRisk",params:{},implemented:!0},{name:"generate-branch-tests",description:"Generate tests specifically targeting branch coverage improvements",agentType:"qe-test-generator",preconditions:{"coverage.measured":!0,"coverage.branch":{max:70}},effects:{"coverage.branch":{delta:8}},cost:3.5,estimatedDurationMs:45e3,successRate:.78,category:"coverage",qeDomain:"test-generation",method:"generateTests",params:{},implemented:!0}],Dl=[{name:"run-unit-tests",description:"Execute unit test suite with parallel execution",agentType:"qe-test-executor",preconditions:{},effects:{"quality.unitTestsRun":!0},cost:1,estimatedDurationMs:2e4,successRate:.95,category:"test",qeDomain:"test-execution",method:"runTests",params:{},implemented:!0},{name:"run-integration-tests",description:"Execute integration test suite with real database connections",agentType:"qe-test-executor",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.integrationTestsRun":!0},cost:2.5,estimatedDurationMs:45e3,successRate:.85,category:"test",qeDomain:"test-execution",method:"execute",params:{},implemented:!0},{name:"run-e2e-tests",description:"Execute end-to-end tests using Playwright or Cypress",agentType:"qe-e2e-tester",preconditions:{"quality.integrationTestsRun":!0},effects:{"quality.e2eTestsRun":!0},cost:4,estimatedDurationMs:9e4,successRate:.8,category:"test",qeDomain:"test-execution",method:"executeE2ETestSuite",params:{},implemented:!0},{name:"fix-failing-tests",description:"Analyze and fix failing tests based on error messages and stack traces",agentType:"qe-tdd-specialist",preconditions:{"quality.testsPassing":{max:90}},effects:{"quality.testsPassing":{delta:10}},cost:3,estimatedDurationMs:3e4,successRate:.75,category:"test",qeDomain:"test-generation",implemented:!1},{name:"fix-flaky-tests",description:"Identify and stabilize flaky tests by analyzing timing and async issues",agentType:"qe-flaky-hunter",preconditions:{"quality.flakyTests":{min:1}},effects:{"quality.flakyTests":{delta:-3}},cost:4,estimatedDurationMs:45e3,successRate:.7,category:"test",qeDomain:"test-execution",method:"detectFlaky",params:{},implemented:!0},{name:"generate-property-tests",description:"Generate property-based tests using fast-check or similar library",agentType:"qe-test-generator",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.propertyTestsGenerated":!0},cost:3.5,estimatedDurationMs:4e4,successRate:.82,category:"test",qeDomain:"test-generation",method:"generatePropertyTests",params:{},implemented:!0},{name:"run-contract-tests",description:"Execute consumer-driven contract tests using Pact or similar",agentType:"qe-contract-tester",preconditions:{"context.hasApiContracts":!0},effects:{"quality.contractTestsRun":!0},cost:2,estimatedDurationMs:25e3,successRate:.88,category:"test",qeDomain:"contract-testing",method:"verifyAllConsumers",params:{},implemented:!0}],Il=[{name:"security-scan",description:"Run comprehensive security scan using SAST and dependency analysis",agentType:"qe-security-scanner",preconditions:{},effects:{"quality.securityScanned":!0},cost:2,estimatedDurationMs:3e4,successRate:.95,category:"security",qeDomain:"security-compliance",method:"runSecurityAudit",params:{},implemented:!0},{name:"fix-vulnerabilities",description:"Remediate identified security vulnerabilities and update dependencies",agentType:"qe-security-auditor",preconditions:{"quality.securityScanned":!0,"quality.vulnerabilities":{min:1}},effects:{"quality.vulnerabilities":{delta:-5},"quality.securityScore":{delta:10}},cost:5,estimatedDurationMs:6e4,successRate:.7,category:"security",qeDomain:"security-compliance",implemented:!1},{name:"owasp-audit",description:"Perform OWASP Top 10 security audit on the application",agentType:"qe-security-auditor",preconditions:{"quality.securityScanned":!0},effects:{"quality.owaspCompliant":!0},cost:3,estimatedDurationMs:45e3,successRate:.85,category:"security",qeDomain:"security-compliance",method:"runComplianceCheck",params:{standard:"owasp"},implemented:!0},{name:"scan-secrets",description:"Scan codebase for hardcoded secrets and credentials",agentType:"qe-security-scanner",preconditions:{},effects:{"quality.secretsScanned":!0},cost:1,estimatedDurationMs:15e3,successRate:.98,category:"security",qeDomain:"security-compliance",method:"runSecurityAudit",params:{includeSecrets:!0},implemented:!0},{name:"run-dast",description:"Run dynamic application security testing against running application",agentType:"qe-security-auditor",preconditions:{"context.environment":"staging"},effects:{"quality.dastCompleted":!0},cost:4.5,estimatedDurationMs:12e4,successRate:.8,category:"security",qeDomain:"security-compliance",method:"runDASTScan",params:{},implemented:!0}],_l=[{name:"run-benchmarks",description:"Execute performance benchmarks to establish baseline metrics",agentType:"qe-performance-tester",preconditions:{},effects:{"quality.benchmarked":!0},cost:2,estimatedDurationMs:45e3,successRate:.9,category:"performance",qeDomain:"chaos-resilience",implemented:!1},{name:"load-test",description:"Run load testing with simulated concurrent traffic",agentType:"qe-load-tester",preconditions:{"context.environment":"staging"},effects:{"quality.loadTested":!0},cost:3.5,estimatedDurationMs:12e4,successRate:.85,category:"performance",qeDomain:"chaos-resilience",method:"runLoadTestSuite",params:{},implemented:!0},{name:"stress-test",description:"Run stress testing to find breaking points and system limits",agentType:"qe-chaos-engineer",preconditions:{"context.environment":"staging","quality.loadTested":!0},effects:{"quality.stressTested":!0},cost:4,estimatedDurationMs:9e4,successRate:.8,category:"performance",qeDomain:"chaos-resilience",method:"runTest",params:{type:"stress"},implemented:!0},{name:"profile-memory",description:"Profile memory usage and identify memory leaks",agentType:"qe-performance-tester",preconditions:{"quality.benchmarked":!0},effects:{"quality.memoryProfiled":!0},cost:2.5,estimatedDurationMs:6e4,successRate:.88,category:"performance",qeDomain:"chaos-resilience",implemented:!1},{name:"optimize-slow-tests",description:"Identify and optimize slow-running tests to improve CI/CD speed",agentType:"qe-performance-tester",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.testsOptimized":!0},cost:2,estimatedDurationMs:3e4,successRate:.82,category:"performance",qeDomain:"test-execution",implemented:!1}],Ol=[{name:"analyze-complexity",description:"Measure cyclomatic and cognitive complexity of codebase",agentType:"code-analyzer",preconditions:{},effects:{"quality.complexityAnalyzed":!0},cost:1,estimatedDurationMs:15e3,successRate:.95,category:"analysis",qeDomain:"quality-assessment",method:"analyzeComplexity",params:{},implemented:!0},{name:"detect-code-smells",description:"Identify code smells and anti-patterns using static analysis",agentType:"code-analyzer",preconditions:{},effects:{"quality.smellsDetected":!0},cost:1.5,estimatedDurationMs:2e4,successRate:.9,category:"analysis",qeDomain:"code-intelligence",implemented:!1},{name:"analyze-dependencies",description:"Analyze dependency graph and identify circular or outdated dependencies",agentType:"code-analyzer",preconditions:{},effects:{"quality.dependenciesAnalyzed":!0},cost:1,estimatedDurationMs:15e3,successRate:.92,category:"analysis",qeDomain:"code-intelligence",method:"mapDependencies",params:{},implemented:!0},{name:"measure-technical-debt",description:"Calculate technical debt metrics and generate remediation plan",agentType:"code-analyzer",preconditions:{"quality.complexityAnalyzed":!0,"quality.smellsDetected":!0},effects:{"quality.technicalDebtMeasured":!0},cost:2,estimatedDurationMs:25e3,successRate:.88,category:"analysis",qeDomain:"code-intelligence",implemented:!1},{name:"build-knowledge-graph",description:"Build semantic knowledge graph of codebase for intelligent context retrieval",agentType:"qe-intelligence-builder",preconditions:{"quality.dependenciesAnalyzed":!0},effects:{"quality.knowledgeGraphBuilt":!0},cost:3,estimatedDurationMs:6e4,successRate:.85,category:"analysis",qeDomain:"code-intelligence",method:"index",params:{},implemented:!0}],Fl=[{name:"spawn-test-agent",description:"Spawn additional test execution agent for parallel work",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{max:10}},effects:{"fleet.activeAgents":{delta:1}},cost:.5,estimatedDurationMs:5e3,successRate:.95,category:"fleet",qeDomain:"test-execution",implemented:!1},{name:"optimize-fleet-topology",description:"Reconfigure fleet topology for optimal task distribution",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:3}},effects:{"fleet.efficiency":{delta:15}},cost:1,estimatedDurationMs:1e4,successRate:.85,category:"fleet",implemented:!1},{name:"scale-down-fleet",description:"Reduce fleet size to conserve resources during low-activity periods",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:5}},effects:{"fleet.activeAgents":{delta:-2}},cost:.3,estimatedDurationMs:3e3,successRate:.98,category:"fleet",implemented:!1},{name:"spawn-specialist-agent",description:"Spawn a specialized agent for specific domain work",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{max:12},"context.specialistNeeded":!0},effects:{"fleet.activeAgents":{delta:1},"fleet.specialistAvailable":!0},cost:1,estimatedDurationMs:8e3,successRate:.9,category:"fleet",implemented:!1},{name:"rebalance-workload",description:"Redistribute tasks across agents based on current load",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:2}},effects:{"fleet.workloadBalanced":!0},cost:.5,estimatedDurationMs:5e3,successRate:.92,category:"fleet",implemented:!1}],Ll=[{name:"generate-quality-report",description:"Generate comprehensive quality report combining all metrics",agentType:"qe-quality-gate",preconditions:{"coverage.measured":!0,"quality.unitTestsRun":!0},effects:{"quality.reported":!0},cost:1,estimatedDurationMs:1e4,successRate:.95,category:"quality",qeDomain:"quality-assessment",method:"analyzeQuality",params:{},implemented:!0},{name:"enforce-quality-gate",description:"Check if all quality gates pass and report status",agentType:"qe-quality-gate",preconditions:{"quality.reported":!0},effects:{"quality.gatePassed":!0},cost:.5,estimatedDurationMs:5e3,successRate:.9,category:"quality",qeDomain:"quality-assessment",method:"evaluateGate",params:{},implemented:!0},{name:"validate-requirements",description:"Validate that tests cover all documented requirements",agentType:"qe-requirements-validator",preconditions:{"context.hasRequirements":!0},effects:{"quality.requirementsValidated":!0},cost:2,estimatedDurationMs:2e4,successRate:.88,category:"quality",qeDomain:"requirements-validation",method:"validate",params:{},implemented:!0},{name:"predict-defects",description:"Use ML-based defect prediction to identify high-risk code areas",agentType:"qe-defect-predictor",preconditions:{"quality.complexityAnalyzed":!0,"coverage.measured":!0},effects:{"quality.defectsPredicted":!0},cost:2.5,estimatedDurationMs:3e4,successRate:.82,category:"quality",qeDomain:"defect-intelligence",method:"predictDefects",params:{},implemented:!0},{name:"generate-deployment-report",description:"Generate deployment readiness report with all quality metrics",agentType:"qe-quality-gate",preconditions:{"quality.gatePassed":!0,"quality.securityScanned":!0},effects:{"quality.deploymentReady":!0},cost:1.5,estimatedDurationMs:15e3,successRate:.9,category:"quality",qeDomain:"quality-assessment",method:"getDeploymentAdvice",params:{},implemented:!0}],Nl=[{name:"run-accessibility-audit",description:"Run WCAG 2.2 accessibility audit using axe-core or similar",agentType:"qe-accessibility-tester",preconditions:{"context.hasUI":!0},effects:{"quality.accessibilityAudited":!0},cost:2,estimatedDurationMs:3e4,successRate:.9,category:"quality",qeDomain:"visual-accessibility",method:"runAccessibilityAudit",params:{},implemented:!0},{name:"run-visual-regression",description:"Run visual regression testing with screenshot comparison",agentType:"qe-visual-tester",preconditions:{"context.hasUI":!0},effects:{"quality.visualRegressionRun":!0},cost:3,estimatedDurationMs:6e4,successRate:.85,category:"quality",qeDomain:"visual-accessibility",method:"runVisualTests",params:{},implemented:!0}],oa=[...Ml,...Dl,...Il,..._l,...Ol,...Fl,...Ll,...Nl];function ql(o){return`action-${o}`}function ca(o){return{...o,id:ql(o.name),executionCount:0}}function Ne(){return oa.map(ca)}var vn=[{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"}];Q();import{randomUUID as ve}from"crypto";var xr=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}}},Gl=new Set(["__proto__","constructor","prototype"]),bn=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=jr(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.ensureDb().prepare("SELECT COUNT(*) as count FROM goap_actions").get().count===0&&this.seedDefaultActions(),this.backfillActionMethodBindings(),await this.loadActions(),this.initialized=!0,console.log(`[GOAPPlanner] Initialized: ${this.persistence.getDbPath()}`)}seedDefaultActions(){let e=Ne(),t=this.ensureDb(),n=t.prepare(`
624
+ `).length,h=l[g-1]||"",y=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:u,line:g,snippet:y},description:d.description,remediation:d.remediation,cweId:d.cweId,references:[]}),i>200)break}}}return r}async function Cl(o){let e=await import("fs"),t=await import("path"),n=[],r=t.resolve(o),i=t.join(r,"package.json");if(e.existsSync(i))try{let c=A(e.readFileSync(i,"utf-8")),l={...c.dependencies,...c.devDependencies};n.push(...Sl(l,"package.json"))}catch{}let a=t.join(r,"pyproject.toml");if(e.existsSync(a))try{let c=e.readFileSync(a,"utf-8"),l=wl(c);n.push(...ha(l,"pyproject.toml"))}catch{}let s=t.join(r,"requirements.txt");if(e.existsSync(s))try{let c=e.readFileSync(s,"utf-8"),l=Rl(c);n.push(...ha(l,"requirements.txt"))}catch{}if(n.length===0){let c=[i,a,s].filter(l=>e.existsSync(l));c.length>0&&n.push({id:"DEP-INFO-001",title:"Dependency audit recommended",severity:"informational",category:"vulnerable-components",location:{file:t.relative(process.cwd(),c[0])},description:`Found ${t.basename(c[0])} \u2014 run language-specific dependency audit for comprehensive results`,remediation:"Run npm audit, pip-audit, or equivalent for full vulnerability check",references:[]})}return n}var Tl={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 Sl(o,e){let t=[];for(let[n,r]of Object.entries(o)){let i=Tl[n];if(i){let a=r.replace(/^[\^~>=<]+/,"");Pl(a,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:a}},description:i.desc,remediation:`Upgrade ${n} to >= ${i.maxSafe}`,cveId:i.cve,references:[`https://nvd.nist.gov/vuln/detail/${i.cve}`]})}}return t}var El={"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 wl(o){let e=[],t=o.match(/dependencies\s*=\s*\[([\s\S]*?)\]/);if(t){let n=t[1].matchAll(/["']([a-zA-Z0-9_-]+)/g);for(let r of n)e.push(r[1].toLowerCase())}return e}function Rl(o){return o.split(`
625
+ `).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")).map(e=>e.split(/[>=<!~\[]/)[0].trim().toLowerCase()).filter(Boolean)}function ha(o,e){let t=[];for(let n of o){let r=El[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 Pl(o,e){let t=o.split(".").map(Number),n=e.split(".").map(Number);for(let r=0;r<3;r++){let i=t[r]||0,a=n[r]||0;if(i<a)return-1;if(i>a)return 1}return 0}function xl(o){return[{id:"DAST-INFO-001",title:"DAST scan target noted",severity:"informational",category:"security-misconfiguration",location:{file:o},description:`DAST target ${o} recorded. Full DAST requires integration with a dynamic scanner (e.g., ZAP, Burp).`,remediation:"Configure a DAST tool to scan the live application",references:["https://owasp.org/www-project-zap/"]}]}function Al(o,e){let t=e.filter(n=>o==="owasp"?!0:o==="pci-dss"?n.category==="injection"||n.category==="sensitive-data":o==="gdpr"?n.category==="sensitive-data":!1);return{standard:o,passed:t.filter(n=>n.severity==="critical"||n.severity==="high").length===0,score:Math.max(0,100-t.length*15),violations:t.map(n=>({ruleId:n.id,ruleName:n.title,location:n.location,details:n.description,remediation:n.remediation}))}}function kl(o,e){let t=[];return e.critical>0&&t.push("URGENT: Address critical vulnerabilities immediately"),e.high>0&&t.push("Prioritize high-severity issues in next sprint"),o.some(n=>n.category==="injection")&&t.push("Review input validation across the application"),o.some(n=>n.category==="sensitive-data")&&t.push("Implement proper secrets management"),o.some(n=>n.category==="vulnerable-components")&&t.push("Run full dependency audit and update vulnerable packages"),t.length===0&&t.push("No critical issues found. Continue regular security reviews."),t}Q();k();function fa(o){try{let e=new URL(o);if(!["http:","https:"].includes(e.protocol))return{valid:!1,error:`Invalid protocol: ${e.protocol}. Only http/https allowed.`};let t=e.hostname.toLowerCase(),n=[/^localhost$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2[0-9]|3[01])\./,/^192\.168\./,/^0\.0\.0\.0$/,/^\[::1\]$/,/^169\.254\./];for(let r of n)if(r.test(t))return{valid:!1,error:`Blocked hostname: ${t}. Cannot access internal/private addresses.`};return{valid:!0}}catch{return{valid:!1,error:`Invalid URL format: ${o}`}}}var fn=class extends x{config={name:"qe/contracts/validate",description:"Validate API contracts, detect breaking changes, and verify provider-consumer compatibility.",domain:"contract-testing",schema:Ml,streaming:!0,timeout:18e4};contractValidator=null;apiCompatibility=null;async getServices(e){if(!this.contractValidator||!this.apiCompatibility){let t=e.memory||await N(),n=await z(e);this.contractValidator=new Pi({memory:t,llmRouter:n}),this.apiCompatibility=new xi(t)}return{contractValidator:this.contractValidator,apiCompatibility:this.apiCompatibility}}async execute(e,t){let{contractPath:n,contractContent:r,providerUrl:i,consumerName:a,baselineVersion:s,baselineContent:c,checkBreakingChanges:l=!0,format:u="openapi"}=e,{contractValidator:d,apiCompatibility:m}=await this.getServices(t);try{if(!n&&!r)return{success:!1,error:"Either contractPath or contractContent is required"};if(this.emitStream(t,{status:"validating",message:`Validating ${u} contract`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let p=r||n||"",g=[],h,y,v;if(u==="openapi"){let b=await d.validateOpenAPI(p);if(b.success){let E=b.value;for(let w of E.errors)g.push({path:w.path,message:w.message,code:w.code,severity:"error"});for(let w of E.warnings)g.push({path:"",message:w,code:"WARNING",severity:"warning"});this.emitStream(t,{status:"analyzed",message:`Found ${E.endpointCount} endpoints, ${E.schemaCount} schemas`})}}else{let b=this.buildContractFromContent(p,u,a),E=await d.validateContract(b);if(E.success){let w=E.value;for(let T of w.errors)g.push(this.convertValidationError(T));for(let T of w.warnings)g.push({path:"",message:T,code:"WARNING",severity:"warning"})}}if(l&&(s||c)){this.emitStream(t,{status:"comparing",message:"Detecting breaking changes"});let b=this.buildContractFromContent(p,u,a),E=this.buildContractFromContent(c||p,u,a,s),w=await m.compareVersions(E,b);w.success?(h=w.value.breakingChanges.map(T=>this.convertBreakingChange(T)),v={isBackwardCompatible:w.value.isCompatible,breakingChangeCount:w.value.breakingChanges.length,nonBreakingChangeCount:w.value.nonBreakingChanges.length,deprecations:w.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"}),y=await this.verifyAgainstProvider(i,a||"default",p,u,d));let f=g.filter(b=>b.severity==="error").length===0,C=this.generateRecommendations(g,h,y);return this.emitStream(t,{status:"complete",message:f?"Contract is valid":`Found ${g.length} issues`,progress:100}),{success:!0,data:{isValid:f,validationErrors:g,breakingChanges:h,verificationResult:y,compatibility:v,recommendations:C}}}catch(p){return{success:!1,error:`Contract validation failed: ${S(p)}`}}}buildContractFromContent(e,t,n,r){let i=`contract-${Date.now()}`,a=ci.parse(r||"1.0.0"),s=[],c=[];if(t==="openapi")try{let l=A(e),d=l.components?.schemas||{};for(let[p,g]of Object.entries(d))s.push({id:p,name:p,type:"openapi",content:JSON.stringify(g)});let m=l.paths||{};for(let[p,g]of Object.entries(m))if(typeof g=="object"&&g!==null){let h=g,y=["get","post","put","patch","delete","head","options"];for(let v of y)v in h&&c.push({path:p,method:v.toUpperCase(),examples:[]})}}catch{}else if(t==="graphql")s.push({id:"graphql-schema",name:"GraphQL Schema",type:"graphql",content:e});else if(t==="pact")try{let u=A(e).interactions||[];for(let d of u){let m=d.request;m&&c.push({path:m.path||"/",method:(m.method||"GET").toUpperCase(),examples:[]})}}catch{}return{id:i,name:`${t}-contract`,version:a,type:t,provider:{name:"provider",version:"1.0.0"},consumers:[{name:n||"default",version:"1.0.0"}],endpoints:c,schemas:s}}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 a=[],s=[],c=fa(e);if(!c.valid)return{provider:e,consumer:t,passed:!1,failures:[{endpoint:e,type:"validation-error",expected:"Valid HTTP/HTTPS URL",actual:c.error||"Invalid URL",message:`Provider URL validation failed: ${c.error}`}],warnings:[]};let l=this.buildContractFromContent(n,r,t);for(let u of l.endpoints)try{let d=`${e}${u.path}`,m=fa(d);if(!m.valid){a.push({endpoint:`${u.method} ${u.path}`,type:"validation-error",expected:"Valid URL",actual:m.error||"Invalid URL",message:`URL validation failed: ${m.error}`});continue}let p=await fetch(d,{method:u.method==="GET"?"GET":"OPTIONS",headers:{Accept:"application/json"}});if(!p.ok&&p.status!==405&&(p.status===404?a.push({endpoint:`${u.method} ${u.path}`,type:"missing-endpoint",expected:"Endpoint should exist",actual:`Got ${p.status}`,message:"Endpoint not found at provider"}):s.push({endpoint:`${u.method} ${u.path}`,message:`Unexpected status ${p.status}`,severity:"medium"})),u.responseSchema&&p.ok){let g=await p.json(),h=l.schemas.find(y=>y.id===u.responseSchema);if(h){let y=await i.validateResponse(g,h);if(y.success&&!y.value.isValid)for(let v of y.value.errors)a.push({endpoint:`${u.method} ${u.path}`,type:"schema-mismatch",expected:`Schema ${u.responseSchema}`,actual:v.message,message:`Response does not match schema: ${v.message}`})}}}catch(d){s.push({endpoint:`${u.method} ${u.path}`,message:`Failed to verify: ${S(d)}`,severity:"high"})}return{provider:e,consumer:t,passed:a.length===0,failures:a,warnings:s}}generateRecommendations(e,t,n){let r=[],i=e.filter(s=>s.severity==="error").length;if(i>0&&r.push(`Fix ${i} validation error${i>1?"s":""} before deploying`),t&&t.length>0){let s=t.filter(c=>c.impact==="high").length;s>0&&r.push(`Address ${s} high-impact breaking change${s>1?"s":""} before release`),r.push("Coordinate with affected consumers before releasing breaking changes"),r.push("Consider versioning the API to maintain backward compatibility")}n&&(n.passed||(r.push(`Provider verification failed with ${n.failures.length} failure${n.failures.length>1?"s":""}`),n.failures.filter(l=>l.type==="missing-endpoint").length>0&&r.push("Ensure all contract endpoints are implemented in the provider"),n.failures.filter(l=>l.type==="schema-mismatch").length>0&&r.push("Update provider responses to match the contract schema")),n.warnings.length>0&&n.warnings.filter(c=>c.severity==="high").length>0&&r.push("Investigate high-severity verification warnings"));let a=e.filter(s=>s.severity==="warning").length;return a>0&&r.push(`Review ${a} warning${a>1?"s":""} for potential issues`),r.length===0&&r.push("Contract is valid and backward compatible"),r}},Ml={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 yn=class extends x{config={name:"qe/visual/compare",description:"Visual regression testing with screenshot comparison, diff detection, and baseline management.",domain:"visual-accessibility",schema:Il,streaming:!0,timeout:3e5};visualTester=null;async getService(e){if(!this.visualTester){let t=e.memory??await N(),n=await z(e);this.visualTester=Ai({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:a=.1,fullPage:s=!0}=e;try{if(this.emitStream(t,{status:"capturing",message:`Capturing ${n.length} URLs across ${r.length} viewports`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};this.markAsRealData();let c=await this.getService(t),l=[],u=[];for(let m of n)for(let p of r){this.emitStream(t,{status:"comparing",message:`Comparing ${m} at ${p.width}x${p.height}`});let g={width:p.width,height:p.height,deviceScaleFactor:1,isMobile:p.isMobile||!1,hasTouch:p.isMobile||!1},h=await c.captureScreenshot(m,{viewport:g,fullPage:s});if(!h.success){l.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let y=h.value,v=await c.getBaseline(m,g);if(!v)await c.setBaseline(y),u.push(y.path.value),l.push({url:m,viewport:p,status:"new",diffPercentage:0,diffPixels:0,screenshotPath:y.path.value});else{let f=await c.compare(y,v.id);if(!f.success){l.push({url:m,viewport:p,status:"failed",diffPercentage:100,diffPixels:0});continue}let C=f.value,b=C.diffPercentage<=a;l.push({url:m,viewport:p,status:b?"passed":"failed",diffPercentage:C.diffPercentage,diffPixels:C.diffPixels,screenshotPath:y.path.value,baselinePath:v.path.value,diffImagePath:C.diffImagePath?.value,regions:C.regions?.map(E=>({x:E.x,y:E.y,width:E.width,height:E.height,changeType:E.changeType,significance:E.significance}))})}}let d={total:l.length,passed:l.filter(m=>m.status==="passed").length,failed:l.filter(m=>m.status==="failed").length,new:l.filter(m=>m.status==="new").length,avgDiffPercentage:l.length>0?l.reduce((m,p)=>m+p.diffPercentage,0)/l.length:0};return this.emitStream(t,{status:"complete",message:`Visual comparison complete: ${d.passed}/${d.total} passed`,progress:100}),{success:!0,data:{comparisons:l,summary:d,newBaselines:u,recommendations:Ol(l,d)}}}catch(c){return{success:!1,error:`Visual comparison failed: ${S(c)}`}}}},vn=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:Dl,streaming:!0,timeout:18e4};accessibilityTester=null;async getService(e){if(!this.accessibilityTester){let t=e.memory;this.accessibilityTester=new ki(t||await N(),{enableColorContrastCheck:!0,enableKeyboardCheck:!0})}return this.accessibilityTester}async execute(e,t){let{urls:n,standard:r="wcag21-aa",includeWarnings:i=!0,checkContrast:a=!0,checkKeyboard:s=!0}=e;try{if(this.emitStream(t,{status:"auditing",message:`Auditing ${n.length} URLs against ${r}`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};this.markAsRealData();let c=await this.getService(t),l=[],u=_l(r);for(let g of n){this.emitStream(t,{status:"scanning",message:`Scanning ${g}`});let h=await c.audit(g,{wcagLevel:u,includeWarnings:i});if(!h.success){l.push({url:g,score:0,passed:!1,violations:[],warnings:[],passedRules:0});continue}let y=h.value,v=[];if(a){let w=await c.checkContrast(g);if(w.success){let T=w.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 f=[];if(s){let w=await c.checkKeyboardNavigation(g);if(w.success){let T=w.value;for(let P of T.issues)f.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)f.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=[...y.violations.map(w=>({id:w.id,impact:w.impact,description:w.description,help:w.help,helpUrl:w.helpUrl,wcagCriteria:w.wcagCriteria.map(T=>T.id),nodes:w.nodes.map(T=>({selector:T.selector,html:T.html,failureSummary:T.failureSummary,fixSuggestion:T.fixSuggestion}))})),...v,...f],b=y.incomplete.map(w=>({id:w.id,description:w.description,nodes:w.nodes.length})),E=C.some(w=>w.impact==="critical"||w.impact==="serious");l.push({url:g,score:y.score,passed:!E,violations:C,warnings:b,passedRules:y.passes.length})}let d={totalUrls:l.length,passingUrls:l.filter(g=>g.passed).length,avgScore:l.length>0?Math.round(l.reduce((g,h)=>g+h.score,0)/l.length):0,criticalViolations:l.reduce((g,h)=>g+h.violations.filter(y=>y.impact==="critical").length,0),seriousViolations:l.reduce((g,h)=>g+h.violations.filter(y=>y.impact==="serious").length,0),totalViolations:l.reduce((g,h)=>g+h.violations.length,0)},m=Nl(l),p=Fl(m);return this.emitStream(t,{status:"complete",message:`Audit complete: avg score ${d.avgScore}%`,progress:100}),{success:!0,data:{audits:l,summary:d,topIssues:m,remediationPlan:p}}}catch(c){return{success:!1,error:`Accessibility audit failed: ${S(c)}`}}}},Il={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"]},Dl={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 _l(o){return o==="wcag21-aaa"?"AAA":"AA"}function Ol(o,e){let t=[];return e.failed>0&&t.push(`Review ${e.failed} failed comparisons for intentional vs unintentional changes`),e.new>0&&t.push(`${e.new} new baselines created - review and approve if correct`),e.avgDiffPercentage>1&&t.push("Consider increasing diff threshold or reviewing major changes"),t.length>0?t:["All visual tests passed"]}function Nl(o){let e=new Map;for(let t of o)for(let n of t.violations){let r=e.get(n.id);r?(r.occurrences++,r.affectedUrls.includes(t.url)||r.affectedUrls.push(t.url)):e.set(n.id,{ruleId:n.id,description:n.description,occurrences:1,impact:n.impact,affectedUrls:[t.url]})}return Array.from(e.values()).sort((t,n)=>n.occurrences-t.occurrences)}function Fl(o){return o.map((e,t)=>({violationId:e.ruleId,description:e.description,fix:`Fix ${e.ruleId} across ${e.occurrences} occurrences`,effort:e.occurrences>10?"moderate":"minor",priority:t+1}))}k();var bn=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:Ll,streaming:!0,timeout:3e5};chaosEngineer=null;async getService(e){if(!this.chaosEngineer){let t=e.memory||await N(),n=await z(e);this.chaosEngineer=new Mi({memory:t,llmRouter:n},{enableDryRun:!0,autoRollbackOnFailure:!0})}return this.chaosEngineer}async execute(e,t){let{faultType:n,target:r,duration:i=3e4,intensity:a=50,dryRun:s=!0,hypothesis:c,rollbackOnFailure:l=!0}=e,u=await this.getService(t);try{if(this.emitStream(t,{status:"preparing",message:`Preparing ${n} fault injection on ${r}`,dryRun:s}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let d=t.requestId||q(),m=this.buildExperiment(d,n,r,i,a,c,l);this.emitStream(t,{status:"verifying",message:"Verifying steady state"});let p=await u.verifySteadyState(m.steadyState),g=p.success&&p.value;if(!g&&!s)return{success:!1,error:"Steady state verification failed. System not in healthy state for chaos experiment."};let h=await u.createExperiment(m);if(!h.success)return{success:!1,error:`Failed to create experiment: ${h.error.message}`};this.emitStream(t,{status:"injecting",message:s?`[DRY RUN] Simulating ${n} fault`:`Injecting ${n} fault`});let y=!1,v,f="pending",C=[],b={faultDuration:i,targetAffected:!s};if(s)y=!1,f="completed",b=this.simulateMetrics(n,i,a),c&&(v=this.validateHypothesisText(c,b,C));else{let T=await u.runExperiment(d);if(T.success){let P=T.value;y=P.faultResults.some(O=>O.injected),v=P.hypothesisValidated,f=P.status;for(let O of P.incidents)C.push(this.convertIncident(O));b=this.extractMetrics(P,n,i)}else f="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 E=this.collectIntensityIncidents(n,a,s);C.push(...E),!s&&C.some(T=>T.severity==="critical"&&!T.resolved)&&(f=l?"rolled-back":"failed");let w=this.generateRecommendations(n,b,C,v);return this.emitStream(t,{status:"complete",message:`Chaos experiment ${f}`,progress:100}),{success:!0,data:{experimentId:d,status:f,faultInjected:y,hypothesisValidated:v,steadyStateVerified:g,metrics:b,incidents:C,recommendations:w}}}catch(d){return{success:!1,error:`Chaos injection failed: ${S(d)}`}}}buildExperiment(e,t,n,r,i,a,s=!0){let c={id:`fault-${e}`,type:t,target:{type:"service",selector:n},duration:r,parameters:this.buildFaultParameters(t,i)},l={description:`Steady state for ${n}`,probes:[{name:"target-health",type:n.startsWith("http")?"http":"command",target:n.startsWith("http")?n:`echo "checking ${n}"`,expected:n.startsWith("http")?200:"OK",timeout:5e3}]},u=a||`System should remain stable under ${t} fault`;return{id:e,name:`${t}-experiment-${Date.now()}`,description:`Chaos experiment: ${t} on ${n}`,hypothesis:{statement:u,metrics:[{metric:t==="latency"?"response_time":"error_rate",operator:"lt",value:t==="latency"?5e3:50}],tolerances:[{metric:"availability",maxDeviation:20,unit:"percent"}]},steadyState:l,faults:[c],blastRadius:{scope:"single",maxAffected:1,excludeProduction:!0},rollbackPlan:{automatic:s,triggerConditions:[{type:"error-rate",condition:"error_rate > 50%"}],steps:[{order:1,action:"remove-fault",target:c.id,timeout:1e4}]},schedule:{type:"once"}}}buildFaultParameters(e,t){let n={};switch(e){case"latency":n.latencyMs=100+t*20;break;case"error":n.errorCode=500,n.errorRate=t/100;break;case"timeout":n.timeoutMs=5e3+t*250;break;case"cpu-stress":n.cpuPercent=t,n.cores=Math.max(1,Math.floor(t/25));break;case"memory-stress":n.memoryBytes=t/100*512*1024*1024;break;case"network-partition":n.partitionPercent=t;break;case"packet-loss":n.packetLossPercent=t;break;case"dns-failure":n.failureRate=t/100;break;case"process-kill":n.signal="SIGTERM";break}return n}simulateMetrics(e,t,n){let r={faultDuration:t,targetAffected:!1,recoveryTime:5e3+n*100};switch(e){case"latency":r.latencyP99=100+n*25;break;case"error":case"timeout":r.errorRate=n*.5;break;case"cpu-stress":case"memory-stress":r.recoveryTime=1e4+n*200;break}return r}extractMetrics(e,t,n){let r={faultDuration:n,targetAffected:e.faultResults.some(c=>c.injected&&c.affectedTargets>0)},i=e.metrics;e.endTime&&e.startTime&&(r.recoveryTime=e.endTime.getTime()-e.startTime.getTime());let a=i.find(c=>c.name.includes("latency")||c.name.includes("response"));a&&(r.latencyP99=a.value);let s=i.find(c=>c.name.includes("error")||c.name.includes("failure"));return s&&(r.errorRate=s.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 a=parseInt(i[1])*1e3;return t.recoveryTime<=a}}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(a=>a.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}},Ll={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();Xe();var st=class extends x{config={name:"qe/learning/optimize",description:"Cross-domain learning, pattern recognition, strategy optimization, and knowledge transfer.",domain:"learning-optimization",schema:ql,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 N(),n=await z(e);this.learningCoordinator=new Ii({memory:t,llmRouter:n}),this.metricsOptimizer=new Di(t),this.transferSpecialist=new _i(t)}return{learningCoordinator:this.learningCoordinator,metricsOptimizer:this.metricsOptimizer,transferSpecialist:this.transferSpecialist}}async execute(e,t){let{action:n,domain:r,experienceIds:i,targetDomain:a,objective:s}=e;try{if(this.emitStream(t,{status:"processing",message:`Executing ${n} action`}),this.isAborted(t))return{success:!1,error:"Operation aborted"};let c={action:n};switch(n){case"learn":c.learnResult=await this.executeLearn(r,i,t);break;case"optimize":if(!s)return{success:!1,error:"Objective is required for optimize action"};c.optimizeResult=await this.executeOptimize(r,s,t);break;case"transfer":if(!r||!a)return{success:!1,error:"Both domain and targetDomain are required for transfer action"};c.transferResult=await this.executeTransfer(r,a,t);break;case"patterns":c.patternResult=await this.executePatterns(r,t);break;case"dashboard":c.dashboardResult=await this.executeDashboard(t);break;default:return{success:!1,error:`Unknown action: ${n}`}}return this.emitStream(t,{status:"complete",message:`${n} complete`,progress:100}),{success:!0,data:c}}catch(c){return{success:!1,error:`Learning optimization failed: ${S(c)}`}}}async executeLearn(e,t,n){let r=e||"learning-optimization";if(this.isDemoMode(n))return this.markAsDemoData(n,"Demo mode explicitly requested"),this.getDemoLearnResult(r);let{learningCoordinator:i}=await this.getServices(n);this.emitStream(n,{status:"learning",message:`Learning from ${t?.length||"recent"} experiences`});let a=Ye.lastNDays(7),s=await i.mineExperiences(r,a),c=[],l=0,u=0;if(s.success){l=s.value.experienceCount;for(let d of s.value.patterns)c.push({id:d.id,type:d.type,name:d.name,description:d.description,confidence:d.confidence,usageCount:d.usageCount,successRate:d.successRate});u=s.value.successRate>.5?(s.value.successRate-.5)*20:0}return t&&t.length>0&&(l=t.length),c.length===0?(this.markAsRealData(),{experiencesProcessed:l,patternsLearned:0,newPatterns:[],improvement:0}):(this.markAsRealData(),{experiencesProcessed:l,patternsLearned:c.length,newPatterns:c,improvement:u})}getDemoLearnResult(e){return{experiencesProcessed:150,patternsLearned:12,newPatterns:[{id:`pattern-${e}-001`,type:"optimization",name:"Parallel Execution Pattern",description:`Optimal parallelism settings discovered for ${e}`,confidence:.92,usageCount:45,successRate:.87},{id:`pattern-${e}-002`,type:"retry",name:"Exponential Backoff Pattern",description:"Effective retry strategy for flaky operations",confidence:.88,usageCount:32,successRate:.91},{id:`pattern-${e}-003`,type:"caching",name:"Result Caching Pattern",description:"Cache frequently computed results for faster access",confidence:.85,usageCount:28,successRate:.82}],improvement:15.5}}async executeOptimize(e,t,n){let{learningCoordinator:r,metricsOptimizer:i}=await this.getServices(n);this.emitStream(n,{status:"optimizing",message:`Optimizing for ${t.metric}`});let a=e||"learning-optimization",s=Ye.lastNDays(30),c=await r.mineExperiences(a,s),l=[];if(c.success&&c.value.experienceCount>0){let v={value:"optimizer-agent",domain:a,type:"optimizer"};for(let f=0;f<Math.min(c.value.experienceCount,20);f++)l.push({id:`exp-${f}`,agentId:v,domain:a,action:"optimize",state:{context:{},metrics:{}},result:{success:ne()>.3,outcome:{[t.metric]:re(70,100)},duration:re(1e3,6e3)},reward:c.value.avgReward,timestamp:new Date})}let u={name:`${a}-current`,parameters:{parallelism:4,retryCount:3,timeout:3e4},expectedOutcome:{[t.metric]:70}},d=(t.constraints||[]).map(v=>({metric:v.metric,operator:v.operator,value:v.value})),m={metric:t.metric,direction:t.direction,constraints:d},p=u,g=0,h=.5,y=[];if(l.length>=20){let v=await i.optimizeStrategy(u,m,l);v.success&&(p={name:v.value.optimizedStrategy.name,parameters:v.value.optimizedStrategy.parameters,expectedOutcome:v.value.optimizedStrategy.expectedOutcome},g=v.value.improvement*100,h=v.value.confidence,y=v.value.validationResults)}else{let v={tags:[a,t.metric]},f=await i.recommendStrategy(v);f.success&&(p={name:f.value.name,parameters:f.value.parameters,expectedOutcome:f.value.expectedOutcome})}return{strategiesEvaluated:l.length>0?Math.min(l.length,12):1,bestStrategy:p,improvement:g,confidence:h,validationResults:y}}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}),a=0,s=0,c=0,l=0;if(i.success){a=i.value.length;for(let d of i.value){let m=await r.transferKnowledge(d,t);m.success&&(s++,l+=m.value.relevanceScore,Math.abs(m.value.relevanceScore-d.relevanceScore)>.1&&c++)}}let u=a>0?s/a:0;return{sourcePatterns:a,transferredPatterns:s,adaptedPatterns:c,successRate:u,targetDomainUpdated:s>0}}async executePatterns(e,t){let{learningCoordinator:n}=await this.getServices(t),r=await this.getSONASnapshot(t);this.emitStream(t,{status:"analyzing",message:`Analyzing patterns${e?` for ${e}`:""}`});let i=await n.getPatternStats(e);if(!i.success)return{totalPatterns:0,byType:{},byDomain:{},topPatterns:[],avgConfidence:0,avgSuccessRate:0,sona:r};let a=i.value,s=a.topPatterns.map(c=>({id:c.id,type:c.type,name:c.name,description:c.description,confidence:c.confidence,usageCount:c.usageCount,successRate:c.successRate}));return{totalPatterns:a.totalPatterns,byType:a.byType,byDomain:a.byDomain,topPatterns:s,avgConfidence:a.avgConfidence,avgSuccessRate:a.avgSuccessRate,sona:r}}async executeDashboard(e){let{learningCoordinator:t,transferSpecialist:n}=await this.getServices(e),r=await this.getSONASnapshot(e);this.emitStream(e,{status:"aggregating",message:"Aggregating learning metrics"});let i=await t.getPatternStats(),a=await n.queryKnowledge({minRelevance:0,limit:1e3}),s=Ye.lastNDays(1),c=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","learning-optimization"],l=0,u=[];for(let f of c){let C=await t.mineExperiences(f,s);C.success&&(l+=C.value.experienceCount,C.value.experienceCount>0&&u.push({domain:f,successRate:C.value.successRate}))}u.sort((f,C)=>C.successRate-f.successRate);let d=u.slice(0,3).map(f=>f.domain),m=i.success?i.value.totalPatterns:0,p=i.success?i.value.avgSuccessRate:0,g=p,h=[],y=new Date;for(let f=6;f>=0;f--){let C=new Date(y.getTime()-f*24*60*60*1e3),b=new Date(C.getTime()+1440*60*1e3),E=Ye.create(C,b),w=0;for(let T of c.slice(0,3)){let P=await t.mineExperiences(T,E);P.success&&(w+=P.value.patterns.length)}h.push({timestamp:C.toISOString(),metric:"patterns-learned",value:w})}let v=[];return m>=100&&v.push({name:`Reached ${Math.floor(m/50)*50} patterns`,achievedAt:new Date(y.getTime()-2880*60*1e3).toISOString(),domain:"learning-optimization"}),p>=.8&&v.push({name:`${Math.round(p*100)}% pattern success rate`,achievedAt:new Date(y.getTime()-7200*60*1e3).toISOString(),domain:d[0]||"learning-optimization"}),{overallLearningRate:g,totalPatterns:m,totalKnowledge:a.success?a.value.length:0,experiencesLast24h:l,topPerformingDomains:d.length>0?d:["test-generation"],learningTrend:h,recentMilestones:v,sona:r}}async getSONASnapshot(e){let t=e.kernel?.getDomainAPI("learning-optimization");if(!t?.isSONAAvailable())return{available:!1,stats:null};try{return{available:!0,stats:await t.getSONAPersistedStats()}}catch(n){return this.logger.warn("Failed to read persisted SONA statistics",{requestId:e.requestId,error:S(n)}),{available:!1,stats:null}}}},ql={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 Gl={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"]},at=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:Gl,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=Oi(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 N(),n=Nn(t);await n.initialize();try{let{getSharedRvfDualWriter:s}=await import("./shared-rvf-dual-writer-LHMFCYVE.js"),c=await s();c&&n.setRvfDualWriter(c)}catch(s){process.env.DEBUG&&this.logger.info("RVF wiring skipped",{error:String(s)})}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(s=>({id:s.pattern.id,name:s.pattern.name,description:s.pattern.description||`${s.pattern.patternType} pattern`,domain:s.pattern.qeDomain||"learning-optimization",patternType:s.pattern.patternType,confidence:s.pattern.confidence,successRate:s.pattern.successRate||.5})),a=await e.loadPatternsAsConcepts(i);return this.logger.info(`Loaded ${a} patterns as concepts from ReasoningBank`),a}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=S(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 a=await this.getEngine({maxDurationMs:n,minConceptsRequired:r});if(i){let u=await this.loadPatternsFromReasoningBank(a);this.logger.info(`Loaded ${u} patterns from ReasoningBank`)}let s=await a.dream(n),c={cycleId:s.cycle.id,status:s.cycle.status,durationMs:s.cycle.durationMs||0,conceptsProcessed:s.cycle.conceptsProcessed,associationsFound:s.cycle.associationsFound,insightsGenerated:s.cycle.insightsGenerated,activationStats:s.activationStats,patternsCreated:s.patternsCreated},l=s.insights.map(u=>({id:u.id,type:u.type,description:u.description,noveltyScore:u.noveltyScore,confidenceScore:u.confidenceScore,actionable:u.actionable,applied:u.applied||!1,suggestedAction:u.suggestedAction,createdAt:u.createdAt?.toISOString()||new Date().toISOString()}));return this.logger.info(`Dream cycle complete: ${s.cycle.insightsGenerated} insights, ${s.cycle.associationsFound} associations found`),{success:!0,data:{action:"dream",success:!0,dreamResult:c,insights:l}}}async getPendingInsights(e,t){let n=e.limit||20;return{success:!0,data:{action:"insights",success:!0,insights:(await(await this.getEngine()).getPendingInsights(n)).map(s=>({id:s.id,type:s.type,description:s.description,noveltyScore:s.noveltyScore,confidenceScore:s.confidenceScore,actionable:s.actionable,applied:s.applied||!1,suggestedAction:s.suggestedAction,createdAt:s.createdAt?.toISOString()||new Date().toISOString()}))}}}async applyInsight(e,t){if(!e.insightId)return{success:!1,error:"insightId is required for apply action",data:{action:"apply",success:!1,error:"insightId is required for apply action"}};try{let r=await(await this.getEngine()).applyInsight(e.insightId);return r.success?(this.logger.info(`Applied insight ${e.insightId} \u2192 REAL pattern ${r.patternId} in ReasoningBank`),{success:!0,data:{action:"apply",success:!0,applyResult:{insightId:e.insightId,...r}}}):{success:!1,error:r.error,data:{action:"apply",success:!1,error:r.error}}}catch(n){let r=S(n);return{success:!1,error:r,data:{action:"apply",success:!1,error:r}}}}async getDreamHistory(e,t){let n=e.limit||20;return{success:!0,data:{action:"history",success:!0,history:(await(await this.getEngine()).getDreamHistory(n)).map(s=>({id:s.id,startTime:s.startTime.toISOString(),endTime:s.endTime?.toISOString(),durationMs:s.durationMs,status:s.status,conceptsProcessed:s.conceptsProcessed,associationsFound:s.associationsFound,insightsGenerated:s.insightsGenerated}))}}}async getDreamStatus(e,t){let n=await this.getEngine(),r=n.isDreaming(),i=n.getCurrentCycle(),a=await n.getDreamHistory(100),s=await n.getPendingInsights(100),c=a.reduce((d,m)=>d+m.insightsGenerated,0),l=a[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:a.length,totalInsights:c,pendingInsights:s.length,lastDreamTime:l?.startTime.toISOString()}}}}resetInstanceCache(){this.engine&&(this.engine.close().catch(console.error),this.engine=null)}};k();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:$l,streaming:!1,timeout:3e4};async execute(e,t){let{operation:n,timeframe:r,agentId:i,domain:a}=e;try{if(this.isAborted(t))return{success:!1,error:"Operation aborted"};let s;switch(n){case"session":s=this.getSessionUsage(r);break;case"agent":s=this.getAgentUsage(i,r);break;case"domain":s=this.getDomainUsage(a,r);break;case"task":s=this.getTaskUsage(r);break;case"efficiency":s=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:[Zr()]}}};default:return{success:!1,error:`Unknown operation: ${n}`}}return{success:!0,data:s}}catch(s){return{success:!1,error:`Token usage analysis failed: ${S(s)}`}}}getSessionUsage(e){let t=Z.getSessionSummary(e),n={};for(let[i,a]of t.byAgent)n[i]={tokens:a.totalTokens,cost:H(a.totalCost),tasks:a.tasksExecuted};let r={};for(let[i,a]of t.byDomain)r[i]={tokens:a.totalTokens,cost:H(a.estimatedCostUsd||0)};return{operation:"session",timeframe:e||"all",summary:{totalTokens:t.totalUsage.totalTokens,totalCost:H(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=Z.getAgentMetrics(e,t),r=Z.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:H(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:H(d.totalCost),tasksExecuted:d.tasksExecuted,patternsReused:d.patternsReused,tokensSaved:d.estimatedTokensSaved,efficiency:Math.round(m*100)}}}}let i=Array.isArray(n)?n:[n],a={},s=0,c=0,l=0,u=0;for(let d of i)a[d.agentId]={tokens:d.totalTokens,cost:H(d.totalCost),tasks:d.tasksExecuted},s+=d.totalTokens,c+=d.totalCost,l+=d.estimatedTokensSaved,u+=d.patternsReused;return{operation:"agent",timeframe:t||"all",summary:{totalTokens:s,totalCost:H(c),tokensSaved:l,savingsPercentage:this.calculateSavingsPercentage(s,l)},breakdown:{byAgent:Object.keys(a).length>0?a:void 0},optimization:{patternsReused:u,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateMultiAgentRecommendations(i)}}}getDomainUsage(e,t){let n=Z.getDomainMetrics(e,t),r=Z.getSessionSummary(t);if(e&&!(n instanceof Map)){let l=n;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:l.totalTokens,totalCost:H(l.estimatedCostUsd||0),tokensSaved:r.optimizationStats.tokensSaved,savingsPercentage:r.optimizationStats.savingsPercentage},optimization:{patternsReused:r.optimizationStats.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateDomainRecommendations(e,l)},details:{domainMetrics:{domain:e,inputTokens:l.inputTokens,outputTokens:l.outputTokens,totalTokens:l.totalTokens,cost:H(l.estimatedCostUsd||0)}}}}let i=n instanceof Map?n:new Map,a={},s=0,c=0;for(let[l,u]of i)a[l]={tokens:u.totalTokens,cost:H(u.estimatedCostUsd||0)},s+=u.totalTokens,c+=u.estimatedCostUsd||0;return{operation:"domain",timeframe:t||"all",summary:{totalTokens:s,totalCost:H(c),tokensSaved:r.optimizationStats.tokensSaved,savingsPercentage:r.optimizationStats.savingsPercentage},breakdown:{byDomain:Object.keys(a).length>0?a:void 0},optimization:{patternsReused:r.optimizationStats.patternsReused,cacheHits:r.optimizationStats.cacheHits,earlyExits:r.optimizationStats.earlyExits,recommendations:this.generateMultiDomainRecommendations(i)}}}getTaskUsage(e){let t=Z.getTaskMetrics(e),n=Z.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:H(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:H(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=Z.getEfficiencyReport(e),n=Z.getSessionSummary(e);return{operation:"efficiency",timeframe:e||"all",summary:{totalTokens:t.totalTokensUsed,totalCost:H(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:a}=e.optimizationStats;return a<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."),a>25&&t.push(`Excellent token efficiency! ${a.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((a,s)=>s.totalTokens-a.totalTokens);n[0].totalTokens>0&&t.push(`Highest consumer: ${n[0].agentId} (${n[0].totalTokens.toLocaleString()} tokens)`);let r=e.reduce((a,s)=>a+s.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}},$l={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 ot={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 zl=[{name:"measure-coverage",description:"Run coverage analysis on the codebase to determine current coverage metrics",agentType:"qe-coverage-specialist",preconditions:{"coverage.measured":!1},effects:{"coverage.measured":!0},cost:2,estimatedDurationMs:3e4,successRate:.95,category:"coverage",qeDomain:"coverage-analysis",method:"analyze",params:{},implemented:!0},{name:"analyze-coverage-gaps",description:"Identify uncovered code paths and prioritize them by risk and complexity",agentType:"qe-gap-detector",preconditions:{"coverage.measured":!0},effects:{"coverage.gapsIdentified":!0},cost:1.5,estimatedDurationMs:15e3,successRate:.9,category:"coverage",qeDomain:"coverage-analysis",method:"detectGaps",params:{},implemented:!0},{name:"generate-coverage-tests",description:"Generate tests targeting identified coverage gaps using AI-powered analysis",agentType:"qe-test-generator",preconditions:{"coverage.gapsIdentified":!0},effects:{"coverage.line":{delta:10}},cost:4,estimatedDurationMs:6e4,successRate:.8,category:"coverage",qeDomain:"test-generation",method:"generateTests",params:{},implemented:!0},{name:"run-mutation-testing",description:"Run mutation testing to validate test effectiveness and find weak spots",agentType:"qe-mutation-tester",preconditions:{"coverage.line":{min:60}},effects:{"quality.mutationScore":{set:!0}},cost:5,estimatedDurationMs:12e4,successRate:.85,category:"coverage",qeDomain:"coverage-analysis",implemented:!1},{name:"prioritize-uncovered-paths",description:"Use sublinear O(log n) analysis to identify highest-risk uncovered paths",agentType:"qe-coverage-specialist",preconditions:{"coverage.gapsIdentified":!0},effects:{"coverage.riskPrioritized":!0},cost:1,estimatedDurationMs:1e4,successRate:.92,category:"coverage",qeDomain:"coverage-analysis",method:"calculateRisk",params:{},implemented:!0},{name:"generate-branch-tests",description:"Generate tests specifically targeting branch coverage improvements",agentType:"qe-test-generator",preconditions:{"coverage.measured":!0,"coverage.branch":{max:70}},effects:{"coverage.branch":{delta:8}},cost:3.5,estimatedDurationMs:45e3,successRate:.78,category:"coverage",qeDomain:"test-generation",method:"generateTests",params:{},implemented:!0}],jl=[{name:"run-unit-tests",description:"Execute unit test suite with parallel execution",agentType:"qe-test-executor",preconditions:{},effects:{"quality.unitTestsRun":!0},cost:1,estimatedDurationMs:2e4,successRate:.95,category:"test",qeDomain:"test-execution",method:"runTests",params:{},implemented:!0},{name:"run-integration-tests",description:"Execute integration test suite with real database connections",agentType:"qe-test-executor",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.integrationTestsRun":!0},cost:2.5,estimatedDurationMs:45e3,successRate:.85,category:"test",qeDomain:"test-execution",method:"execute",params:{},implemented:!0},{name:"run-e2e-tests",description:"Execute end-to-end tests using Playwright or Cypress",agentType:"qe-e2e-tester",preconditions:{"quality.integrationTestsRun":!0},effects:{"quality.e2eTestsRun":!0},cost:4,estimatedDurationMs:9e4,successRate:.8,category:"test",qeDomain:"test-execution",method:"executeE2ETestSuite",params:{},implemented:!0},{name:"fix-failing-tests",description:"Analyze and fix failing tests based on error messages and stack traces",agentType:"qe-tdd-specialist",preconditions:{"quality.testsPassing":{max:90}},effects:{"quality.testsPassing":{delta:10}},cost:3,estimatedDurationMs:3e4,successRate:.75,category:"test",qeDomain:"test-generation",implemented:!1},{name:"fix-flaky-tests",description:"Identify and stabilize flaky tests by analyzing timing and async issues",agentType:"qe-flaky-hunter",preconditions:{"quality.flakyTests":{min:1}},effects:{"quality.flakyTests":{delta:-3}},cost:4,estimatedDurationMs:45e3,successRate:.7,category:"test",qeDomain:"test-execution",method:"detectFlaky",params:{},implemented:!0},{name:"generate-property-tests",description:"Generate property-based tests using fast-check or similar library",agentType:"qe-test-generator",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.propertyTestsGenerated":!0},cost:3.5,estimatedDurationMs:4e4,successRate:.82,category:"test",qeDomain:"test-generation",method:"generatePropertyTests",params:{},implemented:!0},{name:"run-contract-tests",description:"Execute consumer-driven contract tests using Pact or similar",agentType:"qe-contract-tester",preconditions:{"context.hasApiContracts":!0},effects:{"quality.contractTestsRun":!0},cost:2,estimatedDurationMs:25e3,successRate:.88,category:"test",qeDomain:"contract-testing",method:"verifyAllConsumers",params:{},implemented:!0}],Bl=[{name:"security-scan",description:"Run comprehensive security scan using SAST and dependency analysis",agentType:"qe-security-scanner",preconditions:{},effects:{"quality.securityScanned":!0},cost:2,estimatedDurationMs:3e4,successRate:.95,category:"security",qeDomain:"security-compliance",method:"runSecurityAudit",params:{},implemented:!0},{name:"fix-vulnerabilities",description:"Remediate identified security vulnerabilities and update dependencies",agentType:"qe-security-auditor",preconditions:{"quality.securityScanned":!0,"quality.vulnerabilities":{min:1}},effects:{"quality.vulnerabilities":{delta:-5},"quality.securityScore":{delta:10}},cost:5,estimatedDurationMs:6e4,successRate:.7,category:"security",qeDomain:"security-compliance",implemented:!1},{name:"owasp-audit",description:"Perform OWASP Top 10 security audit on the application",agentType:"qe-security-auditor",preconditions:{"quality.securityScanned":!0},effects:{"quality.owaspCompliant":!0},cost:3,estimatedDurationMs:45e3,successRate:.85,category:"security",qeDomain:"security-compliance",method:"runComplianceCheck",params:{standard:"owasp"},implemented:!0},{name:"scan-secrets",description:"Scan codebase for hardcoded secrets and credentials",agentType:"qe-security-scanner",preconditions:{},effects:{"quality.secretsScanned":!0},cost:1,estimatedDurationMs:15e3,successRate:.98,category:"security",qeDomain:"security-compliance",method:"runSecurityAudit",params:{includeSecrets:!0},implemented:!0},{name:"run-dast",description:"Run dynamic application security testing against running application",agentType:"qe-security-auditor",preconditions:{"context.environment":"staging"},effects:{"quality.dastCompleted":!0},cost:4.5,estimatedDurationMs:12e4,successRate:.8,category:"security",qeDomain:"security-compliance",method:"runDASTScan",params:{},implemented:!0}],Ul=[{name:"run-benchmarks",description:"Execute performance benchmarks to establish baseline metrics",agentType:"qe-performance-tester",preconditions:{},effects:{"quality.benchmarked":!0},cost:2,estimatedDurationMs:45e3,successRate:.9,category:"performance",qeDomain:"chaos-resilience",implemented:!1},{name:"load-test",description:"Run load testing with simulated concurrent traffic",agentType:"qe-load-tester",preconditions:{"context.environment":"staging"},effects:{"quality.loadTested":!0},cost:3.5,estimatedDurationMs:12e4,successRate:.85,category:"performance",qeDomain:"chaos-resilience",method:"runLoadTestSuite",params:{},implemented:!0},{name:"stress-test",description:"Run stress testing to find breaking points and system limits",agentType:"qe-chaos-engineer",preconditions:{"context.environment":"staging","quality.loadTested":!0},effects:{"quality.stressTested":!0},cost:4,estimatedDurationMs:9e4,successRate:.8,category:"performance",qeDomain:"chaos-resilience",method:"runTest",params:{type:"stress"},implemented:!0},{name:"profile-memory",description:"Profile memory usage and identify memory leaks",agentType:"qe-performance-tester",preconditions:{"quality.benchmarked":!0},effects:{"quality.memoryProfiled":!0},cost:2.5,estimatedDurationMs:6e4,successRate:.88,category:"performance",qeDomain:"chaos-resilience",implemented:!1},{name:"optimize-slow-tests",description:"Identify and optimize slow-running tests to improve CI/CD speed",agentType:"qe-performance-tester",preconditions:{"quality.unitTestsRun":!0},effects:{"quality.testsOptimized":!0},cost:2,estimatedDurationMs:3e4,successRate:.82,category:"performance",qeDomain:"test-execution",implemented:!1}],Hl=[{name:"analyze-complexity",description:"Measure cyclomatic and cognitive complexity of codebase",agentType:"code-analyzer",preconditions:{},effects:{"quality.complexityAnalyzed":!0},cost:1,estimatedDurationMs:15e3,successRate:.95,category:"analysis",qeDomain:"quality-assessment",method:"analyzeComplexity",params:{},implemented:!0},{name:"detect-code-smells",description:"Identify code smells and anti-patterns using static analysis",agentType:"code-analyzer",preconditions:{},effects:{"quality.smellsDetected":!0},cost:1.5,estimatedDurationMs:2e4,successRate:.9,category:"analysis",qeDomain:"code-intelligence",implemented:!1},{name:"analyze-dependencies",description:"Analyze dependency graph and identify circular or outdated dependencies",agentType:"code-analyzer",preconditions:{},effects:{"quality.dependenciesAnalyzed":!0},cost:1,estimatedDurationMs:15e3,successRate:.92,category:"analysis",qeDomain:"code-intelligence",method:"mapDependencies",params:{},implemented:!0},{name:"measure-technical-debt",description:"Calculate technical debt metrics and generate remediation plan",agentType:"code-analyzer",preconditions:{"quality.complexityAnalyzed":!0,"quality.smellsDetected":!0},effects:{"quality.technicalDebtMeasured":!0},cost:2,estimatedDurationMs:25e3,successRate:.88,category:"analysis",qeDomain:"code-intelligence",implemented:!1},{name:"build-knowledge-graph",description:"Build semantic knowledge graph of codebase for intelligent context retrieval",agentType:"qe-intelligence-builder",preconditions:{"quality.dependenciesAnalyzed":!0},effects:{"quality.knowledgeGraphBuilt":!0},cost:3,estimatedDurationMs:6e4,successRate:.85,category:"analysis",qeDomain:"code-intelligence",method:"index",params:{},implemented:!0}],Vl=[{name:"spawn-test-agent",description:"Spawn additional test execution agent for parallel work",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{max:10}},effects:{"fleet.activeAgents":{delta:1}},cost:.5,estimatedDurationMs:5e3,successRate:.95,category:"fleet",qeDomain:"test-execution",implemented:!1},{name:"optimize-fleet-topology",description:"Reconfigure fleet topology for optimal task distribution",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:3}},effects:{"fleet.efficiency":{delta:15}},cost:1,estimatedDurationMs:1e4,successRate:.85,category:"fleet",implemented:!1},{name:"scale-down-fleet",description:"Reduce fleet size to conserve resources during low-activity periods",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:5}},effects:{"fleet.activeAgents":{delta:-2}},cost:.3,estimatedDurationMs:3e3,successRate:.98,category:"fleet",implemented:!1},{name:"spawn-specialist-agent",description:"Spawn a specialized agent for specific domain work",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{max:12},"context.specialistNeeded":!0},effects:{"fleet.activeAgents":{delta:1},"fleet.specialistAvailable":!0},cost:1,estimatedDurationMs:8e3,successRate:.9,category:"fleet",implemented:!1},{name:"rebalance-workload",description:"Redistribute tasks across agents based on current load",agentType:"queen-coordinator",preconditions:{"fleet.activeAgents":{min:2}},effects:{"fleet.workloadBalanced":!0},cost:.5,estimatedDurationMs:5e3,successRate:.92,category:"fleet",implemented:!1}],Ql=[{name:"generate-quality-report",description:"Generate comprehensive quality report combining all metrics",agentType:"qe-quality-gate",preconditions:{"coverage.measured":!0,"quality.unitTestsRun":!0},effects:{"quality.reported":!0},cost:1,estimatedDurationMs:1e4,successRate:.95,category:"quality",qeDomain:"quality-assessment",method:"analyzeQuality",params:{},implemented:!0},{name:"enforce-quality-gate",description:"Check if all quality gates pass and report status",agentType:"qe-quality-gate",preconditions:{"quality.reported":!0},effects:{"quality.gatePassed":!0},cost:.5,estimatedDurationMs:5e3,successRate:.9,category:"quality",qeDomain:"quality-assessment",method:"evaluateGate",params:{},implemented:!0},{name:"validate-requirements",description:"Validate that tests cover all documented requirements",agentType:"qe-requirements-validator",preconditions:{"context.hasRequirements":!0},effects:{"quality.requirementsValidated":!0},cost:2,estimatedDurationMs:2e4,successRate:.88,category:"quality",qeDomain:"requirements-validation",method:"validate",params:{},implemented:!0},{name:"predict-defects",description:"Use ML-based defect prediction to identify high-risk code areas",agentType:"qe-defect-predictor",preconditions:{"quality.complexityAnalyzed":!0,"coverage.measured":!0},effects:{"quality.defectsPredicted":!0},cost:2.5,estimatedDurationMs:3e4,successRate:.82,category:"quality",qeDomain:"defect-intelligence",method:"predictDefects",params:{},implemented:!0},{name:"generate-deployment-report",description:"Generate deployment readiness report with all quality metrics",agentType:"qe-quality-gate",preconditions:{"quality.gatePassed":!0,"quality.securityScanned":!0},effects:{"quality.deploymentReady":!0},cost:1.5,estimatedDurationMs:15e3,successRate:.9,category:"quality",qeDomain:"quality-assessment",method:"getDeploymentAdvice",params:{},implemented:!0}],Wl=[{name:"run-accessibility-audit",description:"Run WCAG 2.2 accessibility audit using axe-core or similar",agentType:"qe-accessibility-tester",preconditions:{"context.hasUI":!0},effects:{"quality.accessibilityAudited":!0},cost:2,estimatedDurationMs:3e4,successRate:.9,category:"quality",qeDomain:"visual-accessibility",method:"runAccessibilityAudit",params:{},implemented:!0},{name:"run-visual-regression",description:"Run visual regression testing with screenshot comparison",agentType:"qe-visual-tester",preconditions:{"context.hasUI":!0},effects:{"quality.visualRegressionRun":!0},cost:3,estimatedDurationMs:6e4,successRate:.85,category:"quality",qeDomain:"visual-accessibility",method:"runVisualTests",params:{},implemented:!0}],ya=[...zl,...jl,...Bl,...Ul,...Hl,...Vl,...Ql,...Wl];function Kl(o){return`action-${o}`}function va(o){return{...o,id:Kl(o.name),executionCount:0}}function $e(){return ya.map(va)}var Tn=[{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"}];Q();import{randomUUID as be}from"crypto";var Lr=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}}},Xl=new Set(["__proto__","constructor","prototype"]),Sn=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=Jr(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.ensureDb().prepare("SELECT COUNT(*) as count FROM goap_actions").get().count===0&&this.seedDefaultActions(),this.backfillActionMethodBindings(),await this.loadActions(),this.initialized=!0,console.log(`[GOAPPlanner] Initialized: ${this.persistence.getDbPath()}`)}seedDefaultActions(){let e=$e(),t=this.ensureDb(),n=t.prepare(`
626
626
  INSERT INTO goap_actions (id, name, description, category, preconditions, effects, cost, qe_domain, agent_type, method, params, implemented)
627
627
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
628
- `);for(let i of e){let a=`action-${Date.now()}-${ve().slice(0,8)}`;n.run(a,i.name,i.description,i.category,JSON.stringify(i.preconditions),JSON.stringify(i.effects),i.cost,i.qeDomain??null,i.agentType??null,i.method??null,i.params?JSON.stringify(i.params):null,i.implemented?1:0)}let r=t.prepare(`
628
+ `);for(let i of e){let a=`action-${Date.now()}-${be().slice(0,8)}`;n.run(a,i.name,i.description,i.category,JSON.stringify(i.preconditions),JSON.stringify(i.effects),i.cost,i.qeDomain??null,i.agentType??null,i.method??null,i.params?JSON.stringify(i.params):null,i.implemented?1:0)}let r=t.prepare(`
629
629
  INSERT INTO goap_goals (id, name, description, conditions, priority, qe_domain)
630
630
  VALUES (?, ?, ?, ?, ?, ?)
631
- `);for(let i of vn){let a=`goal-${Date.now()}-${ve().slice(0,8)}`;r.run(a,i.name,i.description,JSON.stringify(i.conditions),i.priority,i.qeDomain??null)}console.log(`[GOAPPlanner] Seeded ${e.length} actions and ${vn.length} goals`)}backfillActionMethodBindings(){let t=this.ensureDb().prepare(`
631
+ `);for(let i of Tn){let a=`goal-${Date.now()}-${be().slice(0,8)}`;r.run(a,i.name,i.description,JSON.stringify(i.conditions),i.priority,i.qeDomain??null)}console.log(`[GOAPPlanner] Seeded ${e.length} actions and ${Tn.length} goals`)}backfillActionMethodBindings(){let t=this.ensureDb().prepare(`
632
632
  UPDATE goap_actions SET method = ?, params = ?, implemented = 1
633
633
  WHERE name = ? AND (method IS NULL OR implemented = 0)
634
- `);for(let n of Ne())!n.implemented||!n.method||t.run(n.method,n.params?JSON.stringify(n.params):"{}",n.name)}async findPlan(e,t,n){await this.initialize();let r=Date.now();if(this.enablePlanReuse){let l=await this.findSimilarPlan(t,.75);if(l&&this.validatePlanForState(l,e)){this.recordPlanReuse(l.id,!0);let u={...l,id:`plan-${Date.now()}-${ve().slice(0,8)}`,initialState:this.cloneState(e),reusedFrom:l.id,status:"pending"};return await this.savePlan(u),u}}let i=this.getAvailableActions(n),a=this.aStarSearch(e,t,i,n);if(!a)return null;let s={id:`plan-${Date.now()}-${ve().slice(0,8)}`,initialState:this.cloneState(e),goalState:t,actions:a,totalCost:a.reduce((l,u)=>l+u.cost,0),estimatedDurationMs:a.reduce((l,u)=>l+(u.estimatedDurationMs??0),0),status:"pending"};await this.savePlan(s),await this.storePlanSignature(s);let c=Date.now()-r;return c>500&&console.warn(`[GOAPPlanner] Plan finding took ${c}ms (target: <500ms)`),s}aStarSearch(e,t,n,r){if(!this.canAnyActionAffectGoal(n,t))return null;let i=new xr((g,h)=>g.f-h.f),a=new Set,s=new Map,c={state:this.cloneState(e),action:null,parent:null,g:0,h:this.calculateHeuristic(e,t),f:0,depth:0};c.f=c.g+c.h,i.push(c),s.set(this.hashState(e),0);let l=1e4,u=20,d=r?.maxCost??1/0,m=r?.maxDurationMs??1/0,p=0;for(;i.length>0&&p<l;){p++;let g=i.pop();if(this.meetsConditions(g.state,t))return this.reconstructPlan(g);let h=this.hashState(g.state);if(!a.has(h)&&(a.add(h),s.delete(h),!(g.depth>=u)))for(let y of n){if(!this.meetsConditions(g.state,y.preconditions))continue;let v=this.applyAction(g.state,y),f=this.hashState(v);if(a.has(f))continue;let C=g.g+this.getActionCost(y,g.state),b=this.calculateHeuristic(v,t),E=C+b;if(C>d||g.depth*1e3+(y.estimatedDurationMs??0)>m)continue;let T=s.get(f);T!==void 0&&C>=T||(s.set(f,C),i.push({state:v,action:y,parent:g,g:C,h:b,f:E,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 a of n)if(i===a||i.startsWith(a)||a.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 a=this.getStateValue(e,r);if(typeof i=="object"&&i!==null&&"min"in i){let s=i.min;typeof a=="number"&&a<s&&(n+=(s-a)/100)}if(typeof i=="object"&&i!==null&&"max"in i){let s=i.max;typeof a=="number"&&a>s&&(n+=(a-s)/100)}typeof i=="object"&&i!==null&&"eq"in i&&a!==i.eq&&(n+=1),(typeof i=="string"||typeof i=="number"||typeof i=="boolean")&&a!==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 s of r)if(Gl.has(s)){console.warn(`[GOAPPlanner] Blocked prototype pollution attempt: ${t}`);return}let i=e;for(let s=0;s<r.length-1;s++){let c=r[s];Object.hasOwn(i,c)||Object.defineProperty(i,c,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0});let l=Object.getOwnPropertyDescriptor(i,c);if(!l)return;i=l.value}let a=r[r.length-1];Object.defineProperty(i,a,{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,method:t.method??void 0,params:t.params?A(t.params):void 0,implemented:t.implemented===1};this.actions.set(n.id,n)}}async addAction(e){await this.initialize();let t=`action-${Date.now()}-${ve().slice(0,8)}`;this.ensureDb().prepare(`
634
+ `);for(let n of $e())!n.implemented||!n.method||t.run(n.method,n.params?JSON.stringify(n.params):"{}",n.name)}async findPlan(e,t,n){await this.initialize();let r=Date.now();if(this.enablePlanReuse){let l=await this.findSimilarPlan(t,.75);if(l&&this.validatePlanForState(l,e)){this.recordPlanReuse(l.id,!0);let u={...l,id:`plan-${Date.now()}-${be().slice(0,8)}`,initialState:this.cloneState(e),reusedFrom:l.id,status:"pending"};return await this.savePlan(u),u}}let i=this.getAvailableActions(n),a=this.aStarSearch(e,t,i,n);if(!a)return null;let s={id:`plan-${Date.now()}-${be().slice(0,8)}`,initialState:this.cloneState(e),goalState:t,actions:a,totalCost:a.reduce((l,u)=>l+u.cost,0),estimatedDurationMs:a.reduce((l,u)=>l+(u.estimatedDurationMs??0),0),status:"pending"};await this.savePlan(s),await this.storePlanSignature(s);let c=Date.now()-r;return c>500&&console.warn(`[GOAPPlanner] Plan finding took ${c}ms (target: <500ms)`),s}aStarSearch(e,t,n,r){if(!this.canAnyActionAffectGoal(n,t))return null;let i=new Lr((g,h)=>g.f-h.f),a=new Set,s=new Map,c={state:this.cloneState(e),action:null,parent:null,g:0,h:this.calculateHeuristic(e,t),f:0,depth:0};c.f=c.g+c.h,i.push(c),s.set(this.hashState(e),0);let l=1e4,u=20,d=r?.maxCost??1/0,m=r?.maxDurationMs??1/0,p=0;for(;i.length>0&&p<l;){p++;let g=i.pop();if(this.meetsConditions(g.state,t))return this.reconstructPlan(g);let h=this.hashState(g.state);if(!a.has(h)&&(a.add(h),s.delete(h),!(g.depth>=u)))for(let y of n){if(!this.meetsConditions(g.state,y.preconditions))continue;let v=this.applyAction(g.state,y),f=this.hashState(v);if(a.has(f))continue;let C=g.g+this.getActionCost(y,g.state),b=this.calculateHeuristic(v,t),E=C+b;if(C>d||g.depth*1e3+(y.estimatedDurationMs??0)>m)continue;let T=s.get(f);T!==void 0&&C>=T||(s.set(f,C),i.push({state:v,action:y,parent:g,g:C,h:b,f:E,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 a of n)if(i===a||i.startsWith(a)||a.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 a=this.getStateValue(e,r);if(typeof i=="object"&&i!==null&&"min"in i){let s=i.min;typeof a=="number"&&a<s&&(n+=(s-a)/100)}if(typeof i=="object"&&i!==null&&"max"in i){let s=i.max;typeof a=="number"&&a>s&&(n+=(a-s)/100)}typeof i=="object"&&i!==null&&"eq"in i&&a!==i.eq&&(n+=1),(typeof i=="string"||typeof i=="number"||typeof i=="boolean")&&a!==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 s of r)if(Xl.has(s)){console.warn(`[GOAPPlanner] Blocked prototype pollution attempt: ${t}`);return}let i=e;for(let s=0;s<r.length-1;s++){let c=r[s];Object.hasOwn(i,c)||Object.defineProperty(i,c,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0});let l=Object.getOwnPropertyDescriptor(i,c);if(!l)return;i=l.value}let a=r[r.length-1];Object.defineProperty(i,a,{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,method:t.method??void 0,params:t.params?A(t.params):void 0,implemented:t.implemented===1};this.actions.set(n.id,n)}}async addAction(e){await this.initialize();let t=`action-${Date.now()}-${be().slice(0,8)}`;this.ensureDb().prepare(`
635
635
  INSERT INTO goap_actions (
636
636
  id, name, description, agent_type, preconditions, effects,
637
637
  cost, estimated_duration_ms, success_rate, execution_count, category, qe_domain,
@@ -655,14 +655,14 @@ Analyze the requirements above and return the complete QualityCriteriaAnalysis.`
655
655
  INSERT OR REPLACE INTO goap_plan_signatures (
656
656
  id, plan_id, goal_hash, state_vector, action_sequence, total_cost
657
657
  ) VALUES (?, ?, ?, ?, ?, ?)
658
- `).run(`sig-${Date.now()}-${ve().slice(0,8)}`,e.id,t,JSON.stringify(n),JSON.stringify(e.actions.map(r=>r.id)),e.totalCost)}recordPlanReuse(e,t){let n=this.ensureDb(),r=n.prepare("SELECT success_rate, usage_count FROM goap_plan_signatures WHERE plan_id = ?").get(e);if(!r)return;let i=r.usage_count+1,a=.1,s=r.success_rate*(1-a)+(t?1:0)*a;n.prepare(`
658
+ `).run(`sig-${Date.now()}-${be().slice(0,8)}`,e.id,t,JSON.stringify(n),JSON.stringify(e.actions.map(r=>r.id)),e.totalCost)}recordPlanReuse(e,t){let n=this.ensureDb(),r=n.prepare("SELECT success_rate, usage_count FROM goap_plan_signatures WHERE plan_id = ?").get(e);if(!r)return;let i=r.usage_count+1,a=.1,s=r.success_rate*(1-a)+(t?1:0)*a;n.prepare(`
659
659
  UPDATE goap_plan_signatures
660
660
  SET usage_count = ?, success_rate = ?
661
661
  WHERE plan_id = ?
662
- `).run(i,s,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()}-${ve().slice(0,8)}`;return this.ensureDb().prepare(`
662
+ `).run(i,s,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()}-${be().slice(0,8)}`;return this.ensureDb().prepare(`
663
663
  INSERT INTO goap_goals (id, name, description, conditions, priority, qe_domain)
664
664
  VALUES (?, ?, ?, ?, ?, ?)
665
- `).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}},Pr=null;function be(){return Pr||(Pr=new bn),Pr}ba();Qe();ae();k();Q();import{randomUUID as Ar}from"crypto";var $l={maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,parallelExecution:!1,recordWorldState:!0,useUnified:!0,dryRun:!1};function zl(o,e=2e3){try{let t=typeof o=="string"?o:JSON.stringify(o);return t.length>e?`${t.slice(0,e)}...(truncated)`:t}catch{return String(o)}}var qe=class{constructor(e,t,n,r,i){this.getDomainAPI=i;this.planner=e,this.spawner=t,this.config={...$l,...r},this.config.useUnified||(this.db=zr(n??":memory:",{walMode:!1}),this.db.pragma("journal_mode = WAL"))}getDomainAPI;db;planner;spawner;config;currentExecution=null;initialized=!1;unifiedMemory=null;async initialize(){if(!this.initialized){if(this.config.useUnified)try{this.unifiedMemory=U(),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-P5FA6WFK.js")).default(":memory:"),this.db.pragma("journal_mode = WAL"),this.unifiedMemory=null,this.createTables()}else this.createTables();this.initialized=!0}}createTables(){this.db.exec(`
665
+ `).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}},Fr=null;function Ce(){return Fr||(Fr=new Sn),Fr}ka();Xe();oe();k();Q();import{randomUUID as qr}from"crypto";var Yl={maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,parallelExecution:!1,recordWorldState:!0,useUnified:!0,dryRun:!1};function Jl(o,e=2e3){try{let t=typeof o=="string"?o:JSON.stringify(o);return t.length>e?`${t.slice(0,e)}...(truncated)`:t}catch{return String(o)}}var ze=class{constructor(e,t,n,r,i){this.getDomainAPI=i;this.planner=e,this.spawner=t,this.config={...Yl,...r},this.config.useUnified||(this.db=Yr(n??":memory:",{walMode:!1}),this.db.pragma("journal_mode = WAL"))}getDomainAPI;db;planner;spawner;config;currentExecution=null;initialized=!1;unifiedMemory=null;async initialize(){if(!this.initialized){if(this.config.useUnified)try{this.unifiedMemory=U(),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-S7M5R2HS.js")).default(":memory:"),this.db.pragma("journal_mode = WAL"),this.unifiedMemory=null,this.createTables()}else this.createTables();this.initialized=!0}}createTables(){this.db.exec(`
666
666
  CREATE TABLE IF NOT EXISTS goap_execution_steps (
667
667
  id TEXT PRIMARY KEY,
668
668
  plan_id TEXT NOT NULL,
@@ -684,7 +684,7 @@ Analyze the requirements above and return the complete QualityCriteriaAnalysis.`
684
684
  CREATE INDEX IF NOT EXISTS idx_goap_exec_steps_plan ON goap_execution_steps(plan_id);
685
685
  CREATE INDEX IF NOT EXISTS idx_goap_exec_steps_execution ON goap_execution_steps(execution_id);
686
686
  CREATE INDEX IF NOT EXISTS idx_goap_exec_steps_action ON goap_execution_steps(action_id);
687
- `)}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(),a=`exec-${Date.now()}-${Ar().slice(0,8)}`;this.currentExecution={planId:e.id,cancelled:!1};let s={planId:e.id,status:"completed",stepsCompleted:0,stepsFailed:0,totalDurationMs:0,steps:[]},c=r?this.cloneState(r):this.cloneState(e.initialState),l=e.actions.map((u,d)=>({id:`step-${Date.now()}-${Ar().slice(0,8)}`,planId:e.id,action:u,stepOrder:d,status:"pending"}));try{for(let u of l){if(this.currentExecution?.cancelled){s.status="cancelled",s.error="Execution was cancelled";break}this.config.recordWorldState&&(u.worldStateBefore=this.cloneState(c)),t(u);let d=!1,m,p=0,g,h,y=Date.now();for(let f=0;f<=this.config.maxRetries;f++){let C=await this.executeStep(u,c);if(C.success){d=!0,c=C.newState,g=C.output,h=C.agentId;break}m=C.error,p=f,f<this.config.maxRetries&&await this.delay(Math.min(1e3*Math.pow(2,f),5e3))}let v={...u,status:d?"completed":"failed",retries:p,startedAt:new Date(y),completedAt:new Date,durationMs:Date.now()-y,agentId:h,agentOutput:g,worldStateAfter:this.config.recordWorldState?this.cloneState(c):void 0,error:m};if(s.steps.push(v),n(v),d)s.stepsCompleted++,await this.updateActionStats(u.action.id,!0,v.durationMs??0);else if(s.stepsFailed++,await this.updateActionStats(u.action.id,!1,0),this.config.replanOnFailure){let f=await this.replanFromFailure(e,u.stepOrder,c);if(f){let C=await this.executeWithCallbacks(f,t,n,c);s.steps.push(...C.steps),s.stepsCompleted+=C.stepsCompleted,s.stepsFailed+=C.stepsFailed,C.status==="completed"&&C.finalWorldState?c=C.finalWorldState:(s.status="partial",s.error=`Replanning partially succeeded: ${C.error||"unknown error"}`)}else{s.status="failed",s.error=`Step ${u.stepOrder} failed and replanning unsuccessful: ${m}`;break}}else{s.status="failed",s.error=`Step ${u.stepOrder} failed: ${m}`;break}}return s.finalWorldState=c,s.totalDurationMs=Date.now()-i,await this.persistExecutionResult(a,s),s}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}`};if(n.implemented===!1)return{success:!1,newState:t,error:`Action '${n.name}' has no real implementation yet (not simulated \u2014 see GOAPAction.implemented)`};if(!this.config.dryRun&&this.getDomainAPI&&n.implemented===!0)return this.executeRealAction(n,t);let r=this.buildTaskDescription(n);try{let i=new Promise((c,l)=>setTimeout(()=>l(new Error(`Step timeout after ${this.config.stepTimeoutMs}ms`)),this.config.stepTimeoutMs)),a=this.spawner.spawn(n.agentType,r),s=await Promise.race([a,i]);return s.success?{success:!0,newState:this.applyEffects(t,n.effects),output:s.output,agentId:s.agentId}:{success:!1,newState:t,agentId:s.agentId,error:s.error||"Agent execution failed"}}catch(i){return{success:!1,newState:t,error:S(i)}}}async executeRealAction(e,t){if(!e.qeDomain)return{success:!1,newState:t,error:`Action '${e.name}' has no qeDomain to resolve a real API from`};if(!e.method)return{success:!1,newState:t,error:`Action '${e.name}' is marked implemented but has no method binding`};let n;try{n=this.getDomainAPI(e.qeDomain)}catch(i){return{success:!1,newState:t,error:`Failed to resolve domain '${e.qeDomain}': ${S(i)}`}}if(!n)return{success:!1,newState:t,error:`Domain '${e.qeDomain}' is not available (kernel not initialized, or the domain isn't loaded \u2014 try fleet_init)`};let r=n[e.method];if(typeof r!="function")return{success:!1,newState:t,error:`Domain '${e.qeDomain}' has no method '${e.method}'`};try{let i=new Promise((l,u)=>setTimeout(()=>u(new Error(`Step timeout after ${this.config.stepTimeoutMs}ms`)),this.config.stepTimeoutMs)),a=r.call(n,e.params??{}),s=await Promise.race([a,i]);return{success:!0,newState:this.applyEffects(t,e.effects),output:zl(s),agentId:`domain:${e.qeDomain}`}}catch(i){return{success:!1,newState:t,error:S(i)}}}buildTaskDescription(e){let t=`Execute action: ${e.name}`;e.description&&(t+=`
687
+ `)}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(),a=`exec-${Date.now()}-${qr().slice(0,8)}`;this.currentExecution={planId:e.id,cancelled:!1};let s={planId:e.id,status:"completed",stepsCompleted:0,stepsFailed:0,totalDurationMs:0,steps:[]},c=r?this.cloneState(r):this.cloneState(e.initialState),l=e.actions.map((u,d)=>({id:`step-${Date.now()}-${qr().slice(0,8)}`,planId:e.id,action:u,stepOrder:d,status:"pending"}));try{for(let u of l){if(this.currentExecution?.cancelled){s.status="cancelled",s.error="Execution was cancelled";break}this.config.recordWorldState&&(u.worldStateBefore=this.cloneState(c)),t(u);let d=!1,m,p=0,g,h,y=Date.now();for(let f=0;f<=this.config.maxRetries;f++){let C=await this.executeStep(u,c);if(C.success){d=!0,c=C.newState,g=C.output,h=C.agentId;break}m=C.error,p=f,f<this.config.maxRetries&&await this.delay(Math.min(1e3*Math.pow(2,f),5e3))}let v={...u,status:d?"completed":"failed",retries:p,startedAt:new Date(y),completedAt:new Date,durationMs:Date.now()-y,agentId:h,agentOutput:g,worldStateAfter:this.config.recordWorldState?this.cloneState(c):void 0,error:m};if(s.steps.push(v),n(v),d)s.stepsCompleted++,await this.updateActionStats(u.action.id,!0,v.durationMs??0);else if(s.stepsFailed++,await this.updateActionStats(u.action.id,!1,0),this.config.replanOnFailure){let f=await this.replanFromFailure(e,u.stepOrder,c);if(f){let C=await this.executeWithCallbacks(f,t,n,c);s.steps.push(...C.steps),s.stepsCompleted+=C.stepsCompleted,s.stepsFailed+=C.stepsFailed,C.status==="completed"&&C.finalWorldState?c=C.finalWorldState:(s.status="partial",s.error=`Replanning partially succeeded: ${C.error||"unknown error"}`)}else{s.status="failed",s.error=`Step ${u.stepOrder} failed and replanning unsuccessful: ${m}`;break}}else{s.status="failed",s.error=`Step ${u.stepOrder} failed: ${m}`;break}}return s.finalWorldState=c,s.totalDurationMs=Date.now()-i,await this.persistExecutionResult(a,s),s}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}`};if(n.implemented===!1)return{success:!1,newState:t,error:`Action '${n.name}' has no real implementation yet (not simulated \u2014 see GOAPAction.implemented)`};if(!this.config.dryRun&&this.getDomainAPI&&n.implemented===!0)return this.executeRealAction(n,t);let r=this.buildTaskDescription(n);try{let i=new Promise((c,l)=>setTimeout(()=>l(new Error(`Step timeout after ${this.config.stepTimeoutMs}ms`)),this.config.stepTimeoutMs)),a=this.spawner.spawn(n.agentType,r),s=await Promise.race([a,i]);return s.success?{success:!0,newState:this.applyEffects(t,n.effects),output:s.output,agentId:s.agentId}:{success:!1,newState:t,agentId:s.agentId,error:s.error||"Agent execution failed"}}catch(i){return{success:!1,newState:t,error:S(i)}}}async executeRealAction(e,t){if(!e.qeDomain)return{success:!1,newState:t,error:`Action '${e.name}' has no qeDomain to resolve a real API from`};if(!e.method)return{success:!1,newState:t,error:`Action '${e.name}' is marked implemented but has no method binding`};let n;try{n=this.getDomainAPI(e.qeDomain)}catch(i){return{success:!1,newState:t,error:`Failed to resolve domain '${e.qeDomain}': ${S(i)}`}}if(!n)return{success:!1,newState:t,error:`Domain '${e.qeDomain}' is not available (kernel not initialized, or the domain isn't loaded \u2014 try fleet_init)`};let r=n[e.method];if(typeof r!="function")return{success:!1,newState:t,error:`Domain '${e.qeDomain}' has no method '${e.method}'`};try{let i=new Promise((l,u)=>setTimeout(()=>u(new Error(`Step timeout after ${this.config.stepTimeoutMs}ms`)),this.config.stepTimeoutMs)),a=r.call(n,e.params??{}),s=await Promise.race([a,i]);return{success:!0,newState:this.applyEffects(t,e.effects),output:Jl(s),agentId:`domain:${e.qeDomain}`}}catch(i){return{success:!1,newState:t,error:S(i)}}}buildTaskDescription(e){let t=`Execute action: ${e.name}`;e.description&&(t+=`
688
688
 
689
689
  Description: ${e.description}`),t+=`
690
690
 
@@ -711,4 +711,4 @@ Expected effects:`;for(let[n,r]of Object.entries(e.effects))typeof r=="object"&&
711
711
  `);for(let r of t.steps)n.run(r.id,r.planId,e,r.action.id,r.stepOrder,r.status,r.retries,r.startedAt.toISOString(),r.durationMs??null,r.agentId??null,r.agentOutput??null,r.worldStateBefore?JSON.stringify(r.worldStateBefore):null,r.worldStateAfter?JSON.stringify(r.worldStateAfter):null,r.error??null);try{this.db.prepare(`
712
712
  UPDATE goap_plans SET status = ?, executed_at = COALESCE(executed_at, ?), completed_at = ?
713
713
  WHERE id = ?
714
- `).run(t.status==="completed"?"completed":t.status==="cancelled"?"cancelled":"failed",new Date(Date.now()-t.totalDurationMs).toISOString(),new Date().toISOString(),t.planId)}catch(r){console.warn("[PlanExecutor] Failed to update goap_plans status (non-fatal):",r)}}async updateActionStats(e,t,n){try{"updateActionStats"in this.planner&&await this.planner.updateActionStats(e,t,n)}catch(r){console.warn("[PlanExecutor] Failed to update action stats:",r)}}meetsConditions(e,t){for(let[n,r]of Object.entries(t))if(!this.checkCondition(e,n,r))return!1;return!0}checkCondition(e,t,n){let r=this.getStateValue(e,t);return typeof n=="string"||typeof n=="number"||typeof n=="boolean"?r===n:!(typeof n=="object"&&n!==null&&("min"in n&&n.min!==void 0&&(typeof r!="number"||r<n.min)||"max"in n&&n.max!==void 0&&(typeof r!="number"||r>n.max)||"eq"in n&&n.eq!==void 0&&r!==n.eq))}applyEffects(e,t){let n=this.cloneState(e);for(let[r,i]of Object.entries(t))this.applyEffect(n,r,i);return n}applyEffect(e,t,n){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean"){this.setStateValue(e,t,n);return}if(typeof n=="object"&&n!==null){let r=this.getStateValue(e,t);if("set"in n&&n.set!==void 0&&this.setStateValue(e,t,n.set),"delta"in n&&n.delta!==void 0&&typeof r=="number"){let i=Math.max(0,Math.min(100,r+n.delta));this.setStateValue(e,t,i)}}}getStateValue(e,t){let n=t.split("."),r=e;for(let i of n){if(r==null)return;r=r[i]}return r}setStateValue(e,t,n){let r=t.split("."),i=new Set(["__proto__","constructor","prototype"]);for(let c of r)if(i.has(c)){console.warn(`[PlanExecutor] Blocked prototype pollution attempt: ${t}`);return}let a=e;for(let c=0;c<r.length-1;c++){let l=r[c];Object.hasOwn(a,l)||Object.defineProperty(a,l,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0});let u=Object.getOwnPropertyDescriptor(a,l);if(!u)return;a=u.value}let s=r[r.length-1];Object.defineProperty(a,s,{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}},Ge=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-${Ar().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 kr(o,e){let t=new Ge({successRate:e?.successRate??1});return new qe(o,t,e?.dbPath,e?.config)}var st=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=be(),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 l=await n.getGoals(),u=l.find(d=>d.name===e.goal);if(!u){let d=l.map(m=>m.name).join(", ");return{success:!1,error:`Unknown goal: ${e.goal}. Available goals: ${d||"none (seed actions first)"}`}}r=u.conditions,i=u.name}else r=e.goal,i="custom";let a=e.currentState||await this.detectCurrentState(),s=e.constraints?{maxCost:e.constraints.maxCost,maxDurationMs:e.constraints.maxDurationMs,requiredAgentTypes:e.constraints.requiredAgentTypes,excludedActions:e.constraints.excludedActions}:void 0,c=await n.findPlan(a,r,s);return c?(this.markAsRealData(),{success:!0,data:{planId:c.id,goal:e.goal,actions:c.actions.map(l=>({name:l.name,agentType:l.agentType,cost:l.cost,category:l.category,description:l.description})),totalCost:c.totalCost,estimatedDurationMs:c.estimatedDurationMs,stepCount:c.actions.length,reusedFrom:c.reusedFrom,similarityScore:c.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:S(n)}}}async detectCurrentState(){return{...it}}};k();var at=class extends x{planner=null;executor=null;config={name:"qe/planning/goap_execute",description:"Execute a GOAP plan. Each action dispatches to a real domain API method when the action is marked implemented and a kernel is available (run fleet_init first); actions with no real implementation, or with no domain/kernel available, fail with a specific reason rather than reporting a fabricated success. Supports dry-run mode to preview the plan without executing anything.",domain:"coordination",schema:this.buildSchema(),timeout:3e5};buildSchema(){return{type:"object",properties:{planId:{type:"string",description:"ID of plan to execute (from goap_plan result)"},dryRun:{type:"boolean",description:"Simulate execution without spawning agents (default: false)",default:!1},stepByStep:{type:"boolean",description:"Execute one step at a time (default: false)",default:!1},maxRetries:{type:"number",description:"Max retries per failed step (default: 2)",default:2,minimum:0,maximum:5}},required:["planId"]}}async getPlanner(){return this.planner||(this.planner=be(),await this.planner.initialize()),this.planner}async getExecutor(e){if(!this.executor){let t=await this.getPlanner(),n=r=>e?.getDomainAPI(r);this.executor=new qe(t,new Ge,void 0,{maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,parallelExecution:!1,recordWorldState:!0},n),await this.executor.initialize()}return this.executor}resetInstanceCache(){this.planner=null,this.executor=null}async execute(e,t){try{let r=await(await this.getPlanner()).getPlan(e.planId);if(!r)return{success:!1,error:`Plan not found: ${e.planId}. Create a plan first using goap_plan.`};if(e.dryRun)return this.markAsRealData(),{success:!0,data:{planId:r.id,mode:"dry-run",status:"completed",stepsCompleted:r.actions.length,stepsFailed:0,totalDurationMs:r.estimatedDurationMs,steps:r.actions.map(c=>({action:c.name,status:"would-execute",retries:0,durationMs:c.estimatedDurationMs}))}};let i=await At(t),a=await this.getExecutor(i);if(a.isExecuting())return{success:!1,error:"Another plan is currently executing. Wait for completion or cancel it."};let s=await a.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(c=>({action:c.action.name,status:c.status,retries:c.retries,durationMs:c.durationMs,error:c.error})),error:s.error},error:s.status!=="completed"?s.error:void 0}}catch(n){return{success:!1,error:S(n)}}}};k();var ot=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=be(),await this.planner.initialize()),this.planner}async getExecutor(){if(!this.executor){let e=await this.getPlanner();this.executor=kr(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:S(n)}}}async getWorldState(){let e={...it};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=Ne(),a=e?i.filter(c=>c.category===e):i;r=a.slice(0,t).map((c,l)=>({id:`action-${l}`,name:c.name,category:c.category,agentType:c.agentType,cost:c.cost,successRate:c.successRate}));let s={};for(let c of i)s[c.category]=(s[c.category]||0)+1;return this.markAsRealData(),{success:!0,data:{type:"actions",data:{actions:r,count:a.length,byCategory:s}}}}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();Qe();ae();k();k();Qe();var ct={HEALTH:"qe/mincut/health",ANALYZE:"qe/mincut/analyze",STRENGTHEN:"qe/mincut/strengthen"};function _r(){return Mn()}function Wl(){return Dn()}var Mr=class extends x{config={name:ct.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=_r(),r=Wl(),i=ce();if(e.agents)for(let l of e.agents)n.hasVertex(l.id)||n.addVertex({id:l.id,type:"agent",domain:l.domain,weight:l.weight??1,createdAt:new Date});if(e.edges)for(let l of e.edges)n.hasVertex(l.source)&&n.hasVertex(l.target)&&(n.hasEdge(l.source,l.target)||n.addEdge({source:l.source,target:l.target,weight:l.weight??1,type:"coordination",bidirectional:!0}));let a=r.checkHealth(),s=e.includeWeakVertices!==!1?i.findWeakVertices(n):[],c={health:{status:a.status,minCutValue:a.minCutValue,healthyThreshold:a.healthyThreshold,warningThreshold:a.warningThreshold,weakVertexCount:a.weakVertexCount,trend:a.trend},topology:{vertexCount:n.vertexCount,edgeCount:n.edgeCount,isConnected:n.isConnected()}};return e.includeWeakVertices!==!1&&s.length>0&&(c.weakVertices=s.map(l=>({id:l.vertexId,domain:l.vertex?.domain,weightedDegree:l.weightedDegree,riskScore:l.riskScore,reason:l.reason}))),e.includeHistory&&(c.history=a.history.map(l=>({timestamp:l.timestamp,value:l.value}))),this.markAsRealData(),{success:!0,data:c,metadata:this.createMetadata(t.startTime,t.requestId)}}},Dr=class extends x{config={name:ct.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=_r(),r=ce(),i=r.getMinCutValue(n),a=r.getMinDegreeVertex(n),s=r.findWeakVertices(n,e.weaknessThreshold),c=r.suggestEdgeAdditions(n,2),l={minCutValue:i,minDegreeVertex:a,weakVertices:s.map(u=>({id:u.vertexId,weightedDegree:u.weightedDegree,riskScore:u.riskScore,reason:u.reason,suggestions:u.suggestions.map(d=>({type:d.type,priority:d.priority,estimatedImprovement:d.estimatedImprovement}))})),suggestedEdges:c.map(u=>({source:u.source,target:u.target,weight:u.weight}))};return e.includePartitioningPoints&&(l.partitioningPoints=r.findPartitioningPoints(n)),this.markAsRealData(),{success:!0,data:l,metadata:this.createMetadata(t.startTime,t.requestId)}}},Ir=class extends x{config={name:ct.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=_r(),r=ce(),i=r.getMinCutValue(n),a=e.targetImprovement??1,s=r.suggestEdgeAdditions(n,a),c=[];if(e.apply)for(let u of s)n.addEdge({source:u.source,target:u.target,weight:u.weight,type:"coordination",bidirectional:!0}),c.push({type:"add_edge",source:u.source,target:u.target,weight:u.weight});else for(let u of s)c.push({type:"add_edge",source:u.source,target:u.target,weight:u.weight});let l=r.getMinCutValue(n);return this.markAsRealData(),{success:!0,data:{beforeMinCut:i,afterMinCut:e.apply?l:i+a,improvement:e.apply?l-i:a,actionsApplied:c,applied:e.apply??!1},metadata:this.createMetadata(t.startTime,t.requestId)}}},da=[new Mr,new Dr,new Ir];k();var Or=null,Cn=null;async function lt(){return Or||Cn||(Cn=(async()=>{let o=Lt({embedding:{model:"all-MiniLM-L6-v2",cacheSize:1e3,normalize:!0,hyperbolic:!1,curvature:-1},autoInitialize:!1});return await o.initialize(),Or=o,console.error("[EmbeddingTool] ONNX adapter initialized"),o})(),Cn)}var $e=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 lt(),i=await r.generateEmbedding(e.text);e.hyperbolic&&(i=r.toHyperbolic(i));let a=performance.now()-n;return this.markAsRealData(),{success:!0,data:{embedding:Array.from(i.vector),dimension:i.dimensions,isHyperbolic:i.isHyperbolic,latencyMs:a,model:i.model}}}catch(r){return{success:!1,error:`Embedding generation failed: ${S(r)}`}}}},ze=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 lt(),i=e.metric||"cosine",a=i==="cosine"?"cosine":i==="euclidean"?"euclidean":"poincare",s=await r.compareSimilarity(e.text1,e.text2,a),c=performance.now()-n;return this.markAsRealData(),{success:!0,data:{similarity:s,metric:i,isSimilar:s>.7,latencyMs:c}}}catch(r){return{success:!1,error:`Similarity comparison failed: ${S(r)}`}}}},je=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 lt()).searchByText(e.query,{metric:"cosine",topK:e.topK??10,threshold:e.threshold??.5,namespace:e.namespace}),a=performance.now()-n;return this.markAsRealData(),{success:!0,data:{results:i.map(s=>({text:s.text,score:s.score,metadata:s.metadata})),totalFound:i.length,latencyMs:a}}}catch(r){return{success:!1,error:`Search failed: ${S(r)}`}}}},Be=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 lt(),i=e.namespace||"default",a=await r.generateAndStore(e.text,{id:e.id,namespace:i,customData:e.metadata}),s=performance.now()-n;return this.markAsRealData(),{success:!0,data:{id:a.id,namespace:a.namespace||i,latencyMs:s}}}catch(r){return{success:!1,error:`Store failed: ${S(r)}`}}}},Ue=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 lt(),r=n.getStats(),i=await n.getHealth(),a=r.cacheHits+r.cacheMisses,s=a>0?r.cacheHits/a:0;return this.markAsRealData(),{success:!0,data:{totalGenerated:r.totalGenerated,vectorsStored:r.vectorsStored,cache:{hits:r.cacheHits,misses:r.cacheMisses,hitRate:s},model:{name:r.currentModel,dimension:r.currentModel==="all-MiniLM-L6-v2"?384:768},healthy:i.available}}}catch(n){return{success:!1,error:`Stats failed: ${S(n)}`}}}},Kl=new $e,Xl=new ze,Yl=new je,Jl=new Be,Zl=new Ue;k();var eu={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"]},ut=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:eu,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 a of r)if(!a.embedding||!Array.isArray(a.embedding))return{success:!1,error:`Node ${a.id} has invalid embedding - must be an array of numbers`};try{let a=await this.getService(),s=r.map(m=>({id:m.id,embedding:m.embedding,weight:m.weight??1,metadata:m.metadata})),c=await a.checkCoherence(s),l=[...c.recommendations,...this.generateAdditionalRecommendations(c,i)],u=c.contradictions.map(m=>({nodeIds:m.nodeIds,severity:String(m.severity),description:m.description||`Contradiction between nodes ${m.nodeIds[0]} and ${m.nodeIds[1]}`})),d=Date.now()-n;return this.markAsRealData(),{success:!0,data:{isCoherent:c.isCoherent,energy:c.energy,lane:c.lane,contradictions:u,recommendations:l,nodeCount:r.length,executionTimeMs:d,usedFallback:c.usedFallback}}}catch(a){return a instanceof Error&&a.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:S(a)}}}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}};$r();k();var ZT=vt.create("qe-unified-memory");var tu={"test-suites":{dimensions:me.DIMENSIONS,M:8,efConstruction:100,efSearch:50,metric:"cosine",namespace:"test-suites-hnsw",maxElements:1e5},coverage:{dimensions:me.DIMENSIONS,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},defects:{dimensions:me.DIMENSIONS,M:32,efConstruction:400,efSearch:200,metric:"cosine",namespace:"defects-hnsw",maxElements:1e5},quality:{dimensions:me.DIMENSIONS,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"quality-hnsw",maxElements:1e5},learning:{dimensions:me.DIMENSIONS,M:24,efConstruction:300,efSearch:150,metric:"cosine",namespace:"learning-hnsw",maxElements:1e5},coordination:{dimensions:me.DIMENSIONS,M:8,efConstruction:100,efSearch:50,metric:"cosine",namespace:"coordination-hnsw",maxElements:5e4}},nu={enableHNSW:{"test-suites":!0,coverage:!0,defects:!0,quality:!0,learning:!0,coordination:!0},defaultNamespace:"qe-unified",enableCrossDomainSearch:!0,embeddingDimension:me.DIMENSIONS};$r();k();import{randomUUID as ru}from"crypto";var Fr=vt.create("MemoryAuditor"),Lr={batchSize:50,energyThreshold:.4,hotspotThreshold:.6,maxRecommendations:10},Tn=class{constructor(e,t,n=Lr){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,a=0;for(let[p,g]of Object.entries(n)){if(g.length<2)continue;let h=this.patternsToNodes(g),y=await this.coherenceService.checkCoherence(h);a+=y.energy,i+=y.contradictions.length,y.energy>this.config.hotspotThreshold&&r.push({domain:p,patternIds:g.map(v=>v.id),energy:y.energy,description:this.describeHotspot(y,p)})}let s=Object.keys(n).length,c=s>0?a/s:0,l=await this.identifyHotspots(e),u=await this.generateRecommendations(l,e),d=Date.now()-t,m={totalPatterns:e.length,scannedPatterns:e.length,contradictionCount:i,globalEnergy:c,hotspots:l,recommendations:u,duration:d,timestamp:new Date};return await this.emitEvent("memory:audit_completed",{result:m,timestamp:new Date}),m}catch(n){try{await this.emitEvent("memory:audit_failed",{error:S(n),timestamp:new Date})}catch(r){Fr.warn("Failed to emit audit_failed event",{error:S(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 a=this.patternsToNodes(i),s=await this.coherenceService.checkCoherence(a);s.energy>this.config.hotspotThreshold&&t.push({domain:r,patternIds:i.map(c=>c.id),energy:s.energy,description:this.describeHotspot(s,r)})}return t}async generateRecommendations(e,t){let n=[],r=new Map(t.map(i=>[i.id,i]));for(let i of e){let a=i.patternIds.map(u=>r.get(u)).filter(u=>u!==void 0),s=this.findDuplicates(a);s.length>0&&n.push({type:"merge",patternIds:s,reason:`Detected ${s.length} similar patterns in ${i.domain} domain`,priority:"high"});let c=this.findOutdated(a);c.length>0&&n.push({type:"remove",patternIds:c,reason:`Found ${c.length} outdated patterns with low usage/success`,priority:"medium"}),i.energy>.7&&n.push({type:"review",patternIds:i.patternIds,reason:`Critical coherence energy (${i.energy.toFixed(2)}) in ${i.domain}`,priority:"high"});let l=this.findBroadPatterns(a);l.length>0&&n.push({type:"split",patternIds:l,reason:`Found ${l.length} overly generic patterns that should be specialized`,priority:"low"})}return n.sort((i,a)=>this.priorityValue(a.priority)-this.priorityValue(i.priority)).slice(0,this.config.maxRecommendations)}async runBackgroundAudit(e){if(this.isAuditing){Fr.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:S(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()}-${ru().split("-")[0]}`,type:e,source:"learning-optimization",timestamp:new Date,payload:t})}catch(n){Fr.warn("Failed to emit event",{eventType:e,error:S(n)})}}};function Nr(o,e,t){return new Tn(o,e,{...Lr,...t})}k();var iu={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:[]},dt=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:iu,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 a=await this.getService();this.auditor||(this.auditor=Nr(a,void 0,{energyThreshold:i,hotspotThreshold:i+.2,maxRecommendations:10}));let s=await F(),c=kn(s,{namespace:n,embeddingDimension:384});await c.initialize();let l=await c.search("",{limit:r,useVectorSearch:!1}),u=l.success?l.value.map(p=>p.pattern):[],d;u.length>0?d=await this.auditor.auditPatterns(u):d={totalPatterns:0,scannedPatterns:0,contradictionCount:0,globalEnergy:0,hotspots:[],recommendations:[],duration:0,timestamp:new Date};let m=this.calculateHealthScore(d);return this.markAsRealData(),{success:!0,data:{totalPatterns:d.totalPatterns,scannedPatterns:d.scannedPatterns,contradictionCount:d.contradictionCount,globalEnergy:d.globalEnergy,hotspots:d.hotspots.map(p=>({domain:p.domain,patternIds:p.patternIds,energy:p.energy,description:p.description})),recommendations:d.recommendations.map(p=>({type:p.type,patternIds:p.patternIds,reason:p.reason,priority:p.priority})),durationMs:d.duration,timestamp:d.timestamp.toISOString(),healthScore:m}}}catch(a){return a instanceof Error&&a.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:S(a)}}}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 su={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"]},mt=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:su,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 a=await this.getService(),s=r.map(m=>({agentId:m.agentId,agentType:m.agentType||"worker",verdict:m.verdict,confidence:m.confidence,reasoning:m.reasoning,timestamp:new Date})),c=await a.verifyConsensus(s),l=c.recommendation,u=r.reduce((m,p)=>m+p.confidence,0)/r.length;u<i&&(l=`Low average confidence (${(u*100).toFixed(1)}%) - consider gathering more evidence. `+l);let d=Date.now()-n;return this.markAsRealData(),{success:!0,data:{isValid:c.isValid,isFalseConsensus:c.isFalseConsensus,confidence:c.confidence,fiedlerValue:c.fiedlerValue,collapseRisk:c.collapseRisk,recommendation:l,usedFallback:c.usedFallback,executionTimeMs:d}}}catch(a){if(a instanceof Error&&a.message.includes("WASM")){let s=this.simpleMajorityAnalysis(r);return this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{...s,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:S(a)}}}simpleMajorityAnalysis(e){let t=new Map;for(let a of e){let s=String(a.verdict);t.set(s,(t.get(s)||0)+1)}let n=0;for(let a of t.values())a>n&&(n=a);let r=n/e.length,i=e.reduce((a,s)=>a+s.confidence,0)/e.length;return{isValid:r>=.5&&i>=.5,isFalseConsensus:!1,confidence:i,fiedlerValue:0,collapseRisk:1-r}}};k();var au={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"]},pt=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:au,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 a=await this.getService(),s={agents:r.agents.map(g=>({agentId:g.agentId,agentType:g.agentType||"worker",health:Number.isFinite(g.health)?g.health:1,beliefs:[],lastActivity:new Date,errorCount:g.errorCount??0,successRate:Number.isFinite(g.successRate)?g.successRate:1})),activeTasks:Number.isFinite(r.activeTasks)?r.activeTasks:0,pendingTasks:Number.isFinite(r.pendingTasks)?r.pendingTasks:0,errorRate:Number.isFinite(r.errorRate)?r.errorRate:0,utilization:Number.isFinite(r.utilization)?r.utilization:0,timestamp:new Date},c=await a.predictCollapse(s),l=Number.isFinite(c.risk)?c.risk:0,u=this.categorizeRisk(l),d=[...c.recommendations,...this.generateAdditionalRecommendations(c,r)],m=Date.now()-n;this.markAsRealData();let p=u==="high"||u==="critical"||u==="medium"&&l>=i;return{success:!0,data:{risk:l,isAtRisk:p,riskLevel:u,fiedlerValue:c.fiedlerValue,collapseImminent:c.collapseImminent,weakVertices:c.weakVertices,recommendations:d,executionTimeMs:m,usedFallback:c.usedFallback}}}catch(a){if(a instanceof Error&&a.message.includes("WASM")){let s=this.heuristicAnalysis(r,i);return this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{...s,recommendations:["Running in fallback mode (heuristic analysis)","Install prime-radiant-advanced-wasm for spectral collapse prediction",...s.recommendations],usedFallback:!0,executionTimeMs:Date.now()-n}}}return{success:!1,error:S(a)}}}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=[],a=Number.isFinite(e.errorRate)?e.errorRate:0,s=Number.isFinite(e.utilization)?e.utilization:0,c=Number.isFinite(e.pendingTasks)?e.pendingTasks:0,l=Number.isFinite(e.activeTasks)?e.activeTasks:0,u=e.agents.map(h=>Number.isFinite(h.health)?h.health:1),d=u.length>0?u.reduce((h,y)=>h+y,0)/u.length:1;n+=(1-d)*.3,n+=Math.min(.25,a*2.5),s>.7&&(n+=(s-.7)*.5);let m=c/Math.max(1,l);m>1&&(n+=Math.min(.2,(m-1)*.1)),e.agents.forEach((h,y)=>{(u[y]<.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 ma=[new ut,new dt,new mt,new pt],pa={COHERENCE_CHECK:"qe/coherence/check",COHERENCE_AUDIT:"qe/coherence/audit",COHERENCE_CONSENSUS:"qe/coherence/consensus",COHERENCE_COLLAPSE:"qe/coherence/collapse"};var gt=(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))(gt||{});var Sn=class{enabledHeuristics;minConfidence;constructor(e={}){this.enabledHeuristics=e.enabledHeuristics||Object.values(gt),this.minConfidence=e.minConfidence||.7}async applyAll(e,t,n,r){let i=[];for(let a of this.enabledHeuristics){let s=await this.apply(a,e,t,n,r);i.push(s)}return i}async apply(e,t,n,r,i){let a=this.getHeuristicCategory(e),s=[],c=[],l=[],u=75;switch(e){case"H7.4-consistency-analysis":t.domMetrics?.semanticStructure?.hasHeader&&t.domMetrics?.semanticStructure?.hasFooter?(u=85,s.push("Consistent page structure with header and footer")):(u=60,l.push("Add consistent header/footer structure"));break;case"H7.2-intuitive-design":{let d=t.domMetrics?.semanticStructure?.hasNav,m=t.accessibility?.focusableElementsCount||0;d&&m>10?(u=82,s.push("Intuitive navigation and interaction design")):(u=55,c.push({description:"Navigation or interaction patterns unclear",severity:"medium"}));break}case"H7.1-exactness-and-clarity":{u=70;let d=t.domMetrics?.semanticStructure,m=[d?.hasHeader,d?.hasMain,d?.hasNav,d?.hasFooter].filter(Boolean).length;u=50+m*10,m>=3?s.push("Strong visual hierarchy with semantic HTML elements"):m>=2?(s.push("Moderate visual hierarchy - some semantic elements present"),l.push("Add more semantic HTML5 elements for clarity")):(c.push({description:"Weak visual hierarchy - missing semantic structure",severity:"high"}),l.push("Implement semantic HTML5: header, nav, main, footer")),t.metadata?.description&&t.metadata.description.length>20&&(u+=10,s.push("Page has descriptive metadata"));break}case"H7.3-counter-intuitive-design":{u=85;let d=!t.domMetrics?.semanticStructure?.hasNav&&(t.domMetrics?.interactiveElements||0)>10,m=!t.domMetrics?.semanticStructure?.hasHeader&&!t.domMetrics?.semanticStructure?.hasFooter;d&&(u=45,c.push({description:"Navigation structure may be counter-intuitive",severity:"high"}),l.push("Add semantic navigation elements")),m&&(u-=15,c.push({description:"Page structure lacks expected header/footer",severity:"medium"})),u>75&&s.push("No counter-intuitive design patterns detected");break}case"H5.2-user-feelings-impact":{let d=t.accessibility?.altTextsCoverage||0,m=t.performance?.loadTime||0,p=t.accessibility?.ariaLabelsCount||0,g=t.accessibility?.focusableElementsCount||0;u=60,d>=90?(u+=20,s.push("Excellent accessibility (90%+ alt coverage) creates inclusive, positive experience")):d>=70?(u+=12,s.push("Good accessibility creates generally positive user feelings")):d<50&&(u-=15,c.push({description:"Poor accessibility (<50% alt coverage) frustrates users with disabilities",severity:"high"}),l.push("Improve alt text coverage to at least 80% for better accessibility")),p>5&&(u+=8,s.push("Strong ARIA labeling enhances screen reader experience")),m<1500?(u+=15,s.push("Very fast load time (<1.5s) delights users")):m<2500?(u+=8,s.push("Fast load time enhances user satisfaction")):m>4e3?(u-=20,c.push({description:"Very slow load time (>4s) causes significant frustration",severity:"critical"}),l.push("Optimize page load time - target under 2.5 seconds")):m>3e3&&(u-=12,c.push({description:"Slow load time causes user frustration",severity:"high"})),t.errorIndicators?.hasErrorMessages&&(u-=12,c.push({description:"Visible errors reduce user confidence and satisfaction",severity:"high"}),l.push("Review and fix visible error messages")),g>20?(u+=5,s.push("Rich interactive elements provide user control and engagement")):g<5&&(u-=8,c.push({description:"Limited interactivity may feel restrictive",severity:"medium"})),u=Math.max(20,Math.min(100,u));break}case"H5.1-gui-flow-impact":{let d=t.domMetrics?.interactiveElements||0,m=t.domMetrics?.forms||0;d>20&&(u=75,s.push(`${d} interactive elements provide user control`)),m>0&&(s.push(`${m} forms impact user input flows`),u=Math.min(100,u+10)),d===0&&(u=30,c.push({description:"Limited user interaction capability",severity:"high"}));break}case"H5.3-cross-functional-impact":u=70,t.accessibility&&(t.accessibility.altTextsCoverage||0)<100&&s.push("Content team needed for alt text creation"),t.performance&&(t.performance.loadTime||0)>2e3&&s.push("Engineering team needed for performance optimization"),n.complexity==="complex"&&s.push("QA team needed for comprehensive testing"),u=70+s.length*5;break;case"H5.4-data-dependent-impact":t.domMetrics?.forms&&t.domMetrics.forms>0?(u=75,s.push(`${t.domMetrics.forms} forms depend on backend data processing`)):(u=50,s.push("Limited data-dependent features"));break;case"H1.1-problem-understanding":u=n.clarityScore,n.clarityScore>80?s.push("Problem is well-defined"):c.push({description:"Problem clarity needs improvement",severity:"medium"}),s.push(...n.breakdown);break;case"H1.2-rule-of-three":u=n.potentialFailures.length>=3?85:60,s.push(`${n.potentialFailures.length} potential failure modes identified`),n.potentialFailures.length<3&&l.push("Identify at least 3 potential failure modes (Rule of Three)");break;case"H1.3-problem-complexity":u=n.complexity==="simple"?90:n.complexity==="moderate"?75:60,s.push(`Problem complexity: ${n.complexity}`);break;case"H2.1-user-needs-identification":{u=r.alignmentScore,s.push(`${r.needs.length} user needs identified`);let d=r.needs.filter(m=>m.priority==="must-have").length;s.push(`${d} must-have features`),r.challenges.length>0&&c.push({description:`${r.challenges.length} user need challenges found`,severity:"medium"});break}case"H2.2-user-needs-suitability":u=r.suitability==="excellent"?95:r.suitability==="good"?80:r.suitability==="adequate"?65:45,s.push(`User needs suitability: ${r.suitability}`);break;case"H2.3-user-needs-validation":{let d=r.needs.filter(m=>m.addressed).length;u=r.needs.length>0?d/r.needs.length*100:50,s.push(`${d}/${r.needs.length} needs validated and addressed`);break}case"H3.1-business-needs-identification":u=i.alignmentScore,s.push(`Primary goal: ${i.primaryGoal}`),s.push(`${i.kpisAffected.length} KPIs affected`),s.push(`${i.crossTeamImpact.length} cross-team impacts`);break;case"H3.2-user-vs-business-balance":{let d=100-Math.abs(r.alignmentScore-i.alignmentScore);u=d,d>80?s.push("Good balance between user and business needs"):(c.push({description:"Imbalance between user and business priorities",severity:"medium"}),l.push("Align user and business objectives more closely"));break}case"H3.3-kpi-impact-analysis":u=i.impactsKPIs?85:50,s.push(`KPIs impacted: ${i.kpisAffected.join(", ")}`),i.compromisesUX&&(c.push({description:"Business ease compromises user experience",severity:"high"}),u-=20);break;case"H4.1-oracle-problem-detection":u=75,s.push("Oracle problem detection capability active");break;case"H4.2-what-must-not-change":u=80,t.domMetrics?.semanticStructure?.hasMain&&s.push("Main content structure is immutable"),t.accessibility&&(t.accessibility.focusableElementsCount||0)>0&&s.push("Keyboard navigation support must be maintained");break;case"H4.3-supporting-data-analysis":{u=75,(t.domMetrics?.forms||0)>0||(t.domMetrics?.interactiveElements||0)>20?(u=82,s.push("Sufficient data points for informed decision-making")):(u=60,c.push({description:"Limited data for comprehensive analysis",severity:"medium"}),l.push("Collect more user interaction data"));break}case"H6.1-competitive-analysis":u=70,s.push("Competitive analysis capability available"),t.domMetrics?.semanticStructure?.hasNav&&t.domMetrics?.interactiveElements&&t.domMetrics.interactiveElements>15?(u=78,s.push("Navigation and interaction patterns follow industry standards")):l.push("Compare interaction patterns with leading competitors");break;case"H6.2-domain-inspiration":{u=72,t.accessibility&&(t.accessibility.ariaLabelsCount||0)>0?(u=80,s.push("Modern accessibility patterns show domain inspiration")):l.push("Research domain-specific design patterns and best practices");break}case"H6.3-innovative-solutions":{u=65,(t.accessibility?.landmarkRoles||0)>3?(u=75,s.push("Advanced accessibility features show innovative thinking")):l.push("Explore innovative UX patterns to differentiate experience");break}default:a==="user-needs"?u=r.alignmentScore:a==="business-needs"?u=i.alignmentScore:a==="problem"&&(u=n.clarityScore);break}return{id:e,name:this.getHeuristicName(e),category:a,applied:!0,score:Math.min(100,Math.max(0,u)),findings:s,issues:c,recommendations:l}}getHeuristicCategory(e){return e.includes("problem")?"problem":e.includes("user-needs")||e.includes("user-vs")?"user-needs":e.includes("business")?"business-needs":e.includes("oracle")||e.includes("balance")||e.includes("what-must")||e.includes("supporting-data")?"balance":e.includes("impact")||e.includes("gui-flow")||e.includes("feelings")||e.includes("cross-functional")||e.includes("data-dependent")?"impact":e.includes("competitive")||e.includes("inspiration")||e.includes("innovative")?"creativity":"design"}getHeuristicName(e){return{"H1.1-problem-understanding":"Problem Understanding","H1.2-rule-of-three":"Rule of Three","H1.3-problem-complexity":"Problem Complexity","H2.1-user-needs-identification":"User Needs Identification","H2.2-user-needs-suitability":"User Needs Suitability","H2.3-user-needs-validation":"User Needs Validation","H3.1-business-needs-identification":"Business Needs Identification","H3.2-user-vs-business-balance":"User vs Business Balance","H3.3-kpi-impact-analysis":"KPI Impact Analysis","H4.1-oracle-problem-detection":"Oracle Problem Detection","H4.2-what-must-not-change":"What Must Not Change","H4.3-supporting-data-analysis":"Supporting Data Analysis","H5.1-gui-flow-impact":"GUI Flow Impact","H5.2-user-feelings-impact":"User Feelings Impact","H5.3-cross-functional-impact":"Cross-Functional Impact","H5.4-data-dependent-impact":"Data-Dependent Impact","H6.1-competitive-analysis":"Competitive Analysis","H6.2-domain-inspiration":"Domain Inspiration","H6.3-innovative-solutions":"Innovative Solutions","H7.1-exactness-and-clarity":"Exactness & Clarity","H7.2-intuitive-design":"Intuitive Design","H7.3-counter-intuitive-design":"Counter-Intuitive Design","H7.4-consistency-analysis":"Consistency Analysis"}[e]||e}};var En=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(),a=(e.metadata?.description||"").toLowerCase();return(i.includes("hotel")||i.includes("booking")||i.includes("travel")||i.includes("shop")||i.includes("store")||a.includes("book"))&&(n.kpisAffected.some(s=>s.toLowerCase().includes("conversion")||s.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(s=>this.meetsMinimumSeverity(s.severity))}meetsMinimumSeverity(e){let t=["low","medium","high","critical"],n=t.indexOf(this.minSeverity);return t.indexOf(e)>=n}};var wn=class o{static LOAD_TIME_FEELINGS=[[4001,1/0,"Impatient - Very slow load time causes significant frustration"],[3001,4e3,"Impatient - Slow load time causes frustration"],[2001,3e3,"Mildly Annoyed - Noticeable load time"],[0,1499,"Delighted - Fast load time enhances experience"],[1500,1999,"Satisfied - Good load time meets expectations"]];static DOMAIN_REQUIREMENTS=[[["health","medical","care"],["Must comply with healthcare accessibility standards","Must protect patient data privacy"]],[["bank","finance","payment"],["Must maintain PCI DSS compliance for payment data","Must support secure authentication flows"]]];static VISIBLE_SCORE_ADJUSTMENTS=[[["Positive","Satisfied","Delighted"],20],[["Oriented"],10],[["Frustrated","Confused","Impatient"],-15],[["Disoriented"],-10]];analyze(e,t){let n=this.analyzeEndUserFlow(e),r=this.analyzeInternalFlow(e),i=this.analyzeUserFeelings(e),a=this.analyzePerformance(e),s=this.analyzeSecurity(e),c=this.analyzeImmutableRequirements(e,t),l=this.calculateVisibleScore(n,i),u=this.calculateInvisibleScore(a,s),d=Math.round((l+u)/2);return{visible:{guiFlow:{forEndUser:n,forInternalUser:r},userFeelings:i,score:l},invisible:{performance:a,security:s,score:u},immutableRequirements:c,overallImpactScore:d}}analyzeEndUserFlow(e){let t=[],n=e.domMetrics?.interactiveElements||0,r=e.domMetrics?.forms||0;return n>0&&t.push(`${n} interactive elements affect user journey`),r>0&&t.push(`${r} forms impact user input flows`),e.domMetrics?.semanticStructure?.hasNav&&t.push("Navigation structure enables exploration flow"),e.domMetrics?.semanticStructure?.hasMain&&t.push("Clear main content area guides user focus"),t}analyzeInternalFlow(e){let t=[];return(e.domMetrics?.forms||0)>0&&t.push("Form submissions create data processing workflows"),e.domMetrics?.semanticStructure?.hasAside&&t.push("Sidebar content may require separate management"),t}analyzeUserFeelings(e){let t=[],n=e.accessibility?.altTextsCoverage||0;n>80?t.push("Positive - Good accessibility creates inclusive experience"):n>=50?t.push("Neutral - Moderate accessibility; some users may struggle"):n<50&&t.push("Frustrated - Poor accessibility excludes some users");let r=e.performance?.loadTime||0;for(let[i,a,s]of o.LOAD_TIME_FEELINGS)if(r>=i&&r<=a){t.push(s);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,a]of o.DOMAIN_REQUIREMENTS)i.some(s=>r.includes(s))&&n.push(...a);return n}calculateVisibleScore(e,t){let n=50;e.length>0&&(n+=15);for(let[r,i]of o.VISIBLE_SCORE_ADJUSTMENTS)t.some(a=>r.some(s=>a.includes(s)))&&(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 ou={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"]},ht=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:ou,streaming:!0,timeout:18e4};async execute(e,t){let{target:n,context:r=this.createMinimalContext(n),mode:i="full",heuristics:a,minOracleSeverity:s="medium",includeCreativity:c=!0,includeDesign:l=!0}=e;try{this.emitStream(t,{status:"starting",message:`Starting QX analysis for: ${n}`,phase:"initialization"}),this.emitStream(t,{status:"analyzing",phase:"problem-analysis"});let u=this.analyzeProblem(r);if(this.isAborted(t))return{success:!1,error:"Operation aborted"};this.emitStream(t,{status:"analyzing",phase:"user-needs"});let d=this.analyzeUserNeeds(r,u);this.emitStream(t,{status:"analyzing",phase:"business-needs"});let m=this.analyzeBusinessNeeds(r,u);this.emitStream(t,{status:"analyzing",phase:"creativity"});let p=c?this.analyzeCreativity(r,u):this.createMinimalCreativityAnalysis();this.emitStream(t,{status:"analyzing",phase:"design"});let g=l?this.analyzeDesign(r):this.createMinimalDesignAnalysis();this.emitStream(t,{status:"analyzing",phase:"oracle-detection"});let y=new En(s).detect(r,d,m);this.emitStream(t,{status:"analyzing",phase:"impact-analysis"});let f=new wn().analyze(r,u);this.emitStream(t,{status:"analyzing",phase:"heuristics",count:23});let b=await new Sn({enabledHeuristics:a||Object.values(gt)}).applyAll(r,u,d,m);this.emitStream(t,{status:"analyzing",phase:"recommendations"});let E=this.generateRecommendations(u,d,m,y,f,b),w=this.calculateOverallScore(u,d,m,p,g,f,b),T=this.scoreToGrade(w),P={overallScore:w,grade:T,timestamp:new Date().toISOString(),target:n,problemAnalysis:u,userNeeds:d,businessNeeds:m,creativityAnalysis:p,designAnalysis:g,oracleProblems:y,impactAnalysis:f,heuristics:b,recommendations:E,context:r};return this.emitStream(t,{status:"complete",score:w,grade:T,heuristicsApplied:b.length,oracleProblemsFound:y.length}),{success:!0,data:P,metadata:this.createMetadata(t.startTime,t.requestId)}}catch(u){return{success:!1,error:`QX analysis failed: ${S(u)}`}}}analyzeProblem(e){let t=e.title||"Untitled page",n=e.metadata?.description||"",r=e.errorIndicators?.hasErrorMessages||!1,i=`Evaluate quality experience of "${t}"`;n&&(i+=` - ${n.substring(0,100)}`);let a=e.domMetrics?.totalElements||0,s=e.domMetrics?.interactiveElements||0,c=e.domMetrics?.forms||0,l;a>500||s>50||c>3?l="complex":a>200||s>20||c>1?l="moderate":l="simple";let u=[];e.domMetrics?.semanticStructure?.hasNav&&u.push("Navigation structure"),c>0&&u.push(`Form interactions (${c} forms)`),s>0&&u.push(`User interactions (${s} elements)`),e.accessibility&&u.push("Accessibility compliance"),e.performance&&u.push("Performance metrics");let d=[],m=t.toLowerCase();for((m.includes("health")||m.includes("care")||m.includes("nhs"))&&(d.push({description:"Healthcare information may not be accessible to users with visual impairments",severity:"high",likelihood:"likely"}),d.push({description:"Patient journey complexity may cause confusion during registration or booking",severity:"medium",likelihood:"possible"}),d.push({description:"Emergency contact information may not be prominently visible",severity:"high",likelihood:"possible"})),e.domMetrics?.semanticStructure?.hasMain||d.push({description:"Missing main content landmark - users may struggle to find primary content",severity:"medium",likelihood:"likely"}),e.accessibility&&(e.accessibility.altTextsCoverage||0)<80&&d.push({description:"Poor image alt text coverage - screen reader users affected",severity:"high",likelihood:"very-likely"}),r&&d.push({description:"Visible error messages detected - potential usability issues",severity:"medium",likelihood:"likely"}),e.performance&&(e.performance.loadTime||0)>3e3&&d.push({description:"Slow load time - user frustration and abandonment risk",severity:"high",likelihood:"very-likely"});d.length<3;)l==="complex"?d.push({description:"Complex interaction flows may confuse first-time users",severity:"medium",likelihood:"possible"}):l==="moderate"?d.push({description:"Multiple interactive elements increase cognitive load",severity:"low",likelihood:"possible"}):d.push({description:"Limited interactivity may not meet user expectations",severity:"low",likelihood:"possible"});let p=50;return t&&t!=="Untitled page"&&(p+=15),n&&(p+=15),u.length>=3&&(p+=10),e.domMetrics?.semanticStructure?.hasMain&&(p+=10),p=Math.min(100,p),{problemStatement:i,complexity:l,breakdown:u,potentialFailures:d.slice(0,5),clarityScore:p}}analyzeUserNeeds(e,t){let n=[],r=[],i=e.domMetrics?.semanticStructure,a=e.accessibility,s=e.domMetrics?.interactiveElements||0,c=e.domMetrics?.forms||0;i?.hasNav?n.push({description:"Clear navigation to find content",priority:"must-have",addressed:!0}):(r.push("Missing navigation structure - users cannot easily explore site"),n.push({description:"Clear navigation to find content",priority:"must-have",addressed:!1})),s>0&&n.push({description:"Interactive elements for engagement",priority:"must-have",addressed:!0}),a&&(a.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}),a&&(a.altTextsCoverage||0)>50?n.push({description:"Image descriptions for screen readers",priority:"should-have",addressed:!0}):a&&(a.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}),a&&(a.landmarkRoles||0)>3&&n.push({description:"Rich ARIA landmarks for navigation",priority:"nice-to-have",addressed:!0}),c>0&&n.push({description:"Form interactions for user input",priority:"nice-to-have",addressed:!0});let l=n.filter(m=>m.priority==="must-have"&&m.addressed).length,u;r.length===0&&l>=3?u="excellent":r.length<=1&&l>=2?u="good":r.length<=2&&l>=2?u="adequate":u="poor";let d=40;return d+=l*10,d+=n.filter(m=>m.priority==="should-have"&&m.addressed).length*5,d+=n.filter(m=>m.priority==="nice-to-have"&&m.addressed).length*2,d-=r.length*8,d=Math.max(0,Math.min(100,d)),{needs:n,suitability:u,challenges:r,alignmentScore:d}}analyzeBusinessNeeds(e,t){let n=e.domMetrics?.forms||0,r=e.domMetrics?.interactiveElements||0,i=e.performance,a=e.errorIndicators?.hasErrorMessages||!1,s,c=[];n>2?(s="business-ease",c=["Form completion rate","Lead generation","User sign-ups"]):r>30?(s="user-experience",c=["Time on site","Click-through rate","User engagement"]):(s="balanced",c=["Content consumption","Bounce rate","Page views"]);let l=(e.title||"").toLowerCase();(l.includes("health")||l.includes("care"))&&c.push("Patient satisfaction","Appointment completion rate","Information accessibility");let u=[];n>0&&(u.push({team:"Marketing",impactType:"positive",description:"Form conversion optimization needed"}),u.push({team:"Development",impactType:"neutral",description:"Form validation and submission handling"})),e.accessibility&&(e.accessibility.altTextsCoverage||0)<100&&u.push({team:"Content",impactType:"negative",description:"Image alt text creation required"}),i&&(i.loadTime||0)>2e3&&u.push({team:"Engineering",impactType:"negative",description:"Performance optimization needed"}),t.complexity==="complex"&&u.push({team:"QA",impactType:"neutral",description:"Comprehensive testing strategy required"});let d=!1;a&&(d=!0),e.accessibility&&(e.accessibility.altTextsCoverage||0)<50&&(d=!0),i&&(i.loadTime||0)>4e3&&(d=!0);let m=50;return c.length>0&&(m+=15),u.length>0&&(m+=10),d||(m+=20),m=Math.min(100,m),{primaryGoal:s,kpisAffected:c,crossTeamImpact:u,compromisesUX:d,impactsKPIs:c.length>0,alignmentScore:m}}analyzeCreativity(e,t){let n=[];(t.complexity==="complex"||t.complexity==="moderate")&&(n.push({description:"Question fundamental assumptions about user mental models and expected workflows",inspirationSource:"philosophy",applicability:"high",novelty:"moderately-novel"}),e.errorIndicators?.hasErrorMessages&&n.push({description:"Apply diagnostic testing - systematically isolate error sources through controlled scenarios",inspirationSource:"medicine",applicability:"high",novelty:"moderately-novel"})),e.domMetrics?.forms&&e.domMetrics.forms>0&&n.push({description:"Test checkout/form flows like fashion retail - focus on friction points, abandonment triggers",inspirationSource:"e-commerce",applicability:"high",novelty:"incremental"}),n.push({description:"Analyze through diverse demographic lenses (age, gender, culture, ability) for inclusive testing",inspirationSource:"social science",applicability:"high",novelty:"moderately-novel"}),e.domMetrics?.interactiveElements&&e.domMetrics.interactiveElements>20&&n.push({description:'Test for "game-breaking" exploits - unexpected interaction sequences, boundary conditions',inspirationSource:"gaming",applicability:"medium",novelty:"highly-novel"});let r=[...new Set(n.map(s=>s.inspirationSource))],i=["Unexperienced user perspective (fresh eyes)","Power user perspective (efficiency focus)","Accessibility perspective (assistive tech users)","International perspective (cultural differences)"],a=50;return a+=n.length*8,a+=r.length*5,a=Math.min(100,a),{innovativeApproaches:n,domainsExplored:r,perspectives:i,creativityScore:a,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 a=50+t.length*15-n.length*10;a=Math.max(0,Math.min(100,a));let s=a>=80?"excellent":a>=60?"good":a>=40?"adequate":"poor",c=[],l=[],u=!0;e.domMetrics?.semanticStructure?.hasNav&&c.push("Standard navigation placement"),e.domMetrics?.semanticStructure?.hasHeader&&c.push("Header follows common layout conventions"),!e.domMetrics?.semanticStructure?.hasNav&&i>10&&(u=!1,l.push("Non-standard navigation pattern may confuse users from different regions"));let d=50+c.length*15;u||(d-=20),d=Math.max(0,Math.min(100,d));let m=Math.round((a+d)/2);return{exactness:{clarity:s,clearElements:t,unclearElements:n,score:a},intuitive:{followsConventions:u,intuitivePatterns:c,culturalIssues:l,score:d},counterIntuitive:{deviations:[],innovativeJustification:!1,freshEyesPerspective:!0,issuesCount:0},overallDesignScore:m}}generateRecommendations(e,t,n,r,i,a){let s=[],c=1;for(let l of a){for(let u of l.issues)(u.severity==="critical"||u.severity==="high")&&s.push({principle:l.name,recommendation:u.description,severity:u.severity,impact:u.severity==="critical"?90:75,effort:"medium",priority:c++,category:"qx"});for(let u of l.recommendations)s.push({principle:l.name,recommendation:u,severity:"medium",impact:60,effort:"medium",priority:c++,category:"qx"})}for(let l of r)s.push({principle:`Oracle: ${l.type}`,recommendation:l.description,severity:l.severity,impact:l.severity==="critical"?95:l.severity==="high"?80:60,effort:"high",priority:c++,category:"process",evidence:l.resolutionApproach});for(let l of t.challenges)s.push({principle:"User Needs",recommendation:l,severity:"medium",impact:65,effort:"medium",priority:c++,category:"ux"});return s.sort((l,u)=>{let d={critical:0,high:1,medium:2,low:3},m=d[l.severity]-d[u.severity];return m!==0?m:u.impact-l.impact}).slice(0,15)}calculateOverallScore(e,t,n,r,i,a,s){let c=s.reduce((u,d)=>u+d.score,0)/s.length||0,l=e.clarityScore*.1+t.alignmentScore*.2+n.alignmentScore*.15+r.creativityScore*.1+i.overallDesignScore*.15+(100-a.overallImpactScore)*.1+c*.2;return Math.round(Math.max(0,Math.min(100,l)))}scoreToGrade(e){return e>=90?"A":e>=80?"B":e>=70?"C":e>=60?"D":"F"}createMinimalContext(e){return{url:e,title:e}}createMinimalCreativityAnalysis(){return{innovativeApproaches:[],domainsExplored:[],perspectives:[],creativityScore:50,notes:["Creativity analysis skipped"]}}createMinimalDesignAnalysis(){return{exactness:{clarity:"adequate",clearElements:[],unclearElements:[],score:50},intuitive:{followsConventions:!0,intuitivePatterns:[],culturalIssues:[],score:50},counterIntuitive:{deviations:[],innovativeJustification:!1,freshEyesPerspective:!1,issuesCount:0},overallDesignScore:50}}emitStream(e,t){e.streaming&&e.onStream&&e.onStream(t)}isAborted(e){return e.abortSignal?.aborted||!1}createMetadata(e,t){return{executionTime:Date.now()-e,timestamp:new Date().toISOString(),requestId:t}}},AR=new ht;var tP={TEST_GENERATE:"qe/tests/generate",TEST_EXECUTE:"qe/tests/execute",COVERAGE_ANALYZE:"qe/coverage/analyze",COVERAGE_GAPS:"qe/coverage/gaps",QUALITY_EVALUATE:"qe/quality/evaluate",QUALITY_GATE:"qe/quality/gate",DEFECT_PREDICT:"qe/defects/predict",REQUIREMENTS_VALIDATE:"qe/requirements/validate",QUALITY_CRITERIA:"qe/requirements/quality-criteria",CODE_ANALYZE:"qe/code/analyze",CODE_C4:"qe/code/c4",SECURITY_SCAN:"qe/security/scan",CONTRACT_VALIDATE:"qe/contracts/validate",VISUAL_COMPARE:"qe/visual/compare",A11Y_AUDIT:"qe/a11y/audit",CHAOS_INJECT:"qe/chaos/inject",LEARNING_OPTIMIZE:"qe/learning/optimize",LEARNING_DREAM:"qe/learning/dream",TOKEN_USAGE:"qe/analysis/token_usage",GOAP_PLAN:"qe/planning/goap_plan",GOAP_EXECUTE:"qe/planning/goap_execute",GOAP_STATUS:"qe/planning/goap_status",...ct,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",...pa,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"},cu=[new Jt,new Zt,new tn,new nn,new rn,new sn,new on,new cn,new tt,new un,new dn,new mn,new pn,new gn,new hn,new fn,new nt,new rt,new yn,new st,new at,new ot,...da,new $e,new ze,new je,new Be,new Ue,...ma,new ht,new Ri,new Pi,new xi,new Ai];function ga(){for(let o of cu)o.resetInstanceCache()}k();var ha=xn.filter(o=>o!=="coordination"),R={fleetId:null,kernel:null,queen:null,router:null,workflowOrchestrator:null,initialized:!1,initTime:null,topology:"hierarchical",agentLevels:new Map};function Je(){return R}function Oe(){return R.initialized&&R.kernel!==null&&R.queen!==null}function fP(o){return Oe()||(R.fleetId=`fleet-${q().slice(0,8)}`,R.kernel=o.kernel,R.queen=o.queen,R.router=o.router??null,R.workflowOrchestrator=o.workflowOrchestrator??null,R.initialized=!0,R.initTime=new Date,R.topology=o.topology??"hierarchical",R.agentLevels.clear()),R.fleetId}function yP(){return R.topology}function vP(o,e){if(R.topology!=="hierarchical"){let i={agentId:o,domain:e,level:"worker",spawnedAt:new Date};return R.agentLevels.set(o,i),"worker"}let n=Array.from(R.agentLevels.values()).find(i=>i.domain===e&&i.level==="lead")?"worker":"lead",r={agentId:o,domain:e,level:n,spawnedAt:new Date};return R.agentLevels.set(o,r),n}function bP(o){return R.agentLevels.get(o)}function CP(){return R.agentLevels}async function TP(o){try{if(R.initialized&&R.kernel&&R.queen)return{success:!0,data:{fleetId:R.fleetId,topology:o.topology||"hierarchical",maxAgents:o.maxAgents||15,enabledDomains:o.enabledDomains||ha,status:"ready"}};R.fleetId=`fleet-${q().slice(0,8)}`;let e=o.enabledDomains||[...xn],t=e.filter(l=>l!=="coordination"),n=process.env.AQE_MEMORY_BACKEND==="memory"?"memory":o.memoryBackend||"hybrid";R.kernel=new Mi({maxConcurrentAgents:o.maxAgents||15,memoryBackend:n,hnswEnabled:!0,lazyLoading:o.lazyLoading!==!1,enabledDomains:e}),await R.kernel.initialize(),R.router=new Vr(R.kernel.eventBus),await R.router.initialize();let r=l=>R.kernel.getDomainAPI(l),i=new ki(R.kernel.eventBus,R.kernel.memory,r),a=R.kernel.plugins;await a.loadAll();let s=new Map;for(let l of a.getLoaded()){let u=a.getPlugin(l);u&&s.set(l,u)}try{let{getDaemon:l}=await import("./daemon-Z7VPGWHY.js"),u=l().getWorkerManager();u.setKernel(R.kernel),u.setMemory(R.kernel.memory)}catch(l){console.warn(`[fleet_init] Daemon worker manager wiring skipped: ${S(l)}`)}R.queen=Ur(R.kernel,R.router,i,void 0,s),await R.queen.initialize(),R.workflowOrchestrator=new Hr(R.kernel.eventBus,R.kernel.memory,R.kernel.coordinator),await R.workflowOrchestrator.initialize(),lu(R.kernel,R.workflowOrchestrator);let{subscribeTrajectoryEvents:c}=await import("./task-handlers-4X357AEW.js");return c(R.router),R.initialized=!0,R.initTime=new Date,R.topology=o.topology||"hierarchical",R.agentLevels.clear(),{success:!0,data:{fleetId:R.fleetId,topology:R.topology,maxAgents:o.maxAgents||15,enabledDomains:t,status:"initialized"}}}catch(e){return{success:!1,error:`Failed to initialize fleet: ${S(e)}`}}}async function SP(o){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(o.includeDomains){let i=[];for(let[a,s]of e.domainHealth)i.push({domain:a,status:s.status,agents:s.agents.total,load:R.queen.getDomainLoad(a)});n.domains=i}let r=R.queen.getDomainTeamManager?.();if(r){let i=r.listDomainTeams(),a=0,s=0;for(let c of i)a+=1+c.teammateIds.length,r.getTeamHealth(c.domain)?.healthy&&s++;n.teams={active:i.length,totalAgentsInTeams:a,healthyCount:s}}o.includeMetrics&&(n.metrics={tasksReceived:t.tasksReceived,tasksCompleted:t.tasksCompleted,tasksFailed:t.tasksFailed,agentUtilization:t.agentUtilization,averageTaskDuration:t.averageTaskDuration});try{let{getUnifiedMemory:i}=await import("./unified-memory-5KQMA7FV.js"),a=i();if(a.isInitialized()){let s=l=>{try{return a.queryCount(l)}catch{return 0}},c=await a.vectorCount();n.learning={totalPatterns:s("qe_patterns"),totalExperiences:s("captured_experiences"),totalTrajectories:s("qe_trajectories"),vectorCount:c,experienceApplications:s("experience_applications"),dreamCycles:s("dream_cycles"),embeddingDimension:384}}}catch{}return{success:!0,data:n}}catch(e){return{success:!1,error:`Failed to get fleet status: ${S(e)}`}}}async function EP(o){if(!Oe())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{if(o.domain){let n=R.queen.getDomainHealth(o.domain);return n?{success:!0,data:{domain:o.domain,status:n.status,agents:n.agents,errors:n.errors,lastActivity:n.lastActivity?.toISOString()}}:{success:!1,error:`Domain not found: ${o.domain}`}}let e=R.queen.getHealth(),t={status:e.status,totalAgents:e.totalAgents,activeAgents:e.activeAgents,pendingTasks:e.pendingTasks,runningTasks:e.runningTasks,workStealingActive:e.workStealingActive,lastHealthCheck:e.lastHealthCheck.toISOString()};if(o.detailed){let n={};for(let[r,i]of e.domainHealth)n[r]={status:i.status,agents:i.agents,errors:i.errors.length,lastActivity:i.lastActivity?.toISOString()};t.domains=n,t.issues=e.issues.map(r=>({severity:r.severity,message:r.message,domain:r.domain,timestamp:r.timestamp.toISOString()}))}try{let{StructuralHealthMonitor:n}=await import("./structural-health-LR6WI3AH.js"),r=new n,i=[];for(let[c]of e.domainHealth){let l=R.queen.getAgentsByDomain(c);for(let u of l)i.push({id:u.id,name:u.name,domain:u.domain})}let a=i.map(c=>({id:c.id,name:c.name,domain:c.domain,capabilities:[c.domain],dependsOn:[],weight:1})),s=r.computeFleetHealth(a);t.structuralHealth={lambda:s.lambda,healthy:s.healthy,normalizedLambda:s.normalizedLambda,riskScore:s.riskScore,status:s.status,weakPoints:s.weakPoints,suggestions:s.suggestions}}catch{}return{success:!0,data:t}}catch(e){return{success:!1,error:`Failed to get fleet health: ${S(e)}`}}}async function wP(){if(ps(),Bs(),ga(),R.workflowOrchestrator&&(await R.workflowOrchestrator.dispose(),R.workflowOrchestrator=null),R.queen&&(await R.queen.dispose(),R.queen=null),R.router){try{let{unsubscribeTrajectoryEvents:o}=await import("./task-handlers-4X357AEW.js");o(R.router)}catch{}await R.router.dispose(),R.router=null}R.kernel&&(await R.kernel.dispose(),R.kernel=null),R.initialized=!1,R.fleetId=null,R.initTime=null,R.topology="hierarchical",R.agentLevels.clear()}async function RP(){let o=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 u=R.kernel.memory;try{n.connected=!0;let d=await u.count("default"),m=await u.count("learning"),p=await u.count("patterns");n.totalEntries=d+m+p;let g=0;for(let h of["default","learning","patterns","mcp-tools","coordination"])await u.count(h)>0&&g++;n.namespaces=g}catch{}try{let d=process.env.AQE_V3_HNSW_ENABLED==="true";r.enabled=d;let m=u;d&&typeof m.vectorCount=="function"&&(r.vectorCount=await m.vectorCount())}catch{}try{i=(await u.search("pattern:*",1e3)).length}catch{}}let a=e&&R.kernel?(R.kernel.getLoadedDomains?.()??ha).length:0,s=null;try{let{getSharedRvfDualWriterSync:u}=await import("./shared-rvf-dual-writer-23X5PNY5.js"),d=u();if(d){let m=d.status(),p=d.getDivergenceReport();s={mode:m.mode,vectorCount:m.rvf?.totalVectors??0,divergences:p.divergences,promotionSafe:d.isPromotionSafe()}}}catch{}let c=null;try{let{SQLitePatternStore:u}=await import("./sqlite-persistence-L2KISU2H.js"),d=new u;await d.initialize(),c=d.getGhostPatternCount(),d.close()}catch{}return{success:!0,data:{status:e?"healthy":"unhealthy",version:"3.14.0",loadedDomains:a,memory:n,hnsw:r,rvf:s??void 0,ghostPatterns:c??void 0,loadedPatterns:i,uptimeMs:t,timestamp:new Date().toISOString()},metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:q(),toolName:"aqe_health"}}}catch(e){return{success:!1,error:S(e),metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:q(),toolName:"aqe_health"}}}}function lu(o,e){let t=o.getDomainAPI("requirements-validation");t?.registerWorkflowActions&&(t.registerWorkflowActions(e),console.log("[Fleet] Registered requirements-validation workflow actions (includes QCSD Ideation)"));let n=o.getDomainAPI("visual-accessibility");n?.registerWorkflowActions&&(n.registerWorkflowActions(e),console.log("[Fleet] Registered visual-accessibility workflow actions"))}export{Zu as a,Ut as b,Je as c,Oe as d,fP as e,yP as f,vP as g,bP as h,CP as i,TP as j,SP as k,EP as l,wP as m,RP as n};
714
+ `).run(t.status==="completed"?"completed":t.status==="cancelled"?"cancelled":"failed",new Date(Date.now()-t.totalDurationMs).toISOString(),new Date().toISOString(),t.planId)}catch(r){console.warn("[PlanExecutor] Failed to update goap_plans status (non-fatal):",r)}}async updateActionStats(e,t,n){try{"updateActionStats"in this.planner&&await this.planner.updateActionStats(e,t,n)}catch(r){console.warn("[PlanExecutor] Failed to update action stats:",r)}}meetsConditions(e,t){for(let[n,r]of Object.entries(t))if(!this.checkCondition(e,n,r))return!1;return!0}checkCondition(e,t,n){let r=this.getStateValue(e,t);return typeof n=="string"||typeof n=="number"||typeof n=="boolean"?r===n:!(typeof n=="object"&&n!==null&&("min"in n&&n.min!==void 0&&(typeof r!="number"||r<n.min)||"max"in n&&n.max!==void 0&&(typeof r!="number"||r>n.max)||"eq"in n&&n.eq!==void 0&&r!==n.eq))}applyEffects(e,t){let n=this.cloneState(e);for(let[r,i]of Object.entries(t))this.applyEffect(n,r,i);return n}applyEffect(e,t,n){if(typeof n=="string"||typeof n=="number"||typeof n=="boolean"){this.setStateValue(e,t,n);return}if(typeof n=="object"&&n!==null){let r=this.getStateValue(e,t);if("set"in n&&n.set!==void 0&&this.setStateValue(e,t,n.set),"delta"in n&&n.delta!==void 0&&typeof r=="number"){let i=Math.max(0,Math.min(100,r+n.delta));this.setStateValue(e,t,i)}}}getStateValue(e,t){let n=t.split("."),r=e;for(let i of n){if(r==null)return;r=r[i]}return r}setStateValue(e,t,n){let r=t.split("."),i=new Set(["__proto__","constructor","prototype"]);for(let c of r)if(i.has(c)){console.warn(`[PlanExecutor] Blocked prototype pollution attempt: ${t}`);return}let a=e;for(let c=0;c<r.length-1;c++){let l=r[c];Object.hasOwn(a,l)||Object.defineProperty(a,l,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0});let u=Object.getOwnPropertyDescriptor(a,l);if(!u)return;a=u.value}let s=r[r.length-1];Object.defineProperty(a,s,{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}},je=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=ne()<this.successRate,r=`mock-agent-${qr().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 Gr(o,e){let t=new je({successRate:e?.successRate??1});return new ze(o,t,e?.dbPath,e?.config)}var ct=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=Ce(),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 l=await n.getGoals(),u=l.find(d=>d.name===e.goal);if(!u){let d=l.map(m=>m.name).join(", ");return{success:!1,error:`Unknown goal: ${e.goal}. Available goals: ${d||"none (seed actions first)"}`}}r=u.conditions,i=u.name}else r=e.goal,i="custom";let a=e.currentState||await this.detectCurrentState(),s=e.constraints?{maxCost:e.constraints.maxCost,maxDurationMs:e.constraints.maxDurationMs,requiredAgentTypes:e.constraints.requiredAgentTypes,excludedActions:e.constraints.excludedActions}:void 0,c=await n.findPlan(a,r,s);return c?(this.markAsRealData(),{success:!0,data:{planId:c.id,goal:e.goal,actions:c.actions.map(l=>({name:l.name,agentType:l.agentType,cost:l.cost,category:l.category,description:l.description})),totalCost:c.totalCost,estimatedDurationMs:c.estimatedDurationMs,stepCount:c.actions.length,reusedFrom:c.reusedFrom,similarityScore:c.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:S(n)}}}async detectCurrentState(){return{...ot}}};k();var lt=class extends x{planner=null;executor=null;config={name:"qe/planning/goap_execute",description:"Execute a GOAP plan. Each action dispatches to a real domain API method when the action is marked implemented and a kernel is available (run fleet_init first); actions with no real implementation, or with no domain/kernel available, fail with a specific reason rather than reporting a fabricated success. Supports dry-run mode to preview the plan without executing anything.",domain:"coordination",schema:this.buildSchema(),timeout:3e5};buildSchema(){return{type:"object",properties:{planId:{type:"string",description:"ID of plan to execute (from goap_plan result)"},dryRun:{type:"boolean",description:"Simulate execution without spawning agents (default: false)",default:!1},stepByStep:{type:"boolean",description:"Execute one step at a time (default: false)",default:!1},maxRetries:{type:"number",description:"Max retries per failed step (default: 2)",default:2,minimum:0,maximum:5}},required:["planId"]}}async getPlanner(){return this.planner||(this.planner=Ce(),await this.planner.initialize()),this.planner}async getExecutor(e){if(!this.executor){let t=await this.getPlanner(),n=r=>e?.getDomainAPI(r);this.executor=new ze(t,new je,void 0,{maxRetries:2,stepTimeoutMs:6e4,replanOnFailure:!0,parallelExecution:!1,recordWorldState:!0},n),await this.executor.initialize()}return this.executor}resetInstanceCache(){this.planner=null,this.executor=null}async execute(e,t){try{let r=await(await this.getPlanner()).getPlan(e.planId);if(!r)return{success:!1,error:`Plan not found: ${e.planId}. Create a plan first using goap_plan.`};if(e.dryRun)return this.markAsRealData(),{success:!0,data:{planId:r.id,mode:"dry-run",status:"completed",stepsCompleted:r.actions.length,stepsFailed:0,totalDurationMs:r.estimatedDurationMs,steps:r.actions.map(c=>({action:c.name,status:"would-execute",retries:0,durationMs:c.estimatedDurationMs}))}};let i=await It(t),a=await this.getExecutor(i);if(a.isExecuting())return{success:!1,error:"Another plan is currently executing. Wait for completion or cancel it."};let s=await a.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(c=>({action:c.action.name,status:c.status,retries:c.retries,durationMs:c.durationMs,error:c.error})),error:s.error},error:s.status!=="completed"?s.error:void 0}}catch(n){return{success:!1,error:S(n)}}}};k();var ut=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=Ce(),await this.planner.initialize()),this.planner}async getExecutor(){if(!this.executor){let e=await this.getPlanner();this.executor=Gr(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:S(n)}}}async getWorldState(){let e={...ot};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=$e(),a=e?i.filter(c=>c.category===e):i;r=a.slice(0,t).map((c,l)=>({id:`action-${l}`,name:c.name,category:c.category,agentType:c.agentType,cost:c.cost,successRate:c.successRate}));let s={};for(let c of i)s[c.category]=(s[c.category]||0)+1;return this.markAsRealData(),{success:!0,data:{type:"actions",data:{actions:r,count:a.length,byCategory:s}}}}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();Xe();oe();k();k();Xe();var dt={HEALTH:"qe/mincut/health",ANALYZE:"qe/mincut/analyze",STRENGTHEN:"qe/mincut/strengthen"};function Br(){return _n()}function su(){return On()}var $r=class extends x{config={name:dt.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=Br(),r=su(),i=le();if(e.agents)for(let l of e.agents)n.hasVertex(l.id)||n.addVertex({id:l.id,type:"agent",domain:l.domain,weight:l.weight??1,createdAt:new Date});if(e.edges)for(let l of e.edges)n.hasVertex(l.source)&&n.hasVertex(l.target)&&(n.hasEdge(l.source,l.target)||n.addEdge({source:l.source,target:l.target,weight:l.weight??1,type:"coordination",bidirectional:!0}));let a=r.checkHealth(),s=e.includeWeakVertices!==!1?i.findWeakVertices(n):[],c={health:{status:a.status,minCutValue:a.minCutValue,healthyThreshold:a.healthyThreshold,warningThreshold:a.warningThreshold,weakVertexCount:a.weakVertexCount,trend:a.trend},topology:{vertexCount:n.vertexCount,edgeCount:n.edgeCount,isConnected:n.isConnected()}};return e.includeWeakVertices!==!1&&s.length>0&&(c.weakVertices=s.map(l=>({id:l.vertexId,domain:l.vertex?.domain,weightedDegree:l.weightedDegree,riskScore:l.riskScore,reason:l.reason}))),e.includeHistory&&(c.history=a.history.map(l=>({timestamp:l.timestamp,value:l.value}))),this.markAsRealData(),{success:!0,data:c,metadata:this.createMetadata(t.startTime,t.requestId)}}},zr=class extends x{config={name:dt.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=Br(),r=le(),i=r.getMinCutValue(n),a=r.getMinDegreeVertex(n),s=r.findWeakVertices(n,e.weaknessThreshold),c=r.suggestEdgeAdditions(n,2),l={minCutValue:i,minDegreeVertex:a,weakVertices:s.map(u=>({id:u.vertexId,weightedDegree:u.weightedDegree,riskScore:u.riskScore,reason:u.reason,suggestions:u.suggestions.map(d=>({type:d.type,priority:d.priority,estimatedImprovement:d.estimatedImprovement}))})),suggestedEdges:c.map(u=>({source:u.source,target:u.target,weight:u.weight}))};return e.includePartitioningPoints&&(l.partitioningPoints=r.findPartitioningPoints(n)),this.markAsRealData(),{success:!0,data:l,metadata:this.createMetadata(t.startTime,t.requestId)}}},jr=class extends x{config={name:dt.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=Br(),r=le(),i=r.getMinCutValue(n),a=e.targetImprovement??1,s=r.suggestEdgeAdditions(n,a),c=[];if(e.apply)for(let u of s)n.addEdge({source:u.source,target:u.target,weight:u.weight,type:"coordination",bidirectional:!0}),c.push({type:"add_edge",source:u.source,target:u.target,weight:u.weight});else for(let u of s)c.push({type:"add_edge",source:u.source,target:u.target,weight:u.weight});let l=r.getMinCutValue(n);return this.markAsRealData(),{success:!0,data:{beforeMinCut:i,afterMinCut:e.apply?l:i+a,improvement:e.apply?l-i:a,actionsApplied:c,applied:e.apply??!1},metadata:this.createMetadata(t.startTime,t.requestId)}}},Ta=[new $r,new zr,new jr];k();var Ur=null,En=null;async function mt(){return Ur||En||(En=(async()=>{let o=Gt({embedding:{model:"all-MiniLM-L6-v2",cacheSize:1e3,normalize:!0,hyperbolic:!1,curvature:-1},autoInitialize:!1});return await o.initialize(),Ur=o,console.error("[EmbeddingTool] ONNX adapter initialized"),o})(),En)}var Be=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 mt(),i=await r.generateEmbedding(e.text);e.hyperbolic&&(i=r.toHyperbolic(i));let a=performance.now()-n;return this.markAsRealData(),{success:!0,data:{embedding:Array.from(i.vector),dimension:i.dimensions,isHyperbolic:i.isHyperbolic,latencyMs:a,model:i.model}}}catch(r){return{success:!1,error:`Embedding generation failed: ${S(r)}`}}}},Ue=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 mt(),i=e.metric||"cosine",a=i==="cosine"?"cosine":i==="euclidean"?"euclidean":"poincare",s=await r.compareSimilarity(e.text1,e.text2,a),c=performance.now()-n;return this.markAsRealData(),{success:!0,data:{similarity:s,metric:i,isSimilar:s>.7,latencyMs:c}}}catch(r){return{success:!1,error:`Similarity comparison failed: ${S(r)}`}}}},He=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 mt()).searchByText(e.query,{metric:"cosine",topK:e.topK??10,threshold:e.threshold??.5,namespace:e.namespace}),a=performance.now()-n;return this.markAsRealData(),{success:!0,data:{results:i.map(s=>({text:s.text,score:s.score,metadata:s.metadata})),totalFound:i.length,latencyMs:a}}}catch(r){return{success:!1,error:`Search failed: ${S(r)}`}}}},Ve=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 mt(),i=e.namespace||"default",a=await r.generateAndStore(e.text,{id:e.id,namespace:i,customData:e.metadata}),s=performance.now()-n;return this.markAsRealData(),{success:!0,data:{id:a.id,namespace:a.namespace||i,latencyMs:s}}}catch(r){return{success:!1,error:`Store failed: ${S(r)}`}}}},Qe=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 mt(),r=n.getStats(),i=await n.getHealth(),a=r.cacheHits+r.cacheMisses,s=a>0?r.cacheHits/a:0;return this.markAsRealData(),{success:!0,data:{totalGenerated:r.totalGenerated,vectorsStored:r.vectorsStored,cache:{hits:r.cacheHits,misses:r.cacheMisses,hitRate:s},model:{name:r.currentModel,dimension:r.currentModel==="all-MiniLM-L6-v2"?384:768},healthy:i.available}}}catch(n){return{success:!1,error:`Stats failed: ${S(n)}`}}}},au=new Be,ou=new Ue,cu=new He,lu=new Ve,uu=new Qe;k();var du={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"]},pt=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:du,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await ue(de)),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 a of r)if(!a.embedding||!Array.isArray(a.embedding))return{success:!1,error:`Node ${a.id} has invalid embedding - must be an array of numbers`};try{let a=await this.getService(),s=r.map(m=>({id:m.id,embedding:m.embedding,weight:m.weight??1,metadata:m.metadata})),c=await a.checkCoherence(s),l=[...c.recommendations,...this.generateAdditionalRecommendations(c,i)],u=c.contradictions.map(m=>({nodeIds:m.nodeIds,severity:String(m.severity),description:m.description||`Contradiction between nodes ${m.nodeIds[0]} and ${m.nodeIds[1]}`})),d=Date.now()-n;return this.markAsRealData(),{success:!0,data:{isCoherent:c.isCoherent,energy:c.energy,lane:c.lane,contradictions:u,recommendations:l,nodeCount:r.length,executionTimeMs:d,usedFallback:c.usedFallback}}}catch(a){return a instanceof Error&&a.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:S(a)}}}generateAdditionalRecommendations(e,t){let n=[];switch(e.energy>t&&n.push(`High coherence energy (${e.energy.toFixed(3)}) detected - review contradicting beliefs`),e.lane){case"reflex":n.push("Low energy - safe for immediate execution");break;case"retrieval":n.push("Moderate energy - consider fetching additional context");break;case"heavy":n.push("High energy - deep analysis recommended");break;case"human":n.push("Critical energy - escalate to Queen coordinator");break}return n}};var mu=["rename","framework-transfer","reordered-steps","distractor-terminology","cross-domain-transfer"],SS=[["async-race","observe completion before assertion","await the operation","increase the timeout","completion probe","unit","vitest"],["stale-cache","invalidate on every state mutation","invalidate the cache","retry the read","freshness assertion","integration","redis"],["transaction-leak","rollback isolates each test","rollback the transaction","truncate a shared table","row-count check","database","postgres"],["clock-skew","compare times in one clock domain","inject a monotonic clock","widen the time window","clock boundary check","unit","node"],["event-loss","subscribe before publishing","register the listener first","publish twice","delivery assertion","events","eventemitter"],["resource-leak","release resources on every exit","close in a finally block","raise the pool limit","handle-count check","integration","playwright"],["eventual-consistency","poll the observable state","poll with a bounded deadline","sleep for a fixed delay","state convergence","distributed","kubernetes"],["identity-confusion","compare canonical identities","normalize the identifier","use display names","identity equality","security","oauth"],["partial-write","publish only complete state","commit through an atomic swap","ignore missing fields","atomicity check","filesystem","node"],["order-dependence","tests start from isolated state","reset state in setup","force alphabetical order","shuffle repeat","unit","jest"],["schema-drift","validate at the boundary","reject the incompatible schema","cast the payload","schema validator","api","zod"],["backpressure-loss","producer respects consumer capacity","await the drain signal","increase buffer memory","loss counter","performance","streams"],["retry-duplication","retries preserve idempotency","attach an idempotency key","disable all retries","duplicate detector","api","fetch"],["permission-bypass","authorization precedes mutation","check permission before write","hide the user interface","denial assertion","security","express"],["encoding-mismatch","encode and decode with one charset","set UTF-8 explicitly","strip non-ASCII text","round-trip equality","api","json"],["pagination-gap","cursor advances from the last item","use the returned cursor","increase page size","set equality","api","graphql"],["cancellation-leak","cancellation propagates to children","forward the abort signal","wait for natural completion","abort observation","integration","abortcontroller"],["floating-point-boundary","compare numeric results by tolerance","use an error bound","round every input","relative-error check","unit","vitest"],["locale-dependence","format under an explicit locale","pass the locale explicitly","update the snapshot locally","multi-locale check","ui","intl"],["lock-starvation","lock acquisition remains fair","queue lock waiters","raise retry count","bounded-wait check","concurrency","mutex"]].map(([o,e,t,n,r,i,a])=>({mechanism:o,invariant:e,action:t,wrongAction:n,oracle:r,domain:i,framework:a}));var pu=Object.freeze([...mu]);Xr();k();var LS=Tt.create("qe-unified-memory");var hu={"test-suites":{dimensions:pe.DIMENSIONS,M:8,efConstruction:100,efSearch:50,metric:"cosine",namespace:"test-suites-hnsw",maxElements:1e5},coverage:{dimensions:pe.DIMENSIONS,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},defects:{dimensions:pe.DIMENSIONS,M:32,efConstruction:400,efSearch:200,metric:"cosine",namespace:"defects-hnsw",maxElements:1e5},quality:{dimensions:pe.DIMENSIONS,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"quality-hnsw",maxElements:1e5},learning:{dimensions:pe.DIMENSIONS,M:24,efConstruction:300,efSearch:150,metric:"cosine",namespace:"learning-hnsw",maxElements:1e5},coordination:{dimensions:pe.DIMENSIONS,M:8,efConstruction:100,efSearch:50,metric:"cosine",namespace:"coordination-hnsw",maxElements:5e4}},fu={enableHNSW:{"test-suites":!0,coverage:!0,defects:!0,quality:!0,learning:!0,coordination:!0},defaultNamespace:"qe-unified",enableCrossDomainSearch:!0,embeddingDimension:pe.DIMENSIONS};Xr();k();import{randomUUID as yu}from"crypto";var Hr=Tt.create("MemoryAuditor"),Vr={batchSize:50,energyThreshold:.4,hotspotThreshold:.6,maxRecommendations:10},wn=class{constructor(e,t,n=Vr){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,a=0;for(let[p,g]of Object.entries(n)){if(g.length<2)continue;let h=this.patternsToNodes(g),y=await this.coherenceService.checkCoherence(h);a+=y.energy,i+=y.contradictions.length,y.energy>this.config.hotspotThreshold&&r.push({domain:p,patternIds:g.map(v=>v.id),energy:y.energy,description:this.describeHotspot(y,p)})}let s=Object.keys(n).length,c=s>0?a/s:0,l=await this.identifyHotspots(e),u=await this.generateRecommendations(l,e),d=Date.now()-t,m={totalPatterns:e.length,scannedPatterns:e.length,contradictionCount:i,globalEnergy:c,hotspots:l,recommendations:u,duration:d,timestamp:new Date};return await this.emitEvent("memory:audit_completed",{result:m,timestamp:new Date}),m}catch(n){try{await this.emitEvent("memory:audit_failed",{error:S(n),timestamp:new Date})}catch(r){Hr.warn("Failed to emit audit_failed event",{error:S(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 a=this.patternsToNodes(i),s=await this.coherenceService.checkCoherence(a);s.energy>this.config.hotspotThreshold&&t.push({domain:r,patternIds:i.map(c=>c.id),energy:s.energy,description:this.describeHotspot(s,r)})}return t}async generateRecommendations(e,t){let n=[],r=new Map(t.map(i=>[i.id,i]));for(let i of e){let a=i.patternIds.map(u=>r.get(u)).filter(u=>u!==void 0),s=this.findDuplicates(a);s.length>0&&n.push({type:"merge",patternIds:s,reason:`Detected ${s.length} similar patterns in ${i.domain} domain`,priority:"high"});let c=this.findOutdated(a);c.length>0&&n.push({type:"remove",patternIds:c,reason:`Found ${c.length} outdated patterns with low usage/success`,priority:"medium"}),i.energy>.7&&n.push({type:"review",patternIds:i.patternIds,reason:`Critical coherence energy (${i.energy.toFixed(2)}) in ${i.domain}`,priority:"high"});let l=this.findBroadPatterns(a);l.length>0&&n.push({type:"split",patternIds:l,reason:`Found ${l.length} overly generic patterns that should be specialized`,priority:"low"})}return n.sort((i,a)=>this.priorityValue(a.priority)-this.priorityValue(i.priority)).slice(0,this.config.maxRecommendations)}async runBackgroundAudit(e){if(this.isAuditing){Hr.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:S(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()}-${yu().split("-")[0]}`,type:e,source:"learning-optimization",timestamp:new Date,payload:t})}catch(n){Hr.warn("Failed to emit event",{eventType:e,error:S(n)})}}};function Qr(o,e,t){return new wn(o,e,{...Vr,...t})}k();var vu={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:[]},gt=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:vu,streaming:!1,timeout:6e4};coherenceService=null;auditor=null;async getService(){return this.coherenceService||(this.coherenceService=await ue(de)),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 a=await this.getService();this.auditor||(this.auditor=Qr(a,void 0,{energyThreshold:i,hotspotThreshold:i+.2,maxRecommendations:10}));let s=await N(),c=Dn(s,{namespace:n,embeddingDimension:384});await c.initialize();let l=await c.search("",{limit:r,useVectorSearch:!1}),u=l.success?l.value.map(p=>p.pattern):[],d;u.length>0?d=await this.auditor.auditPatterns(u):d={totalPatterns:0,scannedPatterns:0,contradictionCount:0,globalEnergy:0,hotspots:[],recommendations:[],duration:0,timestamp:new Date};let m=this.calculateHealthScore(d);return this.markAsRealData(),{success:!0,data:{totalPatterns:d.totalPatterns,scannedPatterns:d.scannedPatterns,contradictionCount:d.contradictionCount,globalEnergy:d.globalEnergy,hotspots:d.hotspots.map(p=>({domain:p.domain,patternIds:p.patternIds,energy:p.energy,description:p.description})),recommendations:d.recommendations.map(p=>({type:p.type,patternIds:p.patternIds,reason:p.reason,priority:p.priority})),durationMs:d.duration,timestamp:d.timestamp.toISOString(),healthScore:m}}}catch(a){return a instanceof Error&&a.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:S(a)}}}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 bu={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"]},ht=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:bu,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await ue(de)),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 a=await this.getService(),s=r.map(m=>({agentId:m.agentId,agentType:m.agentType||"worker",verdict:m.verdict,confidence:m.confidence,reasoning:m.reasoning,timestamp:new Date})),c=await a.verifyConsensus(s),l=c.recommendation,u=r.reduce((m,p)=>m+p.confidence,0)/r.length;u<i&&(l=`Low average confidence (${(u*100).toFixed(1)}%) - consider gathering more evidence. `+l);let d=Date.now()-n;return this.markAsRealData(),{success:!0,data:{isValid:c.isValid,isFalseConsensus:c.isFalseConsensus,confidence:c.confidence,fiedlerValue:c.fiedlerValue,collapseRisk:c.collapseRisk,recommendation:l,usedFallback:c.usedFallback,executionTimeMs:d}}}catch(a){if(a instanceof Error&&a.message.includes("WASM")){let s=this.simpleMajorityAnalysis(r);return this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{...s,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:S(a)}}}simpleMajorityAnalysis(e){let t=new Map;for(let a of e){let s=String(a.verdict);t.set(s,(t.get(s)||0)+1)}let n=0;for(let a of t.values())a>n&&(n=a);let r=n/e.length,i=e.reduce((a,s)=>a+s.confidence,0)/e.length;return{isValid:r>=.5&&i>=.5,isFalseConsensus:!1,confidence:i,fiedlerValue:0,collapseRisk:1-r}}};k();var Cu={type:"object",properties:{swarmState:{type:"object",description:"Current state of the swarm including agents and task info"},riskThreshold:{type:"number",description:"Risk threshold for warning (0-1, default: 0.5)",default:.5,minimum:0,maximum:1}},required:["swarmState"]},ft=class extends 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:Cu,streaming:!1,timeout:3e4};coherenceService=null;async getService(){return this.coherenceService||(this.coherenceService=await ue(de)),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 a=await this.getService(),s={agents:r.agents.map(g=>({agentId:g.agentId,agentType:g.agentType||"worker",health:Number.isFinite(g.health)?g.health:1,beliefs:[],lastActivity:new Date,errorCount:g.errorCount??0,successRate:Number.isFinite(g.successRate)?g.successRate:1})),activeTasks:Number.isFinite(r.activeTasks)?r.activeTasks:0,pendingTasks:Number.isFinite(r.pendingTasks)?r.pendingTasks:0,errorRate:Number.isFinite(r.errorRate)?r.errorRate:0,utilization:Number.isFinite(r.utilization)?r.utilization:0,timestamp:new Date},c=await a.predictCollapse(s),l=Number.isFinite(c.risk)?c.risk:0,u=this.categorizeRisk(l),d=[...c.recommendations,...this.generateAdditionalRecommendations(c,r)],m=Date.now()-n;this.markAsRealData();let p=u==="high"||u==="critical"||u==="medium"&&l>=i;return{success:!0,data:{risk:l,isAtRisk:p,riskLevel:u,fiedlerValue:c.fiedlerValue,collapseImminent:c.collapseImminent,weakVertices:c.weakVertices,recommendations:d,executionTimeMs:m,usedFallback:c.usedFallback}}}catch(a){if(a instanceof Error&&a.message.includes("WASM")){let s=this.heuristicAnalysis(r,i);return this.markAsDemoData(t,"WASM module unavailable"),{success:!0,data:{...s,recommendations:["Running in fallback mode (heuristic analysis)","Install prime-radiant-advanced-wasm for spectral collapse prediction",...s.recommendations],usedFallback:!0,executionTimeMs:Date.now()-n}}}return{success:!1,error:S(a)}}}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=[],a=Number.isFinite(e.errorRate)?e.errorRate:0,s=Number.isFinite(e.utilization)?e.utilization:0,c=Number.isFinite(e.pendingTasks)?e.pendingTasks:0,l=Number.isFinite(e.activeTasks)?e.activeTasks:0,u=e.agents.map(h=>Number.isFinite(h.health)?h.health:1),d=u.length>0?u.reduce((h,y)=>h+y,0)/u.length:1;n+=(1-d)*.3,n+=Math.min(.25,a*2.5),s>.7&&(n+=(s-.7)*.5);let m=c/Math.max(1,l);m>1&&(n+=Math.min(.2,(m-1)*.1)),e.agents.forEach((h,y)=>{(u[y]<.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 Sa=[new pt,new gt,new ht,new ft],Ea={COHERENCE_CHECK:"qe/coherence/check",COHERENCE_AUDIT:"qe/coherence/audit",COHERENCE_CONSENSUS:"qe/coherence/consensus",COHERENCE_COLLAPSE:"qe/coherence/collapse"};var yt=(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))(yt||{});var Rn=class{enabledHeuristics;minConfidence;constructor(e={}){this.enabledHeuristics=e.enabledHeuristics||Object.values(yt),this.minConfidence=e.minConfidence||.7}async applyAll(e,t,n,r){let i=[];for(let a of this.enabledHeuristics){let s=await this.apply(a,e,t,n,r);i.push(s)}return i}async apply(e,t,n,r,i){let a=this.getHeuristicCategory(e),s=[],c=[],l=[],u=75;switch(e){case"H7.4-consistency-analysis":t.domMetrics?.semanticStructure?.hasHeader&&t.domMetrics?.semanticStructure?.hasFooter?(u=85,s.push("Consistent page structure with header and footer")):(u=60,l.push("Add consistent header/footer structure"));break;case"H7.2-intuitive-design":{let d=t.domMetrics?.semanticStructure?.hasNav,m=t.accessibility?.focusableElementsCount||0;d&&m>10?(u=82,s.push("Intuitive navigation and interaction design")):(u=55,c.push({description:"Navigation or interaction patterns unclear",severity:"medium"}));break}case"H7.1-exactness-and-clarity":{u=70;let d=t.domMetrics?.semanticStructure,m=[d?.hasHeader,d?.hasMain,d?.hasNav,d?.hasFooter].filter(Boolean).length;u=50+m*10,m>=3?s.push("Strong visual hierarchy with semantic HTML elements"):m>=2?(s.push("Moderate visual hierarchy - some semantic elements present"),l.push("Add more semantic HTML5 elements for clarity")):(c.push({description:"Weak visual hierarchy - missing semantic structure",severity:"high"}),l.push("Implement semantic HTML5: header, nav, main, footer")),t.metadata?.description&&t.metadata.description.length>20&&(u+=10,s.push("Page has descriptive metadata"));break}case"H7.3-counter-intuitive-design":{u=85;let d=!t.domMetrics?.semanticStructure?.hasNav&&(t.domMetrics?.interactiveElements||0)>10,m=!t.domMetrics?.semanticStructure?.hasHeader&&!t.domMetrics?.semanticStructure?.hasFooter;d&&(u=45,c.push({description:"Navigation structure may be counter-intuitive",severity:"high"}),l.push("Add semantic navigation elements")),m&&(u-=15,c.push({description:"Page structure lacks expected header/footer",severity:"medium"})),u>75&&s.push("No counter-intuitive design patterns detected");break}case"H5.2-user-feelings-impact":{let d=t.accessibility?.altTextsCoverage||0,m=t.performance?.loadTime||0,p=t.accessibility?.ariaLabelsCount||0,g=t.accessibility?.focusableElementsCount||0;u=60,d>=90?(u+=20,s.push("Excellent accessibility (90%+ alt coverage) creates inclusive, positive experience")):d>=70?(u+=12,s.push("Good accessibility creates generally positive user feelings")):d<50&&(u-=15,c.push({description:"Poor accessibility (<50% alt coverage) frustrates users with disabilities",severity:"high"}),l.push("Improve alt text coverage to at least 80% for better accessibility")),p>5&&(u+=8,s.push("Strong ARIA labeling enhances screen reader experience")),m<1500?(u+=15,s.push("Very fast load time (<1.5s) delights users")):m<2500?(u+=8,s.push("Fast load time enhances user satisfaction")):m>4e3?(u-=20,c.push({description:"Very slow load time (>4s) causes significant frustration",severity:"critical"}),l.push("Optimize page load time - target under 2.5 seconds")):m>3e3&&(u-=12,c.push({description:"Slow load time causes user frustration",severity:"high"})),t.errorIndicators?.hasErrorMessages&&(u-=12,c.push({description:"Visible errors reduce user confidence and satisfaction",severity:"high"}),l.push("Review and fix visible error messages")),g>20?(u+=5,s.push("Rich interactive elements provide user control and engagement")):g<5&&(u-=8,c.push({description:"Limited interactivity may feel restrictive",severity:"medium"})),u=Math.max(20,Math.min(100,u));break}case"H5.1-gui-flow-impact":{let d=t.domMetrics?.interactiveElements||0,m=t.domMetrics?.forms||0;d>20&&(u=75,s.push(`${d} interactive elements provide user control`)),m>0&&(s.push(`${m} forms impact user input flows`),u=Math.min(100,u+10)),d===0&&(u=30,c.push({description:"Limited user interaction capability",severity:"high"}));break}case"H5.3-cross-functional-impact":u=70,t.accessibility&&(t.accessibility.altTextsCoverage||0)<100&&s.push("Content team needed for alt text creation"),t.performance&&(t.performance.loadTime||0)>2e3&&s.push("Engineering team needed for performance optimization"),n.complexity==="complex"&&s.push("QA team needed for comprehensive testing"),u=70+s.length*5;break;case"H5.4-data-dependent-impact":t.domMetrics?.forms&&t.domMetrics.forms>0?(u=75,s.push(`${t.domMetrics.forms} forms depend on backend data processing`)):(u=50,s.push("Limited data-dependent features"));break;case"H1.1-problem-understanding":u=n.clarityScore,n.clarityScore>80?s.push("Problem is well-defined"):c.push({description:"Problem clarity needs improvement",severity:"medium"}),s.push(...n.breakdown);break;case"H1.2-rule-of-three":u=n.potentialFailures.length>=3?85:60,s.push(`${n.potentialFailures.length} potential failure modes identified`),n.potentialFailures.length<3&&l.push("Identify at least 3 potential failure modes (Rule of Three)");break;case"H1.3-problem-complexity":u=n.complexity==="simple"?90:n.complexity==="moderate"?75:60,s.push(`Problem complexity: ${n.complexity}`);break;case"H2.1-user-needs-identification":{u=r.alignmentScore,s.push(`${r.needs.length} user needs identified`);let d=r.needs.filter(m=>m.priority==="must-have").length;s.push(`${d} must-have features`),r.challenges.length>0&&c.push({description:`${r.challenges.length} user need challenges found`,severity:"medium"});break}case"H2.2-user-needs-suitability":u=r.suitability==="excellent"?95:r.suitability==="good"?80:r.suitability==="adequate"?65:45,s.push(`User needs suitability: ${r.suitability}`);break;case"H2.3-user-needs-validation":{let d=r.needs.filter(m=>m.addressed).length;u=r.needs.length>0?d/r.needs.length*100:50,s.push(`${d}/${r.needs.length} needs validated and addressed`);break}case"H3.1-business-needs-identification":u=i.alignmentScore,s.push(`Primary goal: ${i.primaryGoal}`),s.push(`${i.kpisAffected.length} KPIs affected`),s.push(`${i.crossTeamImpact.length} cross-team impacts`);break;case"H3.2-user-vs-business-balance":{let d=100-Math.abs(r.alignmentScore-i.alignmentScore);u=d,d>80?s.push("Good balance between user and business needs"):(c.push({description:"Imbalance between user and business priorities",severity:"medium"}),l.push("Align user and business objectives more closely"));break}case"H3.3-kpi-impact-analysis":u=i.impactsKPIs?85:50,s.push(`KPIs impacted: ${i.kpisAffected.join(", ")}`),i.compromisesUX&&(c.push({description:"Business ease compromises user experience",severity:"high"}),u-=20);break;case"H4.1-oracle-problem-detection":u=75,s.push("Oracle problem detection capability active");break;case"H4.2-what-must-not-change":u=80,t.domMetrics?.semanticStructure?.hasMain&&s.push("Main content structure is immutable"),t.accessibility&&(t.accessibility.focusableElementsCount||0)>0&&s.push("Keyboard navigation support must be maintained");break;case"H4.3-supporting-data-analysis":{u=75,(t.domMetrics?.forms||0)>0||(t.domMetrics?.interactiveElements||0)>20?(u=82,s.push("Sufficient data points for informed decision-making")):(u=60,c.push({description:"Limited data for comprehensive analysis",severity:"medium"}),l.push("Collect more user interaction data"));break}case"H6.1-competitive-analysis":u=70,s.push("Competitive analysis capability available"),t.domMetrics?.semanticStructure?.hasNav&&t.domMetrics?.interactiveElements&&t.domMetrics.interactiveElements>15?(u=78,s.push("Navigation and interaction patterns follow industry standards")):l.push("Compare interaction patterns with leading competitors");break;case"H6.2-domain-inspiration":{u=72,t.accessibility&&(t.accessibility.ariaLabelsCount||0)>0?(u=80,s.push("Modern accessibility patterns show domain inspiration")):l.push("Research domain-specific design patterns and best practices");break}case"H6.3-innovative-solutions":{u=65,(t.accessibility?.landmarkRoles||0)>3?(u=75,s.push("Advanced accessibility features show innovative thinking")):l.push("Explore innovative UX patterns to differentiate experience");break}default:a==="user-needs"?u=r.alignmentScore:a==="business-needs"?u=i.alignmentScore:a==="problem"&&(u=n.clarityScore);break}return{id:e,name:this.getHeuristicName(e),category:a,applied:!0,score:Math.min(100,Math.max(0,u)),findings:s,issues:c,recommendations:l}}getHeuristicCategory(e){return e.includes("problem")?"problem":e.includes("user-needs")||e.includes("user-vs")?"user-needs":e.includes("business")?"business-needs":e.includes("oracle")||e.includes("balance")||e.includes("what-must")||e.includes("supporting-data")?"balance":e.includes("impact")||e.includes("gui-flow")||e.includes("feelings")||e.includes("cross-functional")||e.includes("data-dependent")?"impact":e.includes("competitive")||e.includes("inspiration")||e.includes("innovative")?"creativity":"design"}getHeuristicName(e){return{"H1.1-problem-understanding":"Problem Understanding","H1.2-rule-of-three":"Rule of Three","H1.3-problem-complexity":"Problem Complexity","H2.1-user-needs-identification":"User Needs Identification","H2.2-user-needs-suitability":"User Needs Suitability","H2.3-user-needs-validation":"User Needs Validation","H3.1-business-needs-identification":"Business Needs Identification","H3.2-user-vs-business-balance":"User vs Business Balance","H3.3-kpi-impact-analysis":"KPI Impact Analysis","H4.1-oracle-problem-detection":"Oracle Problem Detection","H4.2-what-must-not-change":"What Must Not Change","H4.3-supporting-data-analysis":"Supporting Data Analysis","H5.1-gui-flow-impact":"GUI Flow Impact","H5.2-user-feelings-impact":"User Feelings Impact","H5.3-cross-functional-impact":"Cross-Functional Impact","H5.4-data-dependent-impact":"Data-Dependent Impact","H6.1-competitive-analysis":"Competitive Analysis","H6.2-domain-inspiration":"Domain Inspiration","H6.3-innovative-solutions":"Innovative Solutions","H7.1-exactness-and-clarity":"Exactness & Clarity","H7.2-intuitive-design":"Intuitive Design","H7.3-counter-intuitive-design":"Counter-Intuitive Design","H7.4-consistency-analysis":"Consistency Analysis"}[e]||e}};var Pn=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(),a=(e.metadata?.description||"").toLowerCase();return(i.includes("hotel")||i.includes("booking")||i.includes("travel")||i.includes("shop")||i.includes("store")||a.includes("book"))&&(n.kpisAffected.some(s=>s.toLowerCase().includes("conversion")||s.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(s=>this.meetsMinimumSeverity(s.severity))}meetsMinimumSeverity(e){let t=["low","medium","high","critical"],n=t.indexOf(this.minSeverity);return t.indexOf(e)>=n}};var xn=class o{static LOAD_TIME_FEELINGS=[[4001,1/0,"Impatient - Very slow load time causes significant frustration"],[3001,4e3,"Impatient - Slow load time causes frustration"],[2001,3e3,"Mildly Annoyed - Noticeable load time"],[0,1499,"Delighted - Fast load time enhances experience"],[1500,1999,"Satisfied - Good load time meets expectations"]];static DOMAIN_REQUIREMENTS=[[["health","medical","care"],["Must comply with healthcare accessibility standards","Must protect patient data privacy"]],[["bank","finance","payment"],["Must maintain PCI DSS compliance for payment data","Must support secure authentication flows"]]];static VISIBLE_SCORE_ADJUSTMENTS=[[["Positive","Satisfied","Delighted"],20],[["Oriented"],10],[["Frustrated","Confused","Impatient"],-15],[["Disoriented"],-10]];analyze(e,t){let n=this.analyzeEndUserFlow(e),r=this.analyzeInternalFlow(e),i=this.analyzeUserFeelings(e),a=this.analyzePerformance(e),s=this.analyzeSecurity(e),c=this.analyzeImmutableRequirements(e,t),l=this.calculateVisibleScore(n,i),u=this.calculateInvisibleScore(a,s),d=Math.round((l+u)/2);return{visible:{guiFlow:{forEndUser:n,forInternalUser:r},userFeelings:i,score:l},invisible:{performance:a,security:s,score:u},immutableRequirements:c,overallImpactScore:d}}analyzeEndUserFlow(e){let t=[],n=e.domMetrics?.interactiveElements||0,r=e.domMetrics?.forms||0;return n>0&&t.push(`${n} interactive elements affect user journey`),r>0&&t.push(`${r} forms impact user input flows`),e.domMetrics?.semanticStructure?.hasNav&&t.push("Navigation structure enables exploration flow"),e.domMetrics?.semanticStructure?.hasMain&&t.push("Clear main content area guides user focus"),t}analyzeInternalFlow(e){let t=[];return(e.domMetrics?.forms||0)>0&&t.push("Form submissions create data processing workflows"),e.domMetrics?.semanticStructure?.hasAside&&t.push("Sidebar content may require separate management"),t}analyzeUserFeelings(e){let t=[],n=e.accessibility?.altTextsCoverage||0;n>80?t.push("Positive - Good accessibility creates inclusive experience"):n>=50?t.push("Neutral - Moderate accessibility; some users may struggle"):n<50&&t.push("Frustrated - Poor accessibility excludes some users");let r=e.performance?.loadTime||0;for(let[i,a,s]of o.LOAD_TIME_FEELINGS)if(r>=i&&r<=a){t.push(s);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,a]of o.DOMAIN_REQUIREMENTS)i.some(s=>r.includes(s))&&n.push(...a);return n}calculateVisibleScore(e,t){let n=50;e.length>0&&(n+=15);for(let[r,i]of o.VISIBLE_SCORE_ADJUSTMENTS)t.some(a=>r.some(s=>a.includes(s)))&&(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 Tu={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"]},vt=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:Tu,streaming:!0,timeout:18e4};async execute(e,t){let{target:n,context:r=this.createMinimalContext(n),mode:i="full",heuristics:a,minOracleSeverity:s="medium",includeCreativity:c=!0,includeDesign:l=!0}=e;try{this.emitStream(t,{status:"starting",message:`Starting QX analysis for: ${n}`,phase:"initialization"}),this.emitStream(t,{status:"analyzing",phase:"problem-analysis"});let u=this.analyzeProblem(r);if(this.isAborted(t))return{success:!1,error:"Operation aborted"};this.emitStream(t,{status:"analyzing",phase:"user-needs"});let d=this.analyzeUserNeeds(r,u);this.emitStream(t,{status:"analyzing",phase:"business-needs"});let m=this.analyzeBusinessNeeds(r,u);this.emitStream(t,{status:"analyzing",phase:"creativity"});let p=c?this.analyzeCreativity(r,u):this.createMinimalCreativityAnalysis();this.emitStream(t,{status:"analyzing",phase:"design"});let g=l?this.analyzeDesign(r):this.createMinimalDesignAnalysis();this.emitStream(t,{status:"analyzing",phase:"oracle-detection"});let y=new Pn(s).detect(r,d,m);this.emitStream(t,{status:"analyzing",phase:"impact-analysis"});let f=new xn().analyze(r,u);this.emitStream(t,{status:"analyzing",phase:"heuristics",count:23});let b=await new Rn({enabledHeuristics:a||Object.values(yt)}).applyAll(r,u,d,m);this.emitStream(t,{status:"analyzing",phase:"recommendations"});let E=this.generateRecommendations(u,d,m,y,f,b),w=this.calculateOverallScore(u,d,m,p,g,f,b),T=this.scoreToGrade(w),P={overallScore:w,grade:T,timestamp:new Date().toISOString(),target:n,problemAnalysis:u,userNeeds:d,businessNeeds:m,creativityAnalysis:p,designAnalysis:g,oracleProblems:y,impactAnalysis:f,heuristics:b,recommendations:E,context:r};return this.emitStream(t,{status:"complete",score:w,grade:T,heuristicsApplied:b.length,oracleProblemsFound:y.length}),{success:!0,data:P,metadata:this.createMetadata(t.startTime,t.requestId)}}catch(u){return{success:!1,error:`QX analysis failed: ${S(u)}`}}}analyzeProblem(e){let t=e.title||"Untitled page",n=e.metadata?.description||"",r=e.errorIndicators?.hasErrorMessages||!1,i=`Evaluate quality experience of "${t}"`;n&&(i+=` - ${n.substring(0,100)}`);let a=e.domMetrics?.totalElements||0,s=e.domMetrics?.interactiveElements||0,c=e.domMetrics?.forms||0,l;a>500||s>50||c>3?l="complex":a>200||s>20||c>1?l="moderate":l="simple";let u=[];e.domMetrics?.semanticStructure?.hasNav&&u.push("Navigation structure"),c>0&&u.push(`Form interactions (${c} forms)`),s>0&&u.push(`User interactions (${s} elements)`),e.accessibility&&u.push("Accessibility compliance"),e.performance&&u.push("Performance metrics");let d=[],m=t.toLowerCase();for((m.includes("health")||m.includes("care")||m.includes("nhs"))&&(d.push({description:"Healthcare information may not be accessible to users with visual impairments",severity:"high",likelihood:"likely"}),d.push({description:"Patient journey complexity may cause confusion during registration or booking",severity:"medium",likelihood:"possible"}),d.push({description:"Emergency contact information may not be prominently visible",severity:"high",likelihood:"possible"})),e.domMetrics?.semanticStructure?.hasMain||d.push({description:"Missing main content landmark - users may struggle to find primary content",severity:"medium",likelihood:"likely"}),e.accessibility&&(e.accessibility.altTextsCoverage||0)<80&&d.push({description:"Poor image alt text coverage - screen reader users affected",severity:"high",likelihood:"very-likely"}),r&&d.push({description:"Visible error messages detected - potential usability issues",severity:"medium",likelihood:"likely"}),e.performance&&(e.performance.loadTime||0)>3e3&&d.push({description:"Slow load time - user frustration and abandonment risk",severity:"high",likelihood:"very-likely"});d.length<3;)l==="complex"?d.push({description:"Complex interaction flows may confuse first-time users",severity:"medium",likelihood:"possible"}):l==="moderate"?d.push({description:"Multiple interactive elements increase cognitive load",severity:"low",likelihood:"possible"}):d.push({description:"Limited interactivity may not meet user expectations",severity:"low",likelihood:"possible"});let p=50;return t&&t!=="Untitled page"&&(p+=15),n&&(p+=15),u.length>=3&&(p+=10),e.domMetrics?.semanticStructure?.hasMain&&(p+=10),p=Math.min(100,p),{problemStatement:i,complexity:l,breakdown:u,potentialFailures:d.slice(0,5),clarityScore:p}}analyzeUserNeeds(e,t){let n=[],r=[],i=e.domMetrics?.semanticStructure,a=e.accessibility,s=e.domMetrics?.interactiveElements||0,c=e.domMetrics?.forms||0;i?.hasNav?n.push({description:"Clear navigation to find content",priority:"must-have",addressed:!0}):(r.push("Missing navigation structure - users cannot easily explore site"),n.push({description:"Clear navigation to find content",priority:"must-have",addressed:!1})),s>0&&n.push({description:"Interactive elements for engagement",priority:"must-have",addressed:!0}),a&&(a.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}),a&&(a.altTextsCoverage||0)>50?n.push({description:"Image descriptions for screen readers",priority:"should-have",addressed:!0}):a&&(a.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}),a&&(a.landmarkRoles||0)>3&&n.push({description:"Rich ARIA landmarks for navigation",priority:"nice-to-have",addressed:!0}),c>0&&n.push({description:"Form interactions for user input",priority:"nice-to-have",addressed:!0});let l=n.filter(m=>m.priority==="must-have"&&m.addressed).length,u;r.length===0&&l>=3?u="excellent":r.length<=1&&l>=2?u="good":r.length<=2&&l>=2?u="adequate":u="poor";let d=40;return d+=l*10,d+=n.filter(m=>m.priority==="should-have"&&m.addressed).length*5,d+=n.filter(m=>m.priority==="nice-to-have"&&m.addressed).length*2,d-=r.length*8,d=Math.max(0,Math.min(100,d)),{needs:n,suitability:u,challenges:r,alignmentScore:d}}analyzeBusinessNeeds(e,t){let n=e.domMetrics?.forms||0,r=e.domMetrics?.interactiveElements||0,i=e.performance,a=e.errorIndicators?.hasErrorMessages||!1,s,c=[];n>2?(s="business-ease",c=["Form completion rate","Lead generation","User sign-ups"]):r>30?(s="user-experience",c=["Time on site","Click-through rate","User engagement"]):(s="balanced",c=["Content consumption","Bounce rate","Page views"]);let l=(e.title||"").toLowerCase();(l.includes("health")||l.includes("care"))&&c.push("Patient satisfaction","Appointment completion rate","Information accessibility");let u=[];n>0&&(u.push({team:"Marketing",impactType:"positive",description:"Form conversion optimization needed"}),u.push({team:"Development",impactType:"neutral",description:"Form validation and submission handling"})),e.accessibility&&(e.accessibility.altTextsCoverage||0)<100&&u.push({team:"Content",impactType:"negative",description:"Image alt text creation required"}),i&&(i.loadTime||0)>2e3&&u.push({team:"Engineering",impactType:"negative",description:"Performance optimization needed"}),t.complexity==="complex"&&u.push({team:"QA",impactType:"neutral",description:"Comprehensive testing strategy required"});let d=!1;a&&(d=!0),e.accessibility&&(e.accessibility.altTextsCoverage||0)<50&&(d=!0),i&&(i.loadTime||0)>4e3&&(d=!0);let m=50;return c.length>0&&(m+=15),u.length>0&&(m+=10),d||(m+=20),m=Math.min(100,m),{primaryGoal:s,kpisAffected:c,crossTeamImpact:u,compromisesUX:d,impactsKPIs:c.length>0,alignmentScore:m}}analyzeCreativity(e,t){let n=[];(t.complexity==="complex"||t.complexity==="moderate")&&(n.push({description:"Question fundamental assumptions about user mental models and expected workflows",inspirationSource:"philosophy",applicability:"high",novelty:"moderately-novel"}),e.errorIndicators?.hasErrorMessages&&n.push({description:"Apply diagnostic testing - systematically isolate error sources through controlled scenarios",inspirationSource:"medicine",applicability:"high",novelty:"moderately-novel"})),e.domMetrics?.forms&&e.domMetrics.forms>0&&n.push({description:"Test checkout/form flows like fashion retail - focus on friction points, abandonment triggers",inspirationSource:"e-commerce",applicability:"high",novelty:"incremental"}),n.push({description:"Analyze through diverse demographic lenses (age, gender, culture, ability) for inclusive testing",inspirationSource:"social science",applicability:"high",novelty:"moderately-novel"}),e.domMetrics?.interactiveElements&&e.domMetrics.interactiveElements>20&&n.push({description:'Test for "game-breaking" exploits - unexpected interaction sequences, boundary conditions',inspirationSource:"gaming",applicability:"medium",novelty:"highly-novel"});let r=[...new Set(n.map(s=>s.inspirationSource))],i=["Unexperienced user perspective (fresh eyes)","Power user perspective (efficiency focus)","Accessibility perspective (assistive tech users)","International perspective (cultural differences)"],a=50;return a+=n.length*8,a+=r.length*5,a=Math.min(100,a),{innovativeApproaches:n,domainsExplored:r,perspectives:i,creativityScore:a,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 a=50+t.length*15-n.length*10;a=Math.max(0,Math.min(100,a));let s=a>=80?"excellent":a>=60?"good":a>=40?"adequate":"poor",c=[],l=[],u=!0;e.domMetrics?.semanticStructure?.hasNav&&c.push("Standard navigation placement"),e.domMetrics?.semanticStructure?.hasHeader&&c.push("Header follows common layout conventions"),!e.domMetrics?.semanticStructure?.hasNav&&i>10&&(u=!1,l.push("Non-standard navigation pattern may confuse users from different regions"));let d=50+c.length*15;u||(d-=20),d=Math.max(0,Math.min(100,d));let m=Math.round((a+d)/2);return{exactness:{clarity:s,clearElements:t,unclearElements:n,score:a},intuitive:{followsConventions:u,intuitivePatterns:c,culturalIssues:l,score:d},counterIntuitive:{deviations:[],innovativeJustification:!1,freshEyesPerspective:!0,issuesCount:0},overallDesignScore:m}}generateRecommendations(e,t,n,r,i,a){let s=[],c=1;for(let l of a){for(let u of l.issues)(u.severity==="critical"||u.severity==="high")&&s.push({principle:l.name,recommendation:u.description,severity:u.severity,impact:u.severity==="critical"?90:75,effort:"medium",priority:c++,category:"qx"});for(let u of l.recommendations)s.push({principle:l.name,recommendation:u,severity:"medium",impact:60,effort:"medium",priority:c++,category:"qx"})}for(let l of r)s.push({principle:`Oracle: ${l.type}`,recommendation:l.description,severity:l.severity,impact:l.severity==="critical"?95:l.severity==="high"?80:60,effort:"high",priority:c++,category:"process",evidence:l.resolutionApproach});for(let l of t.challenges)s.push({principle:"User Needs",recommendation:l,severity:"medium",impact:65,effort:"medium",priority:c++,category:"ux"});return s.sort((l,u)=>{let d={critical:0,high:1,medium:2,low:3},m=d[l.severity]-d[u.severity];return m!==0?m:u.impact-l.impact}).slice(0,15)}calculateOverallScore(e,t,n,r,i,a,s){let c=s.reduce((u,d)=>u+d.score,0)/s.length||0,l=e.clarityScore*.1+t.alignmentScore*.2+n.alignmentScore*.15+r.creativityScore*.1+i.overallDesignScore*.15+(100-a.overallImpactScore)*.1+c*.2;return Math.round(Math.max(0,Math.min(100,l)))}scoreToGrade(e){return e>=90?"A":e>=80?"B":e>=70?"C":e>=60?"D":"F"}createMinimalContext(e){return{url:e,title:e}}createMinimalCreativityAnalysis(){return{innovativeApproaches:[],domainsExplored:[],perspectives:[],creativityScore:50,notes:["Creativity analysis skipped"]}}createMinimalDesignAnalysis(){return{exactness:{clarity:"adequate",clearElements:[],unclearElements:[],score:50},intuitive:{followsConventions:!0,intuitivePatterns:[],culturalIssues:[],score:50},counterIntuitive:{deviations:[],innovativeJustification:!1,freshEyesPerspective:!1,issuesCount:0},overallDesignScore:50}}emitStream(e,t){e.streaming&&e.onStream&&e.onStream(t)}isAborted(e){return e.abortSignal?.aborted||!1}createMetadata(e,t){return{executionTime:Date.now()-e,timestamp:new Date().toISOString(),requestId:t}}},hP=new vt;var jP={TEST_GENERATE:"qe/tests/generate",TEST_EXECUTE:"qe/tests/execute",COVERAGE_ANALYZE:"qe/coverage/analyze",COVERAGE_GAPS:"qe/coverage/gaps",QUALITY_EVALUATE:"qe/quality/evaluate",QUALITY_GATE:"qe/quality/gate",DEFECT_PREDICT:"qe/defects/predict",REQUIREMENTS_VALIDATE:"qe/requirements/validate",QUALITY_CRITERIA:"qe/requirements/quality-criteria",CODE_ANALYZE:"qe/code/analyze",CODE_C4:"qe/code/c4",SECURITY_SCAN:"qe/security/scan",CONTRACT_VALIDATE:"qe/contracts/validate",VISUAL_COMPARE:"qe/visual/compare",A11Y_AUDIT:"qe/a11y/audit",CHAOS_INJECT:"qe/chaos/inject",LEARNING_OPTIMIZE:"qe/learning/optimize",LEARNING_DREAM:"qe/learning/dream",TOKEN_USAGE:"qe/analysis/token_usage",GOAP_PLAN:"qe/planning/goap_plan",GOAP_EXECUTE:"qe/planning/goap_execute",GOAP_STATUS:"qe/planning/goap_status",...dt,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",...Ea,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"},Su=[new tn,new nn,new sn,new an,new on,new cn,new un,new dn,new it,new pn,new gn,new hn,new fn,new yn,new vn,new bn,new st,new at,new Cn,new ct,new lt,new ut,...Ta,new Be,new Ue,new He,new Ve,new Qe,...Sa,new vt,new Ni,new Fi,new Li,new qi];function wa(){for(let o of Su)o.resetInstanceCache()}k();var Ra=Mn.filter(o=>o!=="coordination"),R={fleetId:null,kernel:null,queen:null,router:null,workflowOrchestrator:null,initialized:!1,initTime:null,topology:"hierarchical",agentLevels:new Map};function tt(){return R}function Ne(){return R.initialized&&R.kernel!==null&&R.queen!==null}function rx(o){return Ne()||(R.fleetId=`fleet-${q().slice(0,8)}`,R.kernel=o.kernel,R.queen=o.queen,R.router=o.router??null,R.workflowOrchestrator=o.workflowOrchestrator??null,R.initialized=!0,R.initTime=new Date,R.topology=o.topology??"hierarchical",R.agentLevels.clear()),R.fleetId}function ix(){return R.topology}function sx(o,e){if(R.topology!=="hierarchical"){let i={agentId:o,domain:e,level:"worker",spawnedAt:new Date};return R.agentLevels.set(o,i),"worker"}let n=Array.from(R.agentLevels.values()).find(i=>i.domain===e&&i.level==="lead")?"worker":"lead",r={agentId:o,domain:e,level:n,spawnedAt:new Date};return R.agentLevels.set(o,r),n}function ax(o){return R.agentLevels.get(o)}function ox(){return R.agentLevels}async function cx(o){try{if(R.initialized&&R.kernel&&R.queen)return{success:!0,data:{fleetId:R.fleetId,topology:o.topology||"hierarchical",maxAgents:o.maxAgents||15,enabledDomains:o.enabledDomains||Ra,status:"ready"}};R.fleetId=`fleet-${q().slice(0,8)}`;let e=o.enabledDomains||[...Mn],t=e.filter(l=>l!=="coordination"),n=process.env.AQE_MEMORY_BACKEND==="memory"?"memory":o.memoryBackend||"hybrid";R.kernel=new $i({maxConcurrentAgents:o.maxAgents||15,memoryBackend:n,hnswEnabled:!0,lazyLoading:o.lazyLoading!==!1,enabledDomains:e}),await R.kernel.initialize(),R.router=new ni(R.kernel.eventBus),await R.router.initialize();let r=l=>R.kernel.getDomainAPI(l),i=new Gi(R.kernel.eventBus,R.kernel.memory,r),a=R.kernel.plugins;await a.loadAll();let s=new Map;for(let l of a.getLoaded()){let u=a.getPlugin(l);u&&s.set(l,u)}try{let{getDaemon:l}=await import("./daemon-XCULEHWY.js"),u=l().getWorkerManager();u.setKernel(R.kernel),u.setMemory(R.kernel.memory)}catch(l){console.warn(`[fleet_init] Daemon worker manager wiring skipped: ${S(l)}`)}R.queen=ei(R.kernel,R.router,i,void 0,s),await R.queen.initialize(),R.workflowOrchestrator=new ti(R.kernel.eventBus,R.kernel.memory,R.kernel.coordinator),await R.workflowOrchestrator.initialize(),Eu(R.kernel,R.workflowOrchestrator);let{subscribeTrajectoryEvents:c}=await import("./task-handlers-FYSDH55N.js");return c(R.router),R.initialized=!0,R.initTime=new Date,R.topology=o.topology||"hierarchical",R.agentLevels.clear(),{success:!0,data:{fleetId:R.fleetId,topology:R.topology,maxAgents:o.maxAgents||15,enabledDomains:t,status:"initialized"}}}catch(e){return{success:!1,error:`Failed to initialize fleet: ${S(e)}`}}}async function lx(o){if(!Ne())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{let e=R.queen.getHealth(),t=R.queen.getMetrics(),n={status:e.status,uptime:t.uptime,agents:{total:e.totalAgents,active:e.activeAgents,idle:e.totalAgents-e.activeAgents},tasks:{pending:e.pendingTasks,running:e.runningTasks,completed:t.tasksCompleted,failed:t.tasksFailed}};if(o.includeDomains){let i=[];for(let[a,s]of e.domainHealth)i.push({domain:a,status:s.status,agents:s.agents.total,load:R.queen.getDomainLoad(a)});n.domains=i}let r=R.queen.getDomainTeamManager?.();if(r){let i=r.listDomainTeams(),a=0,s=0;for(let c of i)a+=1+c.teammateIds.length,r.getTeamHealth(c.domain)?.healthy&&s++;n.teams={active:i.length,totalAgentsInTeams:a,healthyCount:s}}o.includeMetrics&&(n.metrics={tasksReceived:t.tasksReceived,tasksCompleted:t.tasksCompleted,tasksFailed:t.tasksFailed,agentUtilization:t.agentUtilization,averageTaskDuration:t.averageTaskDuration});try{let{getUnifiedMemory:i}=await import("./unified-memory-DSTIEDSH.js"),a=i();if(a.isInitialized()){let s=l=>{try{return a.queryCount(l)}catch{return 0}},c=await a.vectorCount();n.learning={totalPatterns:s("qe_patterns"),totalExperiences:s("captured_experiences"),totalTrajectories:s("qe_trajectories"),vectorCount:c,experienceApplications:s("experience_applications"),dreamCycles:s("dream_cycles"),embeddingDimension:384}}}catch{}return{success:!0,data:n}}catch(e){return{success:!1,error:`Failed to get fleet status: ${S(e)}`}}}async function ux(o){if(!Ne())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};try{if(o.domain){let n=R.queen.getDomainHealth(o.domain);return n?{success:!0,data:{domain:o.domain,status:n.status,agents:n.agents,errors:n.errors,lastActivity:n.lastActivity?.toISOString()}}:{success:!1,error:`Domain not found: ${o.domain}`}}let e=R.queen.getHealth(),t={status:e.status,totalAgents:e.totalAgents,activeAgents:e.activeAgents,pendingTasks:e.pendingTasks,runningTasks:e.runningTasks,workStealingActive:e.workStealingActive,lastHealthCheck:e.lastHealthCheck.toISOString()};if(o.detailed){let n={};for(let[r,i]of e.domainHealth)n[r]={status:i.status,agents:i.agents,errors:i.errors.length,lastActivity:i.lastActivity?.toISOString()};t.domains=n,t.issues=e.issues.map(r=>({severity:r.severity,message:r.message,domain:r.domain,timestamp:r.timestamp.toISOString()}))}try{let{StructuralHealthMonitor:n}=await import("./structural-health-YZXHVHM6.js"),r=new n,i=[];for(let[c]of e.domainHealth){let l=R.queen.getAgentsByDomain(c);for(let u of l)i.push({id:u.id,name:u.name,domain:u.domain})}let a=i.map(c=>({id:c.id,name:c.name,domain:c.domain,capabilities:[c.domain],dependsOn:[],weight:1})),s=r.computeFleetHealth(a);t.structuralHealth={lambda:s.lambda,healthy:s.healthy,normalizedLambda:s.normalizedLambda,riskScore:s.riskScore,status:s.status,weakPoints:s.weakPoints,suggestions:s.suggestions}}catch{}return{success:!0,data:t}}catch(e){return{success:!1,error:`Failed to get fleet health: ${S(e)}`}}}async function dx(){if(Ss(),Zs(),wa(),R.workflowOrchestrator&&(await R.workflowOrchestrator.dispose(),R.workflowOrchestrator=null),R.queen&&(await R.queen.dispose(),R.queen=null),R.router){try{let{unsubscribeTrajectoryEvents:o}=await import("./task-handlers-FYSDH55N.js");o(R.router)}catch{}await R.router.dispose(),R.router=null}R.kernel&&(await R.kernel.dispose(),R.kernel=null),R.initialized=!1,R.fleetId=null,R.initTime=null,R.topology="hierarchical",R.agentLevels.clear()}async function mx(){let o=performance.now();try{let e=Ne(),t=R.initTime?Date.now()-R.initTime.getTime():0,n={connected:!1,totalEntries:0,namespaces:0},r={enabled:!1,vectorCount:0},i=0;if(e&&R.kernel){let u=R.kernel.memory;try{n.connected=!0;let d=await u.count("default"),m=await u.count("learning"),p=await u.count("patterns");n.totalEntries=d+m+p;let g=0;for(let h of["default","learning","patterns","mcp-tools","coordination"])await u.count(h)>0&&g++;n.namespaces=g}catch{}try{let d=process.env.AQE_V3_HNSW_ENABLED==="true";r.enabled=d;let m=u;d&&typeof m.vectorCount=="function"&&(r.vectorCount=await m.vectorCount())}catch{}try{i=(await u.search("pattern:*",1e3)).length}catch{}}let a=e&&R.kernel?(R.kernel.getLoadedDomains?.()??Ra).length:0,s=null;try{let{getSharedRvfDualWriterSync:u}=await import("./shared-rvf-dual-writer-LHMFCYVE.js"),d=u();if(d){let m=d.status(),p=d.getDivergenceReport();s={mode:m.mode,vectorCount:m.rvf?.totalVectors??0,divergences:p.divergences,promotionSafe:d.isPromotionSafe()}}}catch{}let c=null;try{let{SQLitePatternStore:u}=await import("./sqlite-persistence-NVVAPZN3.js"),d=new u;await d.initialize(),c=d.getGhostPatternCount(),d.close()}catch{}return{success:!0,data:{status:e?"healthy":"unhealthy",version:"3.14.2",loadedDomains:a,memory:n,hnsw:r,rvf:s??void 0,ghostPatterns:c??void 0,loadedPatterns:i,uptimeMs:t,timestamp:new Date().toISOString()},metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:q(),toolName:"aqe_health"}}}catch(e){return{success:!1,error:S(e),metadata:{executionTime:performance.now()-o,timestamp:new Date().toISOString(),requestId:q(),toolName:"aqe_health"}}}}function Eu(o,e){let t=o.getDomainAPI("requirements-validation");t?.registerWorkflowActions&&(t.registerWorkflowActions(e),console.log("[Fleet] Registered requirements-validation workflow actions (includes QCSD Ideation)"));let n=o.getDomainAPI("visual-accessibility");n?.registerWorkflowActions&&(n.registerWorkflowActions(e),console.log("[Fleet] Registered visual-accessibility workflow actions"))}export{pd as a,Qt as b,tt as c,Ne as d,rx as e,ix as f,sx as g,ax as h,ox as i,cx as j,lx as k,ux as l,dx as m,mx as n};