agentic-qe 3.15.11 → 3.15.12

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 (431) hide show
  1. package/.claude/hooks/aqe-hook.cjs +38 -2
  2. package/.claude/skills/skills-manifest.json +1 -1
  3. package/CHANGELOG.md +149 -0
  4. package/assets/skills/skills-manifest.json +1 -1
  5. package/dist/cli/bundle.js +6 -6
  6. package/dist/cli/chunks/adapter-HL7MOCQN.js +2 -0
  7. package/dist/cli/chunks/{agent-booster-wasm-TIDSQ3ZK.js → agent-booster-wasm-5VZCKTIJ.js} +2 -2
  8. package/dist/cli/chunks/{agent-handler-G3EPBVA7.js → agent-handler-K3C6CQCD.js} +2 -2
  9. package/dist/cli/chunks/{agent-memory-branch-ARC5C7GW.js → agent-memory-branch-NVFQ25WS.js} +2 -2
  10. package/dist/cli/chunks/aqe-learning-engine-OZ2DXB4G.js +2 -0
  11. package/dist/cli/chunks/{arena-K4I4QDXB.js → arena-QGWIJADQ.js} +2 -2
  12. package/dist/cli/chunks/{arena-36DTATJV.js → arena-TSZVDSXS.js} +4 -4
  13. package/dist/cli/chunks/{audit-WQSJSJZF.js → audit-KIEE2SHJ.js} +3 -3
  14. package/dist/cli/chunks/base-WIM7G3HC.js +2 -0
  15. package/dist/cli/chunks/{better-sqlite3-BB4K67MT.js → better-sqlite3-BNB32NW3.js} +2 -2
  16. package/dist/cli/chunks/{brain-handler-CU3GOIU3.js → brain-handler-MPC5SPYI.js} +3 -3
  17. package/dist/cli/chunks/{branch-enumerator-NJQX7ZNB.js → branch-enumerator-LZ7UXKAY.js} +2 -2
  18. package/dist/cli/chunks/{browser-6YJF4FQW.js → browser-VDHAW4RK.js} +2 -2
  19. package/dist/cli/chunks/browser-workflow-QRKCFVR3.js +2 -0
  20. package/dist/cli/chunks/{chunk-V7DA4HAK.js → chunk-23PQF7NN.js} +1 -1
  21. package/dist/cli/chunks/{chunk-IENZSO3K.js → chunk-26672ISV.js} +2 -2
  22. package/dist/cli/chunks/{chunk-OURITHFV.js → chunk-2ASQRBK2.js} +2 -2
  23. package/dist/cli/chunks/{chunk-VBK2YAYY.js → chunk-2E2QO44T.js} +2 -2
  24. package/dist/cli/chunks/{chunk-NT7JRHMH.js → chunk-2IVE5AR3.js} +1 -1
  25. package/dist/cli/chunks/{chunk-672XOJDG.js → chunk-2JYUA27M.js} +1 -1
  26. package/dist/cli/chunks/{chunk-OHR7C777.js → chunk-2PPSS4JD.js} +2 -2
  27. package/dist/cli/chunks/{chunk-FUYOOKTH.js → chunk-32UTHIY5.js} +3 -3
  28. package/dist/cli/chunks/{chunk-UKKYMW3S.js → chunk-33I2ZP6E.js} +2 -2
  29. package/dist/cli/chunks/{chunk-76SNL7GU.js → chunk-35MIUSXQ.js} +2 -2
  30. package/dist/cli/chunks/{chunk-4X4MWMHB.js → chunk-35NW676P.js} +2 -2
  31. package/dist/cli/chunks/{chunk-BZPE3LDO.js → chunk-3EWQN37E.js} +2 -2
  32. package/dist/cli/chunks/{chunk-5N25I53C.js → chunk-3IU4LDZR.js} +2 -2
  33. package/dist/cli/chunks/{chunk-NKTWKYHB.js → chunk-47RMGDG4.js} +2 -2
  34. package/dist/cli/chunks/chunk-4A76VPU4.js +3 -0
  35. package/dist/cli/chunks/{chunk-4RH5I24Q.js → chunk-4CB3QPZM.js} +2 -2
  36. package/dist/cli/chunks/{chunk-U3LJNNVJ.js → chunk-4HWUECVD.js} +2 -2
  37. package/dist/cli/chunks/{chunk-T5KHJ3J7.js → chunk-4KUOYDY2.js} +2 -2
  38. package/dist/cli/chunks/{chunk-XNLIWQYE.js → chunk-4LWMAAWK.js} +2 -2
  39. package/dist/cli/chunks/{chunk-KKYO2NKV.js → chunk-4PU5GTZW.js} +2 -2
  40. package/dist/cli/chunks/{chunk-VWUZSNVC.js → chunk-4SA7M34P.js} +1 -1
  41. package/dist/cli/chunks/{chunk-5WYZHDIZ.js → chunk-4Y6OEBJZ.js} +1 -1
  42. package/dist/cli/chunks/{chunk-J4JMCZVA.js → chunk-5A66EGEW.js} +2 -2
  43. package/dist/cli/chunks/{chunk-HFFPYC4G.js → chunk-5ADXFUMO.js} +2 -2
  44. package/dist/cli/chunks/{chunk-KJCIMNHS.js → chunk-5S4UIDFK.js} +1 -1
  45. package/dist/cli/chunks/{chunk-YBBT3YYG.js → chunk-5TAEW5OV.js} +1 -1
  46. package/dist/cli/chunks/{chunk-FLU5FDSC.js → chunk-5Z23ZMXZ.js} +59 -59
  47. package/dist/cli/chunks/{chunk-YNOCQ2SL.js → chunk-65TH6RPD.js} +1 -1
  48. package/dist/cli/chunks/{chunk-XGPTZUKQ.js → chunk-66PXR3NI.js} +2 -2
  49. package/dist/cli/chunks/{chunk-ITPGWGQS.js → chunk-6E6HB4N4.js} +4 -4
  50. package/dist/cli/chunks/{chunk-EJPK7OTR.js → chunk-6QRI3JVE.js} +2 -2
  51. package/dist/cli/chunks/{chunk-ZP75ASUU.js → chunk-7DNR4KKR.js} +1 -1
  52. package/dist/cli/chunks/{chunk-V5AADCBC.js → chunk-7JFDLL2F.js} +1 -1
  53. package/dist/cli/chunks/chunk-7OEFBWAG.js +5 -0
  54. package/dist/cli/chunks/{chunk-EIDJNT5C.js → chunk-7QEUHNKO.js} +1 -1
  55. package/dist/cli/chunks/{chunk-7R5HC56U.js → chunk-7TA5MUPW.js} +1 -1
  56. package/dist/cli/chunks/{chunk-LCVEEII4.js → chunk-A2JCRXTK.js} +2 -2
  57. package/dist/cli/chunks/{chunk-JUMICXM6.js → chunk-A5Y7DAVQ.js} +2 -2
  58. package/dist/cli/chunks/{chunk-FZHSG75I.js → chunk-ADUAJIAU.js} +2 -2
  59. package/dist/cli/chunks/{chunk-TFW7CCKS.js → chunk-AJEXPFAB.js} +1 -1
  60. package/dist/cli/chunks/{chunk-JGJXXAS6.js → chunk-BC4T6SCV.js} +4 -4
  61. package/dist/cli/chunks/{chunk-4RAQ7PJA.js → chunk-BMG2JLSQ.js} +2 -2
  62. package/dist/cli/chunks/{chunk-Y7B5EUIJ.js → chunk-BOSMELJX.js} +2 -2
  63. package/dist/cli/chunks/{chunk-CIAL4YRY.js → chunk-BYRCB5JT.js} +2 -2
  64. package/dist/cli/chunks/{chunk-XS2XF3YG.js → chunk-C3YOVASQ.js} +1 -1
  65. package/dist/cli/chunks/{chunk-FL32MTKT.js → chunk-C74M4WUI.js} +2 -2
  66. package/dist/cli/chunks/{chunk-S6IYEBAI.js → chunk-CA5UNWQF.js} +2 -2
  67. package/dist/cli/chunks/{chunk-5MTWCCZJ.js → chunk-CDA5Z74H.js} +2 -2
  68. package/dist/cli/chunks/{chunk-DOFREOPQ.js → chunk-CPIBIR3X.js} +2 -2
  69. package/dist/cli/chunks/{chunk-UMVSWQNB.js → chunk-CU36D7TN.js} +2 -2
  70. package/dist/cli/chunks/{chunk-G4CKPWF6.js → chunk-DAUEK66C.js} +1 -1
  71. package/dist/cli/chunks/{chunk-2KFFEKSI.js → chunk-DRCBRUGN.js} +2 -2
  72. package/dist/cli/chunks/{chunk-EH2S6AOR.js → chunk-DZGPUGUG.js} +2 -2
  73. package/dist/cli/chunks/{chunk-HYXUN7BW.js → chunk-EF6OERRR.js} +1 -1
  74. package/dist/cli/chunks/{chunk-G77MLBDF.js → chunk-EN7GRVEQ.js} +2 -2
  75. package/dist/cli/chunks/{chunk-XDI5X3FR.js → chunk-ENGL7FIJ.js} +1 -1
  76. package/dist/cli/chunks/{chunk-HDNWSKHA.js → chunk-FAGKBOX2.js} +2 -2
  77. package/dist/cli/chunks/{chunk-FWSGPE3V.js → chunk-FNUFTWEO.js} +3 -3
  78. package/dist/cli/chunks/{chunk-AUUJBXWX.js → chunk-FZJCBSN4.js} +2 -2
  79. package/dist/cli/chunks/{chunk-ERN43HOX.js → chunk-G24SWTAX.js} +35 -35
  80. package/dist/cli/chunks/{chunk-VEEYL2CZ.js → chunk-G3AABG4Q.js} +2 -2
  81. package/dist/cli/chunks/{chunk-35M2X3C5.js → chunk-GJKZ7UQO.js} +2 -2
  82. package/dist/cli/chunks/{chunk-OV5RPLKV.js → chunk-GKFV6CUD.js} +2 -2
  83. package/dist/cli/chunks/{chunk-4HJKQIX5.js → chunk-HLGFHHWV.js} +2 -2
  84. package/dist/cli/chunks/{chunk-R5LGV6GZ.js → chunk-HM3LSFTY.js} +2 -2
  85. package/dist/cli/chunks/{chunk-M7XFBSIK.js → chunk-HSA5IGGW.js} +2 -2
  86. package/dist/cli/chunks/{chunk-GWJWSLDA.js → chunk-HZBXJFGN.js} +2 -2
  87. package/dist/cli/chunks/{chunk-4MUBW4RT.js → chunk-IA55PFLG.js} +2 -2
  88. package/dist/cli/chunks/{chunk-RBZCA7SD.js → chunk-ICKUINKD.js} +2 -2
  89. package/dist/cli/chunks/{chunk-KDI5JOYZ.js → chunk-IETBWYHW.js} +2 -2
  90. package/dist/cli/chunks/{chunk-325QCVDI.js → chunk-IL7GQNNE.js} +2 -2
  91. package/dist/cli/chunks/{chunk-BTVWA35P.js → chunk-INZARYUD.js} +2 -2
  92. package/dist/cli/chunks/{chunk-G2IJFNZS.js → chunk-IPA7K556.js} +2 -2
  93. package/dist/cli/chunks/{chunk-UTTSH4NH.js → chunk-IVTQF55W.js} +3 -3
  94. package/dist/cli/chunks/{chunk-2CW7VRPH.js → chunk-J7Y7ZBIT.js} +5 -5
  95. package/dist/cli/chunks/{chunk-M5RQ6U3G.js → chunk-JGIJPDGD.js} +2 -2
  96. package/dist/cli/chunks/{chunk-RQMCZQN2.js → chunk-JNXK47OL.js} +2 -2
  97. package/dist/cli/chunks/{chunk-X4J73KP3.js → chunk-JOWUS2X5.js} +1 -1
  98. package/dist/cli/chunks/{chunk-ZMC543GI.js → chunk-JR6CUKAI.js} +2 -2
  99. package/dist/cli/chunks/chunk-JRYWLOBD.js +21 -0
  100. package/dist/cli/chunks/{chunk-ETVAYGCB.js → chunk-JW5PDJ5O.js} +3 -3
  101. package/dist/cli/chunks/{chunk-OD5D4LSZ.js → chunk-K3A3NWT3.js} +2 -2
  102. package/dist/cli/chunks/{chunk-LPU6PAJE.js → chunk-KA5SHLMW.js} +2 -2
  103. package/dist/cli/chunks/{chunk-NPZOBSAN.js → chunk-KGA7VAI4.js} +2 -2
  104. package/dist/cli/chunks/{chunk-ZMHCMJ4J.js → chunk-KJDI5CHX.js} +2 -2
  105. package/dist/cli/chunks/{chunk-KSLLHFVY.js → chunk-L3PV7VXK.js} +1 -1
  106. package/dist/cli/chunks/{chunk-LD5CFK53.js → chunk-L7NGKANW.js} +2 -2
  107. package/dist/cli/chunks/{chunk-6NA3KZZT.js → chunk-LFBA735S.js} +7 -7
  108. package/dist/cli/chunks/{chunk-Z2EA7A4Z.js → chunk-MAJXZYGK.js} +1 -1
  109. package/dist/cli/chunks/{chunk-TCYSBC7Y.js → chunk-MCPEC6OO.js} +1 -1
  110. package/dist/cli/chunks/{chunk-LBX7M4LW.js → chunk-MCPXNUDK.js} +2 -2
  111. package/dist/cli/chunks/{chunk-5YLOLACR.js → chunk-MMEALJ4D.js} +2 -2
  112. package/dist/cli/chunks/{chunk-IOZRKXR5.js → chunk-MYF5CNGV.js} +2 -2
  113. package/dist/cli/chunks/{chunk-X3PZCXWG.js → chunk-MYUMJ2ZI.js} +1 -1
  114. package/dist/cli/chunks/{chunk-VYTILW4R.js → chunk-N7O3PF6Y.js} +2 -2
  115. package/dist/cli/chunks/{chunk-GVKVJJQX.js → chunk-NA3F6FEO.js} +2 -2
  116. package/dist/cli/chunks/{chunk-TL6OFMXF.js → chunk-NNBQZR73.js} +2 -2
  117. package/dist/cli/chunks/{chunk-KXS3Y2AX.js → chunk-NV74SICL.js} +2 -2
  118. package/dist/cli/chunks/chunk-NVRYELCY.js +13 -0
  119. package/dist/cli/chunks/{chunk-OH5V5EJW.js → chunk-NX4BCSOZ.js} +2 -2
  120. package/dist/cli/chunks/{chunk-XJKZ7FTR.js → chunk-O3IM4WRZ.js} +2 -2
  121. package/dist/cli/chunks/{chunk-3RHOPP7A.js → chunk-O4QJMANM.js} +1 -1
  122. package/dist/cli/chunks/{chunk-O4JAKWWM.js → chunk-OHVYINGM.js} +17 -17
  123. package/dist/cli/chunks/{chunk-APPZATXA.js → chunk-P5E26N2X.js} +2 -2
  124. package/dist/cli/chunks/{chunk-5ERFHEEE.js → chunk-P7UFJ6DO.js} +1 -1
  125. package/dist/cli/chunks/{chunk-5MNASJOH.js → chunk-PGSJBXTD.js} +2 -2
  126. package/dist/cli/chunks/{chunk-WCAVIJ64.js → chunk-PT2NXS43.js} +1 -1
  127. package/dist/cli/chunks/{chunk-EWPUQCN4.js → chunk-PTBOLBM4.js} +2 -2
  128. package/dist/cli/chunks/{chunk-EK5GMOSO.js → chunk-PX5OPXY6.js} +1 -1
  129. package/dist/cli/chunks/chunk-QCPVUNN3.js +2 -0
  130. package/dist/cli/chunks/{chunk-K2HBNYAZ.js → chunk-QSGEBCDB.js} +2 -2
  131. package/dist/cli/chunks/{chunk-G4FAPO57.js → chunk-QUJJYTJH.js} +2 -2
  132. package/dist/cli/chunks/{chunk-H7BLYMNU.js → chunk-QWG3SILX.js} +3 -3
  133. package/dist/cli/chunks/{chunk-LXQ3B4RY.js → chunk-RCOLPF3B.js} +2 -2
  134. package/dist/cli/chunks/{chunk-E44NNCEU.js → chunk-RYHG3I7J.js} +2 -2
  135. package/dist/cli/chunks/{chunk-RTFKTKSO.js → chunk-SBHM5X2S.js} +2 -2
  136. package/dist/cli/chunks/{chunk-DOBZPSKE.js → chunk-SDRJJUPO.js} +1 -1
  137. package/dist/cli/chunks/{chunk-RTY7VSZB.js → chunk-SG2TX72G.js} +2 -2
  138. package/dist/cli/chunks/{chunk-NTB342NJ.js → chunk-SITL5YZV.js} +4 -4
  139. package/dist/cli/chunks/{chunk-WM3SRRA6.js → chunk-SPC4RBLF.js} +2 -2
  140. package/dist/cli/chunks/{chunk-ITL3IN2E.js → chunk-SQVZ3TRU.js} +2 -2
  141. package/dist/cli/chunks/{chunk-CO3DX2AX.js → chunk-SUX5XB2Z.js} +2 -2
  142. package/dist/cli/chunks/{chunk-KSE5TDM5.js → chunk-T4EN5VVK.js} +2 -2
  143. package/dist/cli/chunks/{chunk-5HQP4SLM.js → chunk-TGMXUZZC.js} +2 -2
  144. package/dist/cli/chunks/{chunk-YOCULVHR.js → chunk-TLRHAMX5.js} +1 -1
  145. package/dist/cli/chunks/{chunk-GBFUANTC.js → chunk-TOWOJGEI.js} +1 -1
  146. package/dist/cli/chunks/{chunk-4UBVAJFO.js → chunk-TSOQ2QLT.js} +2 -2
  147. package/dist/cli/chunks/{chunk-SMVVAVN2.js → chunk-TVA5GRIU.js} +2 -2
  148. package/dist/cli/chunks/{chunk-K7V2WZNF.js → chunk-TXEUVUMO.js} +1 -1
  149. package/dist/cli/chunks/{chunk-LQ4NUC6Q.js → chunk-U6IXYQO4.js} +2 -2
  150. package/dist/cli/chunks/{chunk-HDJUYAZG.js → chunk-U7ZHDGXG.js} +1 -1
  151. package/dist/cli/chunks/{chunk-2VLYUF7U.js → chunk-UCSK2RMI.js} +2 -2
  152. package/dist/cli/chunks/{chunk-4UX35V7P.js → chunk-UIKQPO4Y.js} +2 -2
  153. package/dist/cli/chunks/chunk-UJNGGFGX.js +2 -0
  154. package/dist/cli/chunks/{chunk-AFFN6E6Q.js → chunk-ULCW6IVQ.js} +2 -2
  155. package/dist/cli/chunks/{chunk-WCVCOT4E.js → chunk-UREDS662.js} +2 -2
  156. package/dist/cli/chunks/{chunk-E6PF35JZ.js → chunk-URSTP3WI.js} +2 -2
  157. package/dist/cli/chunks/{chunk-I36CRDHF.js → chunk-UUZZXHUF.js} +2 -2
  158. package/dist/cli/chunks/{chunk-MIK4RBEH.js → chunk-UZED4YZ5.js} +1 -1
  159. package/dist/cli/chunks/{chunk-ZQHDA4O7.js → chunk-VF7FTD64.js} +1 -1
  160. package/dist/cli/chunks/{chunk-AMZKAJLJ.js → chunk-VUR5THML.js} +2 -2
  161. package/dist/cli/chunks/{chunk-H43AFUKL.js → chunk-VXVTFKRA.js} +2 -2
  162. package/dist/cli/chunks/chunk-VZBC6DP7.js +2 -0
  163. package/dist/cli/chunks/{chunk-DDEOZPWJ.js → chunk-W4II6SIH.js} +2 -2
  164. package/dist/cli/chunks/{chunk-55CH76ZO.js → chunk-W5HQIYQU.js} +3 -3
  165. package/dist/cli/chunks/{chunk-YPX2TV3M.js → chunk-W7H55PY4.js} +1 -1
  166. package/dist/cli/chunks/{chunk-CFWGGRE7.js → chunk-WDEXOLK2.js} +1 -1
  167. package/dist/cli/chunks/{chunk-XGBU3KEM.js → chunk-WGTEZT7G.js} +2 -2
  168. package/dist/cli/chunks/{chunk-NC6K7SCQ.js → chunk-WLRU6ESI.js} +2 -2
  169. package/dist/cli/chunks/{chunk-JFLU7L3W.js → chunk-WTAUF6O4.js} +2 -2
  170. package/dist/cli/chunks/chunk-XCNSGSKV.js +3 -0
  171. package/dist/cli/chunks/{chunk-57LNKSW7.js → chunk-XZOYKB22.js} +2 -2
  172. package/dist/cli/chunks/chunk-YIDAXOUX.js +8 -0
  173. package/dist/cli/chunks/{chunk-25P77WA5.js → chunk-YLKIXEPP.js} +1 -1
  174. package/dist/cli/chunks/{chunk-R5GRABPQ.js → chunk-YNVEDFPQ.js} +1 -1
  175. package/dist/cli/chunks/{chunk-NQZNMCZU.js → chunk-YUA6ZKKY.js} +2 -2
  176. package/dist/cli/chunks/{chunk-OYJC3YON.js → chunk-YVJEUX3I.js} +2 -2
  177. package/dist/cli/chunks/{chunk-QDESWOZP.js → chunk-YWWMNTBF.js} +2 -2
  178. package/dist/cli/chunks/{chunk-7HEMJHPP.js → chunk-ZGROHCOW.js} +1 -1
  179. package/dist/cli/chunks/{chunk-AP3ADWDK.js → chunk-ZPVGX4DI.js} +2 -2
  180. package/dist/cli/chunks/{chunk-M5XYIQYZ.js → chunk-ZROAMFX2.js} +2 -2
  181. package/dist/cli/chunks/{chunk-I4K2HTQU.js → chunk-ZYOYR3UR.js} +1 -1
  182. package/dist/cli/chunks/ci-BZNWW3I3.js +81 -0
  183. package/dist/cli/chunks/{ci-config-J665XNOX.js → ci-config-LOHNXOKV.js} +2 -2
  184. package/dist/cli/chunks/{ci-output-PEQQQWVD.js → ci-output-LCOQBSJL.js} +2 -2
  185. package/dist/cli/chunks/{circuit-breaker-HHB2JSKH.js → circuit-breaker-7LRXTLFE.js} +2 -2
  186. package/dist/cli/chunks/{claude-flow-setup-JKUJRWPN.js → claude-flow-setup-HBU4VWC3.js} +2 -2
  187. package/dist/cli/chunks/client-4PNYDFYS.js +2 -0
  188. package/dist/cli/chunks/{cline-installer-Y77BWTAN.js → cline-installer-CO6MLH6X.js} +2 -2
  189. package/dist/cli/chunks/{code-LV2HAGJY.js → code-SIXBS6JM.js} +3 -3
  190. package/dist/cli/chunks/{code-index-extractor-4GKKSETB.js → code-index-extractor-GWJKZ2IQ.js} +2 -2
  191. package/dist/cli/chunks/{codex-installer-WMKBYE5Y.js → codex-installer-6NINVWXJ.js} +2 -2
  192. package/dist/cli/chunks/{completions-SBGFAOIJ.js → completions-7VIX3GML.js} +2 -2
  193. package/dist/cli/chunks/{complexity-analyzer-AQHFIJXC.js → complexity-analyzer-FBQR6ZP2.js} +2 -2
  194. package/dist/cli/chunks/{continuedev-installer-26AYFS2E.js → continuedev-installer-VA7RIXW5.js} +2 -2
  195. package/dist/cli/chunks/{copilot-installer-4UD3DK55.js → copilot-installer-4QEBC4MU.js} +2 -2
  196. package/dist/cli/chunks/core-handlers-ODO6LUWQ.js +2 -0
  197. package/dist/cli/chunks/{cost-tracker-TP4NZCG4.js → cost-tracker-GRYKHPWL.js} +2 -2
  198. package/dist/cli/chunks/{coverage-B2KIXHAI.js → coverage-USPMNKOU.js} +11 -10
  199. package/dist/cli/chunks/cross-domain-router-DT4MHJKK.js +2 -0
  200. package/dist/cli/chunks/{cursor-installer-AVZEQZ4W.js → cursor-installer-ZXIPSZVH.js} +2 -2
  201. package/dist/cli/chunks/{daemon-XM2A7LQU.js → daemon-D7F3RGI5.js} +3 -3
  202. package/dist/cli/chunks/{daemon-P574WWBW.js → daemon-N2VRHPSJ.js} +4 -4
  203. package/dist/cli/chunks/{dag-attention-scheduler-MIWOZ6ET.js → dag-attention-scheduler-NL6BA7BY.js} +2 -2
  204. package/dist/cli/chunks/{detect-TYR7HT23.js → detect-XC2HCIIT.js} +2 -2
  205. package/dist/cli/chunks/{dist-node-2DGVQGLS.js → dist-node-A3Y26MEI.js} +2 -2
  206. package/dist/cli/chunks/{domain-handler-RRA4ZOMF.js → domain-handler-WV6SFXRB.js} +2 -2
  207. package/dist/cli/chunks/{domain-plugins-IVZEZ5RB.js → domain-plugins-KJIF6Z2B.js} +2 -2
  208. package/dist/cli/chunks/{domain-transfer-DOBI67K6.js → domain-transfer-L3F6AES2.js} +2 -2
  209. package/dist/cli/chunks/dream-QOB3JCOM.js +2 -0
  210. package/dist/cli/chunks/{embed-and-insert-pattern-VNIEOVPO.js → embed-and-insert-pattern-PA3Y4KGO.js} +2 -2
  211. package/dist/cli/chunks/{eval-QV4LVPUF.js → eval-YGEZNUVE.js} +2 -2
  212. package/dist/cli/chunks/{experience-capture-middleware-DAPKT763.js → experience-capture-middleware-D4T7NW6B.js} +3 -3
  213. package/dist/cli/chunks/{fast-paths-WVRFPHX7.js → fast-paths-6JYK7RYQ.js} +2 -2
  214. package/dist/cli/chunks/{feature-flags-O7ZXDDCD.js → feature-flags-DKXMDVPE.js} +2 -2
  215. package/dist/cli/chunks/{feature-flags-DEFTUIYT.js → feature-flags-RBH2GDSR.js} +2 -2
  216. package/dist/cli/chunks/file-discovery-BN76S2PR.js +2 -0
  217. package/dist/cli/chunks/fleet-43YMXACN.js +46 -0
  218. package/dist/cli/chunks/{gnn-wrapper-LS4LZJDR.js → gnn-wrapper-MV54UC4C.js} +2 -2
  219. package/dist/cli/chunks/{heartbeat-handler-RFTERD4K.js → heartbeat-handler-7DKMVQQH.js} +4 -4
  220. package/dist/cli/chunks/heartbeat-scheduler-3NNP4WCP.js +2 -0
  221. package/dist/cli/chunks/hnsw-adapter-MZR7Y4WF.js +2 -0
  222. package/dist/cli/chunks/hnsw-index-HE4AX22U.js +2 -0
  223. package/dist/cli/chunks/{hnsw-legacy-bridge-GPKGFFHY.js → hnsw-legacy-bridge-6IWREDQC.js} +2 -2
  224. package/dist/cli/chunks/{hnswlib-node-PHL3F2PR.js → hnswlib-node-5BIESSCK.js} +2 -2
  225. package/dist/cli/chunks/{hooks-GYJ6D4QM.js → hooks-3EETRM62.js} +28 -28
  226. package/dist/cli/chunks/hybrid-backend-IHUHB3Y2.js +2 -0
  227. package/dist/cli/chunks/{hypergraph-engine-YGEQPCKJ.js → hypergraph-engine-RSWCB2D3.js} +2 -2
  228. package/dist/cli/chunks/{hypergraph-handler-ZIMM647V.js → hypergraph-handler-552LXKL3.js} +3 -3
  229. package/dist/cli/chunks/impact-analyzer-FI6GI6PD.js +2 -0
  230. package/dist/cli/chunks/{init-guard-VOMBXJXG.js → init-guard-OTDBJ5HD.js} +2 -2
  231. package/dist/cli/chunks/{init-handler-PSMUBWK5.js → init-handler-3FK3TKEA.js} +6 -6
  232. package/dist/cli/chunks/init-wizard-WLQKH5Y5.js +2 -0
  233. package/dist/cli/chunks/kernel-2WZOQEZS.js +2 -0
  234. package/dist/cli/chunks/{kilocode-installer-2YNTFBWJ.js → kilocode-installer-KZ2O4LF3.js} +2 -2
  235. package/dist/cli/chunks/{kiro-installer-XHJDPVAZ.js → kiro-installer-MLCCXRF7.js} +2 -2
  236. package/dist/cli/chunks/knowledge-graph-G3LVKK6P.js +2 -0
  237. package/dist/cli/chunks/{learning-GNSIDRNG.js → learning-QUCMBD77.js} +3 -3
  238. package/dist/cli/chunks/{llm-router-LQDM7IU2.js → llm-router-PDEV3UP2.js} +4 -4
  239. package/dist/cli/chunks/llm-router-service-MM75HKWJ.js +2 -0
  240. package/dist/cli/chunks/{load-YATHI72E.js → load-XFVVLO7E.js} +2 -2
  241. package/dist/cli/chunks/load-test-BEWEE44J.js +2 -0
  242. package/dist/cli/chunks/{mcp-4Y6GDLYK.js → mcp-74G3CL2S.js} +2 -2
  243. package/dist/cli/chunks/{memory-OUW3L7H2.js → memory-XIFM6JNX.js} +5 -5
  244. package/dist/cli/chunks/memory-backend-NYKBBKZR.js +2 -0
  245. package/dist/cli/chunks/{memory-handlers-G3LFF53U.js → memory-handlers-ZCKURV6S.js} +2 -2
  246. package/dist/cli/chunks/{multi-model-executor-UBZJXAD2.js → multi-model-executor-7L4W3O2Q.js} +2 -2
  247. package/dist/cli/chunks/{opencode-installer-AMMNWVH5.js → opencode-installer-BPG422LF.js} +2 -2
  248. package/dist/cli/chunks/{orchestrator-Y44WDOER.js → orchestrator-OEAFLAEV.js} +58 -20
  249. package/dist/cli/chunks/pattern-null-store-QGPUIV6M.js +2 -0
  250. package/dist/cli/chunks/{pattern-usage-recorder-ESR42RME.js → pattern-usage-recorder-LOPNCULT.js} +2 -2
  251. package/dist/cli/chunks/{pipeline-EDTS6OSC.js → pipeline-VWTYUZB7.js} +2 -2
  252. package/dist/cli/chunks/{platform-5WONJSUX.js → platform-WFJJ3X2E.js} +2 -2
  253. package/dist/cli/chunks/{plugin-IJXPCLD4.js → plugin-744TPUSG.js} +2 -2
  254. package/dist/cli/chunks/{prime-radiant-advanced-wasm-5ECKGZK6.js → prime-radiant-advanced-wasm-BD5BLNDR.js} +2 -2
  255. package/dist/cli/chunks/project-root-C7ELXZRK.js +2 -0
  256. package/dist/cli/chunks/protocol-executor-SUVE33BM.js +2 -0
  257. package/dist/cli/chunks/{protocol-handler-DRD3GVNW.js → protocol-handler-JIBILI74.js} +2 -2
  258. package/dist/cli/chunks/{prove-KTGW2HMJ.js → prove-MNOL5FYW.js} +2 -2
  259. package/dist/cli/chunks/qe-reasoning-bank-YWZMMGJB.js +2 -0
  260. package/dist/cli/chunks/{quality-DV2WPRRS.js → quality-JEGBDGGX.js} +2 -2
  261. package/dist/cli/chunks/{quality-gate-HFUAFVZC.js → quality-gate-SYJ6ROMI.js} +3 -3
  262. package/dist/cli/chunks/queen-coordinator-ZFAKXRN7.js +2 -0
  263. package/dist/cli/chunks/real-embeddings-ZWXS5ZFV.js +2 -0
  264. package/dist/cli/chunks/{ref-validation-QWSKS5OY.js → ref-validation-RRHUFW2N.js} +2 -2
  265. package/dist/cli/chunks/{roocode-installer-RBAYRCHX.js → roocode-installer-XFO6JSVN.js} +2 -2
  266. package/dist/cli/chunks/router-4FTAVYLJ.js +2 -0
  267. package/dist/cli/chunks/routing-feedback-IO2KOWMJ.js +2 -0
  268. package/dist/cli/chunks/{routing-handler-FMPP3XKO.js → routing-handler-L2K3JASE.js} +2 -2
  269. package/dist/cli/chunks/{ruvector-commands-KZZT4HWF.js → ruvector-commands-A6CINHGM.js} +2 -2
  270. package/dist/cli/chunks/rvf-dual-writer-KCIRNE7C.js +2 -0
  271. package/dist/cli/chunks/rvf-migration-adapter-MFC5WTJU.js +2 -0
  272. package/dist/cli/chunks/{rvf-migration-coordinator-7CHEV35N.js → rvf-migration-coordinator-T4RY7L53.js} +2 -2
  273. package/dist/cli/chunks/rvf-native-adapter-I3KWHE7X.js +2 -0
  274. package/dist/cli/chunks/{rvf-store-integrity-Q2TH52SN.js → rvf-store-integrity-IR33TGQS.js} +2 -2
  275. package/dist/cli/chunks/safe-db-QXDZ6QY3.js +2 -0
  276. package/dist/cli/chunks/schedule-CZKD6RIY.js +2 -0
  277. package/dist/cli/chunks/scheduler-BLA3Q4CH.js +2 -0
  278. package/dist/cli/chunks/{security-CUEA3UIM.js → security-Z5GDE2IH.js} +3 -3
  279. package/dist/cli/chunks/{shared-rvf-adapter-DROMBRV2.js → shared-rvf-adapter-SIZMEHPM.js} +2 -2
  280. package/dist/cli/chunks/{shared-rvf-dual-writer-DBNABOP7.js → shared-rvf-dual-writer-HLM65RDS.js} +2 -2
  281. package/dist/cli/chunks/sqlite-persistence-XIUYDJC4.js +2 -0
  282. package/dist/cli/chunks/{standalone-memory-IAHA3M6B.js → standalone-memory-SKSZG7P5.js} +2 -2
  283. package/dist/cli/chunks/{status-handler-AFUCASTX.js → status-handler-766YOOMJ.js} +2 -2
  284. package/dist/cli/chunks/{structural-health-AQRV6JJ6.js → structural-health-M45FNOLT.js} +2 -2
  285. package/dist/cli/chunks/{sync-GX7FMJHL.js → sync-6CJ24B5T.js} +2 -2
  286. package/dist/cli/chunks/{sync-XW5TLZ7M.js → sync-B2U366I3.js} +2 -2
  287. package/dist/cli/chunks/{task-handler-TFKVUTNF.js → task-handler-P6IFLCKP.js} +17 -15
  288. package/dist/cli/chunks/task-handlers-DPWMUKFC.js +9 -0
  289. package/dist/cli/chunks/{test-D2XDJNDX.js → test-TODH7KRF.js} +4 -4
  290. package/dist/cli/chunks/test-runner-process-46IPK3GH.js +2 -0
  291. package/dist/cli/chunks/{test-scheduling-TS6I2PR7.js → test-scheduling-VMVMVRHT.js} +3 -3
  292. package/dist/cli/chunks/{token-bootstrap-HBBLPCZ3.js → token-bootstrap-XQW7BMCK.js} +2 -2
  293. package/dist/cli/chunks/{token-usage-3MBUX4PR.js → token-usage-JCZEIRKO.js} +2 -2
  294. package/dist/cli/chunks/{transformers-ZWMQO3L2.js → transformers-U2ML3OHE.js} +2 -2
  295. package/dist/cli/chunks/tree-sitter-wasm-parser-MOI2WWNJ.js +2 -0
  296. package/dist/cli/chunks/{types-5YEMGPSQ.js → types-GGEPCHP6.js} +2 -2
  297. package/dist/cli/chunks/unified-memory-FL26RTV3.js +2 -0
  298. package/dist/cli/chunks/unified-memory-hnsw-E2BPTH3U.js +2 -0
  299. package/dist/cli/chunks/unified-persistence-5ZOUPKHF.js +2 -0
  300. package/dist/cli/chunks/{upgrade-2TPBKIHI.js → upgrade-T5GRM7HS.js} +2 -2
  301. package/dist/cli/chunks/{validate-XRAXXFW6.js → validate-XMUJPLP3.js} +2 -2
  302. package/dist/cli/chunks/{validate-swarm-IYSCS3BZ.js → validate-swarm-KJLF7JEH.js} +2 -2
  303. package/dist/cli/chunks/visual-security-IJVPO5FA.js +2 -0
  304. package/dist/cli/chunks/{web-tree-sitter-PZQ3ZG2P.js → web-tree-sitter-LOHVZ7G5.js} +2 -2
  305. package/dist/cli/chunks/{windsurf-installer-U6XWFRVT.js → windsurf-installer-33FBTXJU.js} +2 -2
  306. package/dist/cli/chunks/witness-chain-5FAFCQKP.js +2 -0
  307. package/dist/cli/chunks/witness-chain-V2M32W5D.js +2 -0
  308. package/dist/cli/chunks/{witness-chain-repair-K7YX2AO6.js → witness-chain-repair-VWBO4NXE.js} +2 -2
  309. package/dist/cli/chunks/{witness-chain-verifier-GUTC3W7N.js → witness-chain-verifier-BHJ3ZAEK.js} +2 -2
  310. package/dist/cli/chunks/{witness-key-manager-YBNKMOP6.js → witness-key-manager-WNVPH2Z3.js} +2 -2
  311. package/dist/cli/chunks/{workflow-UAJUILFQ.js → workflow-6QR5MQTO.js} +4 -4
  312. package/dist/cli/chunks/workflow-orchestrator-3JLF3IX7.js +2 -0
  313. package/dist/cli/chunks/{wrappers-AVZ3GPAL.js → wrappers-EHOL62TS.js} +2 -2
  314. package/dist/cli/commands/ci.js +7 -0
  315. package/dist/cli/commands/coverage.js +7 -1
  316. package/dist/cli/commands/fleet.js +2 -2
  317. package/dist/cli/commands/hooks-handlers/stats-hooks.d.ts +4 -3
  318. package/dist/cli/commands/hooks-handlers/stats-hooks.js +22 -4
  319. package/dist/cli/handlers/task-handler.js +6 -0
  320. package/dist/cli/utils/coverage-verdict.d.ts +11 -2
  321. package/dist/cli/utils/coverage-verdict.js +26 -6
  322. package/dist/cli/utils/fleet-operation.d.ts +5 -0
  323. package/dist/cli/utils/fleet-operation.js +7 -1
  324. package/dist/cli/utils/fleet-result.d.ts +5 -3
  325. package/dist/cli/utils/fleet-result.js +9 -3
  326. package/dist/coordination/handlers/coverage-collection.d.ts +2 -0
  327. package/dist/coordination/handlers/coverage-collection.js +2 -1
  328. package/dist/coordination/handlers/coverage-evidence.d.ts +75 -0
  329. package/dist/coordination/handlers/coverage-evidence.js +159 -0
  330. package/dist/coordination/handlers/coverage-handlers.js +16 -3
  331. package/dist/coordination/handlers/coverage-scope.d.ts +40 -0
  332. package/dist/coordination/handlers/coverage-scope.js +321 -0
  333. package/dist/coordination/handlers/coverage-target.d.ts +9 -0
  334. package/dist/coordination/handlers/coverage-target.js +15 -5
  335. package/dist/coordination/handlers/handler-utils.d.ts +5 -0
  336. package/dist/coordination/handlers/handler-utils.js +8 -4
  337. package/dist/domains/code-intelligence/services/metric-collector/listing-process-owner.js +4 -1
  338. package/dist/domains/code-intelligence/services/semantic-analyzer.d.ts +8 -0
  339. package/dist/domains/code-intelligence/services/semantic-analyzer.js +10 -7
  340. package/dist/init/phases/10-workers.js +42 -4
  341. package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.d.ts +23 -1
  342. package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.js +50 -15
  343. package/dist/integrations/agentic-flow/reasoning-bank/index.d.ts +7 -2
  344. package/dist/integrations/agentic-flow/reasoning-bank/index.js +8 -0
  345. package/dist/learning/embedder-endpoint-client.d.ts +8 -0
  346. package/dist/learning/embedder-endpoint-client.js +20 -0
  347. package/dist/learning/embedder-recovery.d.ts +63 -0
  348. package/dist/learning/embedder-recovery.js +94 -0
  349. package/dist/learning/qe-reasoning-bank-types.d.ts +5 -0
  350. package/dist/learning/qe-reasoning-bank.d.ts +21 -0
  351. package/dist/learning/qe-reasoning-bank.js +54 -8
  352. package/dist/learning/real-embeddings.d.ts +23 -0
  353. package/dist/learning/real-embeddings.js +69 -2
  354. package/dist/learning/real-qe-reasoning-bank.d.ts +24 -4
  355. package/dist/learning/real-qe-reasoning-bank.js +58 -20
  356. package/dist/logging/redaction.js +142 -12
  357. package/dist/mcp/bundle.js +504 -492
  358. package/dist/mcp/daemon-mode.d.ts +126 -0
  359. package/dist/mcp/daemon-mode.js +257 -0
  360. package/dist/mcp/entry.d.ts +4 -0
  361. package/dist/mcp/entry.js +50 -2
  362. package/dist/mcp/handlers/domain-handler-configs.js +5 -0
  363. package/dist/mcp/handlers/orchestrate-routes.d.ts +6 -1
  364. package/dist/mcp/handlers/orchestrate-routes.js +53 -0
  365. package/dist/mcp/handlers/task-handlers.d.ts +11 -2
  366. package/dist/mcp/handlers/task-handlers.js +50 -5
  367. package/dist/mcp/protocol-server.js +3 -0
  368. package/dist/mcp/services/reasoning-bank-service.d.ts +6 -1
  369. package/dist/mcp/services/reasoning-bank-service.js +9 -0
  370. package/dist/mcp/types.d.ts +14 -0
  371. package/dist/routing/advisor/redaction.js +22 -2
  372. package/dist/shared/llm/providers/response-deadline.js +16 -2
  373. package/dist/shared/types/index.js +3 -1
  374. package/dist/strange-loop/infra-healing/infra-aware-agent-provider.js +8 -1
  375. package/package.json +3 -3
  376. package/dist/cli/chunks/adapter-V4GSGOOK.js +0 -2
  377. package/dist/cli/chunks/aqe-learning-engine-6WQTM5YR.js +0 -2
  378. package/dist/cli/chunks/base-AK7BXBX2.js +0 -2
  379. package/dist/cli/chunks/browser-workflow-VTDFBW7T.js +0 -2
  380. package/dist/cli/chunks/chunk-2DTX7YAZ.js +0 -6
  381. package/dist/cli/chunks/chunk-72ZBJD2E.js +0 -3
  382. package/dist/cli/chunks/chunk-EBPJY4DI.js +0 -3
  383. package/dist/cli/chunks/chunk-HJ3XNTTJ.js +0 -2
  384. package/dist/cli/chunks/chunk-IO5537OM.js +0 -2
  385. package/dist/cli/chunks/chunk-IW6WDGHM.js +0 -2
  386. package/dist/cli/chunks/chunk-LRL56ZYL.js +0 -21
  387. package/dist/cli/chunks/chunk-VLD7Z2ED.js +0 -13
  388. package/dist/cli/chunks/chunk-VO3DRK4P.js +0 -3
  389. package/dist/cli/chunks/ci-6GUFAZMJ.js +0 -81
  390. package/dist/cli/chunks/client-HL2COSFM.js +0 -2
  391. package/dist/cli/chunks/core-handlers-IX7ATLM6.js +0 -2
  392. package/dist/cli/chunks/cross-domain-router-YYKLAPJO.js +0 -2
  393. package/dist/cli/chunks/dream-T6EP7B3F.js +0 -2
  394. package/dist/cli/chunks/file-discovery-JYMVTDMU.js +0 -2
  395. package/dist/cli/chunks/fleet-FVAUMKUT.js +0 -46
  396. package/dist/cli/chunks/heartbeat-scheduler-4N5MUJ7S.js +0 -2
  397. package/dist/cli/chunks/hnsw-adapter-ZPAJDSLR.js +0 -2
  398. package/dist/cli/chunks/hnsw-index-4CTH6RHB.js +0 -2
  399. package/dist/cli/chunks/hybrid-backend-AW6UTXQS.js +0 -2
  400. package/dist/cli/chunks/impact-analyzer-MZK3JMSV.js +0 -2
  401. package/dist/cli/chunks/init-wizard-FUC7KDVX.js +0 -2
  402. package/dist/cli/chunks/kernel-ZCPMCVMW.js +0 -2
  403. package/dist/cli/chunks/knowledge-graph-NUJKEDNF.js +0 -2
  404. package/dist/cli/chunks/llm-router-service-B2BFBQ76.js +0 -2
  405. package/dist/cli/chunks/load-test-ZHQ2MUGO.js +0 -2
  406. package/dist/cli/chunks/memory-backend-AAMQG6WH.js +0 -2
  407. package/dist/cli/chunks/pattern-null-store-RFNVA46O.js +0 -2
  408. package/dist/cli/chunks/project-root-7QL4KP5C.js +0 -2
  409. package/dist/cli/chunks/protocol-executor-2NW5BD4R.js +0 -2
  410. package/dist/cli/chunks/qe-reasoning-bank-G2JZOGKD.js +0 -2
  411. package/dist/cli/chunks/queen-coordinator-GRG5FT2A.js +0 -2
  412. package/dist/cli/chunks/real-embeddings-RQRVOKVM.js +0 -2
  413. package/dist/cli/chunks/router-LQB5SWAF.js +0 -2
  414. package/dist/cli/chunks/routing-feedback-OEEXA55N.js +0 -2
  415. package/dist/cli/chunks/rvf-dual-writer-BZK4M7BO.js +0 -2
  416. package/dist/cli/chunks/rvf-migration-adapter-EZZUJL2E.js +0 -2
  417. package/dist/cli/chunks/rvf-native-adapter-6COXTQZ3.js +0 -2
  418. package/dist/cli/chunks/safe-db-PE6G3L55.js +0 -2
  419. package/dist/cli/chunks/schedule-OLKQ6QYW.js +0 -2
  420. package/dist/cli/chunks/scheduler-LSGBDFAT.js +0 -2
  421. package/dist/cli/chunks/sqlite-persistence-HH4DNTYH.js +0 -2
  422. package/dist/cli/chunks/task-handlers-SS4ZDXNF.js +0 -9
  423. package/dist/cli/chunks/test-runner-process-PSSBNNGR.js +0 -2
  424. package/dist/cli/chunks/tree-sitter-wasm-parser-TYRQRJ2W.js +0 -2
  425. package/dist/cli/chunks/unified-memory-AGDZQ5XD.js +0 -2
  426. package/dist/cli/chunks/unified-memory-hnsw-X5TJ3JDE.js +0 -2
  427. package/dist/cli/chunks/unified-persistence-UCV7YETW.js +0 -2
  428. package/dist/cli/chunks/visual-security-ZLXRIQZV.js +0 -2
  429. package/dist/cli/chunks/witness-chain-CVIWYTD2.js +0 -2
  430. package/dist/cli/chunks/witness-chain-VBKORKOX.js +0 -2
  431. package/dist/cli/chunks/workflow-orchestrator-3ZN7MVCE.js +0 -2
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.11");process.exit(0)}
2
- import{b as Tm,c as Em}from"./chunk-4HJKQIX5.js";import{a as Lm}from"./chunk-55CH76ZO.js";import{b as Fm,c as xs,d as Bm}from"./chunk-RQMCZQN2.js";import{b as _m}from"./chunk-72ZBJD2E.js";import{a as Kr,b as Kc,d as Nm}from"./chunk-TCYSBC7Y.js";import{b as jm,d as wr}from"./chunk-X3PZCXWG.js";import{a as rt,b as Os,c as tn,d as Hm}from"./chunk-2VLYUF7U.js";import{a as he,b as _s,c as Vt,d as nn}from"./chunk-GBFUANTC.js";import{c as Uc,d as Ms,e as Qc,k as Om}from"./chunk-5WYZHDIZ.js";import{a as qm}from"./chunk-672XOJDG.js";import{a as Jc,b as Zi,c as $t,d as br,e as Vm,f as Ot,g as Jr,h as Fs,i as zm}from"./chunk-IENZSO3K.js";import{a as Nc,c as km,d as Dm,w as Rs}from"./chunk-2CW7VRPH.js";import{e as Ym}from"./chunk-T5KHJ3J7.js";import{a as N,b as Ki,c as je,d as He,e as Ts,f as Es,g as As,h as Lt,i as zc,j as bt}from"./chunk-BTVWA35P.js";import{a as Bc,b as Ps,c as qc,d as Yi,e as Gc,f as jc,g as Xi,h as Hc,i as ks}from"./chunk-U3LJNNVJ.js";import{a as pe}from"./chunk-TFW7CCKS.js";import{a as Sm}from"./chunk-XDI5X3FR.js";import{b as Zc}from"./chunk-EK5GMOSO.js";import{a as rn}from"./chunk-APPZATXA.js";import{a as A,b as Ji,c as vr,d as wt,e as en,f as Gm,g as it,h as _t}from"./chunk-H7BLYMNU.js";import{b as Mm,c as Re,d as Qr}from"./chunk-M7XFBSIK.js";import{a as Ur,b as Im,c as Ft,e as Wm,h as Um}from"./chunk-OD5D4LSZ.js";import{c as Ns}from"./chunk-GVKVJJQX.js";import{a as Qm,b as Km,e as Jm}from"./chunk-RBZCA7SD.js";import{a as Xr,b as Xc}from"./chunk-LQ4NUC6Q.js";import{a as Ls,b as $s,c as Nt,d as Yc,e as Yr}from"./chunk-ITL3IN2E.js";import{e as Vs,l as zs,q as Cb}from"./chunk-LCVEEII4.js";import{b as _c}from"./chunk-H43AFUKL.js";import{a as $m,j as tt}from"./chunk-VEEYL2CZ.js";import{b as Wc,d as Ds}from"./chunk-JUMICXM6.js";import{a as Vc,b as Is}from"./chunk-OH5V5EJW.js";import{c as Qi}from"./chunk-KXS3Y2AX.js";import{a as xm,c as Pm}from"./chunk-DOBZPSKE.js";import{b as Am}from"./chunk-CO3DX2AX.js";import{b as pm}from"./chunk-RTY7VSZB.js";import{a as Oc}from"./chunk-OV5RPLKV.js";import{a as Cm}from"./chunk-EWPUQCN4.js";import{a as et,b as Wi,c as vm,d as bb,f as bm,g as wb}from"./chunk-O4JAKWWM.js";import{a as Ui,b as wm}from"./chunk-S6IYEBAI.js";import{b as ym,f as vb}from"./chunk-5HQP4SLM.js";import{g as gm,i as hm,j as fm,l as Cs,m as ae,n as Pe}from"./chunk-5MNASJOH.js";import{c as Ss,d as Rm}from"./chunk-4RH5I24Q.js";import{r as fr,v as yr}from"./chunk-LD5CFK53.js";import{b as D,d as X}from"./chunk-JFLU7L3W.js";import{a as Ve,b as gr,c as ws,e as hr}from"./chunk-WM3SRRA6.js";import{a as z,b as Se,d as ge}from"./chunk-M5XYIQYZ.js";import{c as Hi,d as Lc,e as $c}from"./chunk-NQZNMCZU.js";import{a as Mt,b as pr,c as vs,d as bs}from"./chunk-EJPK7OTR.js";import{i as w}from"./chunk-7R5HC56U.js";import{a as Ne,c as f,d as g}from"./chunk-IW6WDGHM.js";import{a as _}from"./chunk-IO5537OM.js";import{c as x}from"./chunk-FZHSG75I.js";import{a as ji,c as Mc,d as Fc}from"./chunk-VO3DRK4P.js";import{S as vt,b as ur,n as dr}from"./chunk-76SNL7GU.js";import{c as Ce,d as mr}from"./chunk-EH2S6AOR.js";import{f as yb}from"./chunk-J4JMCZVA.js";import{a as P,b as y,c as yt,e as k}from"./chunk-DDEOZPWJ.js";import{a as mm,b as ft,c as G,d as Hr,e as fb,f as Wr}from"./chunk-CFWGGRE7.js";var cp={};Hr(cp,{ALL_SUPPORTED_LANGUAGES:()=>Nb,ALL_TEST_FRAMEWORKS:()=>Us,DEFAULT_FRAMEWORKS:()=>ul,FRAMEWORK_ALIASES:()=>ll,FRAMEWORK_TO_LANGUAGE:()=>Ob,LANGUAGE_FILE_EXTENSIONS:()=>op,getLanguageFromExtension:()=>zt,resolveFrameworkAlias:()=>Qs});function Qs(c){let t=c.toLowerCase().trim();return Us.includes(t)?t:Object.hasOwn(ll,t)?ll[t]:void 0}function zt(c){return op[c.startsWith(".")?c:`.${c}`]}var ul,ll,Ob,op,Us,Nb,ei=ft(()=>{"use strict";ul={typescript:"vitest",javascript:"jest",python:"pytest",java:"junit5",csharp:"xunit",go:"go-test",rust:"rust-test",swift:"swift-testing",kotlin:"kotlin-junit",dart:"flutter-test"},ll={junit:"junit5","junit-5":"junit5","junit-4":"junit5",nunit:"nunit","x-unit":"xunit",xunit:"xunit",gotest:"go-test",go_test:"go-test",rusttest:"rust-test",rust_test:"rust-test",swift_testing:"swift-testing",swifttesting:"swift-testing",kotlin_junit:"kotlin-junit",kotlinjunit:"kotlin-junit",flutter_test:"flutter-test",fluttertest:"flutter-test",jest_rn:"jest-rn","jest-react-native":"jest-rn","react-native":"jest-rn"},Ob={jest:"javascript",vitest:"typescript",mocha:"javascript",pytest:"python","node-test":"javascript",junit5:"java",testng:"java",xunit:"csharp",nunit:"csharp","go-test":"go","rust-test":"rust","swift-testing":"swift",xctest:"swift","kotlin-junit":"kotlin","flutter-test":"dart","jest-rn":"javascript",playwright:"typescript",cypress:"javascript"},op={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".java":"java",".cs":"csharp",".go":"go",".rs":"rust",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".dart":"dart"},Us=["jest","vitest","mocha","pytest","node-test","junit5","testng","xunit","nunit","go-test","rust-test","swift-testing","xctest","kotlin-junit","flutter-test","jest-rn","playwright","cypress"],Nb=["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]});function vl(c,t={}){let{additionalContext:e,sourceCode:r,includeEvidence:i=!0,includeRemediation:n=!0,maxLength:s=8e3}=t,a=[];a.push(`# Security Finding Verification Request
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
2
+ import{b as Tm,c as Em}from"./chunk-HLGFHHWV.js";import{a as Lm}from"./chunk-W5HQIYQU.js";import{b as Fm,c as xs,d as Bm}from"./chunk-JNXK47OL.js";import{b as _m}from"./chunk-XCNSGSKV.js";import{a as Kr,b as Kc,d as Nm}from"./chunk-MCPEC6OO.js";import{b as jm,d as wr}from"./chunk-MYUMJ2ZI.js";import{a as rt,b as Os,c as tn,d as Hm}from"./chunk-UCSK2RMI.js";import{a as he,b as _s,c as Vt,d as nn}from"./chunk-TOWOJGEI.js";import{c as Uc,d as Ms,e as Qc,k as Om}from"./chunk-4Y6OEBJZ.js";import{a as qm}from"./chunk-2JYUA27M.js";import{a as Jc,b as Zi,c as $t,d as br,e as Vm,f as Ot,g as Jr,h as Fs,i as zm}from"./chunk-26672ISV.js";import{a as Nc,c as km,d as Dm,w as Rs}from"./chunk-J7Y7ZBIT.js";import{e as Ym}from"./chunk-4KUOYDY2.js";import{a as N,b as Ki,c as je,d as He,e as Ts,f as Es,g as As,h as Lt,i as zc,j as bt}from"./chunk-INZARYUD.js";import{a as Bc,b as Ps,c as qc,d as Yi,e as Gc,f as jc,g as Xi,h as Hc,i as ks}from"./chunk-4HWUECVD.js";import{a as pe}from"./chunk-AJEXPFAB.js";import{a as Sm}from"./chunk-ENGL7FIJ.js";import{b as Zc}from"./chunk-PX5OPXY6.js";import{a as rn}from"./chunk-P5E26N2X.js";import{a as A,b as Ji,c as vr,d as wt,e as en,f as Gm,g as it,h as _t}from"./chunk-QWG3SILX.js";import{b as Mm,c as Re,d as Qr}from"./chunk-HSA5IGGW.js";import{a as Ur,b as Im,c as Ft,e as Wm,h as Um}from"./chunk-K3A3NWT3.js";import{c as Ns}from"./chunk-NA3F6FEO.js";import{a as Qm,b as Km,e as Jm}from"./chunk-ICKUINKD.js";import{a as Xr,b as Xc}from"./chunk-U6IXYQO4.js";import{a as Ls,b as $s,c as Nt,d as Yc,e as Yr}from"./chunk-SQVZ3TRU.js";import{e as Vs,l as zs,q as Cb}from"./chunk-A2JCRXTK.js";import{b as _c}from"./chunk-VXVTFKRA.js";import{a as $m,j as tt}from"./chunk-G3AABG4Q.js";import{b as Wc,d as Ds}from"./chunk-A5Y7DAVQ.js";import{a as Vc,b as Is}from"./chunk-NX4BCSOZ.js";import{c as Qi}from"./chunk-NV74SICL.js";import{a as xm,c as Pm}from"./chunk-SDRJJUPO.js";import{b as Am}from"./chunk-SUX5XB2Z.js";import{b as pm}from"./chunk-SG2TX72G.js";import{a as Oc}from"./chunk-GKFV6CUD.js";import{a as Cm}from"./chunk-PTBOLBM4.js";import{a as et,b as Wi,c as vm,d as bb,f as bm,g as wb}from"./chunk-OHVYINGM.js";import{a as Ui,b as wm}from"./chunk-CA5UNWQF.js";import{b as ym,f as vb}from"./chunk-TGMXUZZC.js";import{g as gm,i as hm,j as fm,l as Cs,m as ae,n as Pe}from"./chunk-PGSJBXTD.js";import{c as Ss,d as Rm}from"./chunk-4CB3QPZM.js";import{r as fr,v as yr}from"./chunk-L7NGKANW.js";import{b as D,d as X}from"./chunk-WTAUF6O4.js";import{a as Ve,b as gr,c as ws,e as hr}from"./chunk-SPC4RBLF.js";import{a as z,b as Se,d as ge}from"./chunk-ZROAMFX2.js";import{c as Hi,d as Lc,e as $c}from"./chunk-YUA6ZKKY.js";import{a as Mt,b as pr,c as vs,d as bs}from"./chunk-6QRI3JVE.js";import{i as w}from"./chunk-7TA5MUPW.js";import{a as Ne,c as f,d as g}from"./chunk-VZBC6DP7.js";import{a as _}from"./chunk-UJNGGFGX.js";import{c as x}from"./chunk-ADUAJIAU.js";import{a as ji,c as Mc,d as Fc}from"./chunk-7OEFBWAG.js";import{S as vt,b as ur,n as dr}from"./chunk-35MIUSXQ.js";import{c as Ce,d as mr}from"./chunk-DZGPUGUG.js";import{f as yb}from"./chunk-5A66EGEW.js";import{a as P,b as y,c as yt,e as k}from"./chunk-W4II6SIH.js";import{a as mm,b as ft,c as G,d as Hr,e as fb,f as Wr}from"./chunk-WDEXOLK2.js";var cp={};Hr(cp,{ALL_SUPPORTED_LANGUAGES:()=>Nb,ALL_TEST_FRAMEWORKS:()=>Us,DEFAULT_FRAMEWORKS:()=>ul,FRAMEWORK_ALIASES:()=>ll,FRAMEWORK_TO_LANGUAGE:()=>Ob,LANGUAGE_FILE_EXTENSIONS:()=>op,getLanguageFromExtension:()=>zt,resolveFrameworkAlias:()=>Qs});function Qs(c){let t=c.toLowerCase().trim();return Us.includes(t)?t:Object.hasOwn(ll,t)?ll[t]:void 0}function zt(c){return op[c.startsWith(".")?c:`.${c}`]}var ul,ll,Ob,op,Us,Nb,ei=ft(()=>{"use strict";ul={typescript:"vitest",javascript:"jest",python:"pytest",java:"junit5",csharp:"xunit",go:"go-test",rust:"rust-test",swift:"swift-testing",kotlin:"kotlin-junit",dart:"flutter-test"},ll={junit:"junit5","junit-5":"junit5","junit-4":"junit5",nunit:"nunit","x-unit":"xunit",xunit:"xunit",gotest:"go-test",go_test:"go-test",rusttest:"rust-test",rust_test:"rust-test",swift_testing:"swift-testing",swifttesting:"swift-testing",kotlin_junit:"kotlin-junit",kotlinjunit:"kotlin-junit",flutter_test:"flutter-test",fluttertest:"flutter-test",jest_rn:"jest-rn","jest-react-native":"jest-rn","react-native":"jest-rn"},Ob={jest:"javascript",vitest:"typescript",mocha:"javascript",pytest:"python","node-test":"javascript",junit5:"java",testng:"java",xunit:"csharp",nunit:"csharp","go-test":"go","rust-test":"rust","swift-testing":"swift",xctest:"swift","kotlin-junit":"kotlin","flutter-test":"dart","jest-rn":"javascript",playwright:"typescript",cypress:"javascript"},op={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".java":"java",".cs":"csharp",".go":"go",".rs":"rust",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".dart":"dart"},Us=["jest","vitest","mocha","pytest","node-test","junit5","testng","xunit","nunit","go-test","rust-test","swift-testing","xctest","kotlin-junit","flutter-test","jest-rn","playwright","cypress"],Nb=["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]});function vl(c,t={}){let{additionalContext:e,sourceCode:r,includeEvidence:i=!0,includeRemediation:n=!0,maxLength:s=8e3}=t,a=[];a.push(`# Security Finding Verification Request
3
3
 
4
4
  You are a security expert tasked with verifying whether the following security finding is valid or a false positive.
5
5
 
@@ -111,10 +111,10 @@ Format your response with: verdict (confirmed/rejected/uncertain), confidence (0
111
111
  Your task is to verify security findings with high accuracy.
112
112
  Be thorough but avoid false positives.
113
113
  Always explain your reasoning clearly.
114
- Format your response with: verdict (confirmed/rejected/uncertain), confidence (0-100), and reasoning.`}}});var Pi=G((YJ,ff)=>{"use strict";var T0="2.0.0",E0=Number.MAX_SAFE_INTEGER||9007199254740991,A0=16,x0=250,P0=["major","premajor","minor","preminor","patch","prepatch","prerelease"];ff.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:A0,MAX_SAFE_BUILD_LENGTH:x0,MAX_SAFE_INTEGER:E0,RELEASE_TYPES:P0,SEMVER_SPEC_VERSION:T0,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var as=G((XJ,yf)=>{"use strict";var k0=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...c)=>console.error("SEMVER",...c):()=>{};yf.exports=k0});var ki=G((ht,vf)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Ed,MAX_SAFE_BUILD_LENGTH:D0,MAX_LENGTH:I0}=Pi(),M0=as();ht=vf.exports={};var F0=ht.re=[],L0=ht.safeRe=[],F=ht.src=[],$0=ht.safeSrc=[],L=ht.t={},O0=0,Ad="[a-zA-Z0-9-]",N0=[["\\s",1],["\\d",I0],[Ad,D0]],_0=c=>{for(let[t,e]of N0)c=c.split(`${t}*`).join(`${t}{0,${e}}`).split(`${t}+`).join(`${t}{1,${e}}`);return c},W=(c,t,e)=>{let r=_0(t),i=O0++;M0(c,i,t),L[c]=i,F[i]=t,$0[i]=r,F0[i]=new RegExp(t,e?"g":void 0),L0[i]=new RegExp(r,e?"g":void 0)};W("NUMERICIDENTIFIER","0|[1-9]\\d*");W("NUMERICIDENTIFIERLOOSE","\\d+");W("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Ad}*`);W("MAINVERSION",`(${F[L.NUMERICIDENTIFIER]})\\.(${F[L.NUMERICIDENTIFIER]})\\.(${F[L.NUMERICIDENTIFIER]})`);W("MAINVERSIONLOOSE",`(${F[L.NUMERICIDENTIFIERLOOSE]})\\.(${F[L.NUMERICIDENTIFIERLOOSE]})\\.(${F[L.NUMERICIDENTIFIERLOOSE]})`);W("PRERELEASEIDENTIFIER",`(?:${F[L.NONNUMERICIDENTIFIER]}|${F[L.NUMERICIDENTIFIER]})`);W("PRERELEASEIDENTIFIERLOOSE",`(?:${F[L.NONNUMERICIDENTIFIER]}|${F[L.NUMERICIDENTIFIERLOOSE]})`);W("PRERELEASE",`(?:-(${F[L.PRERELEASEIDENTIFIER]}(?:\\.${F[L.PRERELEASEIDENTIFIER]})*))`);W("PRERELEASELOOSE",`(?:-?(${F[L.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${F[L.PRERELEASEIDENTIFIERLOOSE]})*))`);W("BUILDIDENTIFIER",`${Ad}+`);W("BUILD",`(?:\\+(${F[L.BUILDIDENTIFIER]}(?:\\.${F[L.BUILDIDENTIFIER]})*))`);W("FULLPLAIN",`v?${F[L.MAINVERSION]}${F[L.PRERELEASE]}?${F[L.BUILD]}?`);W("FULL",`^${F[L.FULLPLAIN]}$`);W("LOOSEPLAIN",`[v=\\s]*${F[L.MAINVERSIONLOOSE]}${F[L.PRERELEASELOOSE]}?${F[L.BUILD]}?`);W("LOOSE",`^${F[L.LOOSEPLAIN]}$`);W("GTLT","((?:<|>)?=?)");W("XRANGEIDENTIFIERLOOSE",`${F[L.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);W("XRANGEIDENTIFIER",`${F[L.NUMERICIDENTIFIER]}|x|X|\\*`);W("XRANGEPLAIN",`[v=\\s]*(${F[L.XRANGEIDENTIFIER]})(?:\\.(${F[L.XRANGEIDENTIFIER]})(?:\\.(${F[L.XRANGEIDENTIFIER]})(?:${F[L.PRERELEASE]})?${F[L.BUILD]}?)?)?`);W("XRANGEPLAINLOOSE",`[v=\\s]*(${F[L.XRANGEIDENTIFIERLOOSE]})(?:\\.(${F[L.XRANGEIDENTIFIERLOOSE]})(?:\\.(${F[L.XRANGEIDENTIFIERLOOSE]})(?:${F[L.PRERELEASELOOSE]})?${F[L.BUILD]}?)?)?`);W("XRANGE",`^${F[L.GTLT]}\\s*${F[L.XRANGEPLAIN]}$`);W("XRANGELOOSE",`^${F[L.GTLT]}\\s*${F[L.XRANGEPLAINLOOSE]}$`);W("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Ed}})(?:\\.(\\d{1,${Ed}}))?(?:\\.(\\d{1,${Ed}}))?`);W("COERCE",`${F[L.COERCEPLAIN]}(?:$|[^\\d])`);W("COERCEFULL",F[L.COERCEPLAIN]+`(?:${F[L.PRERELEASE]})?(?:${F[L.BUILD]})?(?:$|[^\\d])`);W("COERCERTL",F[L.COERCE],!0);W("COERCERTLFULL",F[L.COERCEFULL],!0);W("LONETILDE","(?:~>?)");W("TILDETRIM",`(\\s*)${F[L.LONETILDE]}\\s+`,!0);ht.tildeTrimReplace="$1~";W("TILDE",`^${F[L.LONETILDE]}${F[L.XRANGEPLAIN]}$`);W("TILDELOOSE",`^${F[L.LONETILDE]}${F[L.XRANGEPLAINLOOSE]}$`);W("LONECARET","(?:\\^)");W("CARETTRIM",`(\\s*)${F[L.LONECARET]}\\s+`,!0);ht.caretTrimReplace="$1^";W("CARET",`^${F[L.LONECARET]}${F[L.XRANGEPLAIN]}$`);W("CARETLOOSE",`^${F[L.LONECARET]}${F[L.XRANGEPLAINLOOSE]}$`);W("COMPARATORLOOSE",`^${F[L.GTLT]}\\s*(${F[L.LOOSEPLAIN]})$|^$`);W("COMPARATOR",`^${F[L.GTLT]}\\s*(${F[L.FULLPLAIN]})$|^$`);W("COMPARATORTRIM",`(\\s*)${F[L.GTLT]}\\s*(${F[L.LOOSEPLAIN]}|${F[L.XRANGEPLAIN]})`,!0);ht.comparatorTrimReplace="$1$2$3";W("HYPHENRANGE",`^\\s*(${F[L.XRANGEPLAIN]})\\s+-\\s+(${F[L.XRANGEPLAIN]})\\s*$`);W("HYPHENRANGELOOSE",`^\\s*(${F[L.XRANGEPLAINLOOSE]})\\s+-\\s+(${F[L.XRANGEPLAINLOOSE]})\\s*$`);W("STAR","(<|>)?=?\\s*\\*");W("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");W("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Yo=G((ZJ,bf)=>{"use strict";var V0=Object.freeze({loose:!0}),z0=Object.freeze({}),B0=c=>c?typeof c!="object"?V0:c:z0;bf.exports=B0});var xd=G((e7,Sf)=>{"use strict";var wf=/^[0-9]+$/,Cf=(c,t)=>{if(typeof c=="number"&&typeof t=="number")return c===t?0:c<t?-1:1;let e=wf.test(c),r=wf.test(t);return e&&r&&(c=+c,t=+t),c===t?0:e&&!r?-1:r&&!e?1:c<t?-1:1},q0=(c,t)=>Cf(t,c);Sf.exports={compareIdentifiers:Cf,rcompareIdentifiers:q0}});var Ae=G((t7,Tf)=>{"use strict";var Xo=as(),{MAX_LENGTH:Rf,MAX_SAFE_INTEGER:Zo}=Pi(),{safeRe:ec,t:tc}=ki(),G0=Yo(),{compareIdentifiers:Pd}=xd(),j0=(c,t)=>{let e=t.split(".");if(e.length>c.length)return!1;for(let r=0;r<e.length;r++)if(Pd(c[r],e[r])!==0)return!1;return!0},kd=class c{constructor(t,e){if(e=G0(e),t instanceof c){if(t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>Rf)throw new TypeError(`version is longer than ${Rf} characters`);Xo("SemVer",t,e),this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease;let r=t.trim().match(e.loose?ec[tc.LOOSE]:ec[tc.FULL]);if(!r)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>Zo||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Zo||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Zo||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let n=+i;if(n>=0&&n<Zo)return n}return i}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(Xo("SemVer.compare",this.version,this.options,t),!(t instanceof c)){if(typeof t=="string"&&t===this.version)return 0;t=new c(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof c||(t=new c(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof c||(t=new c(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let e=0;do{let r=this.prerelease[e],i=t.prerelease[e];if(Xo("prerelease compare",e,r,i),r===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(r===void 0)return-1;if(r===i)continue;return Pd(r,i)}while(++e)}compareBuild(t){t instanceof c||(t=new c(t,this.options));let e=0;do{let r=this.build[e],i=t.build[e];if(Xo("build compare",e,r,i),r===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(r===void 0)return-1;if(r===i)continue;return Pd(r,i)}while(++e)}inc(t,e,r){if(t.startsWith("pre")){if(!e&&r===!1)throw new Error("invalid increment argument: identifier is empty");if(e){let i=`-${e}`.match(this.options.loose?ec[tc.PRERELEASELOOSE]:ec[tc.PRERELEASE]);if(!i||i[1]!==e)throw new Error(`invalid identifier: ${e}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",e,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",e,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",e,r),this.inc("pre",e,r);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",e,r),this.inc("pre",e,r);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let i=Number(r)?1:0;if(this.prerelease.length===0)this.prerelease=[i];else{let n=this.prerelease.length;for(;--n>=0;)typeof this.prerelease[n]=="number"&&(this.prerelease[n]++,n=-2);if(n===-1){if(e===this.prerelease.join(".")&&r===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(e){let n=[e,i];if(r===!1&&(n=[e]),j0(this.prerelease,e)){let s=this.prerelease[e.split(".").length];isNaN(s)&&(this.prerelease=n)}else this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Tf.exports=kd});var sr=G((r7,Af)=>{"use strict";var Ef=Ae(),H0=(c,t,e=!1)=>{if(c instanceof Ef)return c;try{return new Ef(c,t)}catch(r){if(!e)return null;throw r}};Af.exports=H0});var Pf=G((i7,xf)=>{"use strict";var W0=sr(),U0=(c,t)=>{let e=W0(c,t);return e?e.version:null};xf.exports=U0});var Df=G((n7,kf)=>{"use strict";var Q0=sr(),K0=(c,t)=>{let e=Q0(c.trim().replace(/^[=v]+/,""),t);return e?e.version:null};kf.exports=K0});var Ff=G((s7,Mf)=>{"use strict";var If=Ae(),J0=(c,t,e,r,i)=>{typeof e=="string"&&(i=r,r=e,e=void 0);try{return new If(c instanceof If?c.version:c,e).inc(t,r,i).version}catch{return null}};Mf.exports=J0});var Of=G((a7,$f)=>{"use strict";var Lf=sr(),Y0=(c,t)=>{let e=Lf(c,null,!0),r=Lf(t,null,!0),i=e.compare(r);if(i===0)return null;let n=i>0,s=n?e:r,a=n?r:e,o=!!s.prerelease.length;if(!!a.prerelease.length&&!o){if(!a.patch&&!a.minor)return"major";if(a.compareMain(s)===0)return a.minor&&!a.patch?"minor":"patch"}let u=o?"pre":"";return e.major!==r.major?u+"major":e.minor!==r.minor?u+"minor":e.patch!==r.patch?u+"patch":"prerelease"};$f.exports=Y0});var _f=G((o7,Nf)=>{"use strict";var X0=Ae(),Z0=(c,t)=>new X0(c,t).major;Nf.exports=Z0});var zf=G((c7,Vf)=>{"use strict";var eE=Ae(),tE=(c,t)=>new eE(c,t).minor;Vf.exports=tE});var qf=G((l7,Bf)=>{"use strict";var rE=Ae(),iE=(c,t)=>new rE(c,t).patch;Bf.exports=iE});var jf=G((u7,Gf)=>{"use strict";var nE=sr(),sE=(c,t)=>{let e=nE(c,t);return e&&e.prerelease.length?e.prerelease:null};Gf.exports=sE});var Je=G((d7,Wf)=>{"use strict";var Hf=Ae(),aE=(c,t,e)=>new Hf(c,e).compare(new Hf(t,e));Wf.exports=aE});var Qf=G((m7,Uf)=>{"use strict";var oE=Je(),cE=(c,t,e)=>oE(t,c,e);Uf.exports=cE});var Jf=G((p7,Kf)=>{"use strict";var lE=Je(),uE=(c,t)=>lE(c,t,!0);Kf.exports=uE});var rc=G((g7,Xf)=>{"use strict";var Yf=Ae(),dE=(c,t,e)=>{let r=new Yf(c,e),i=new Yf(t,e);return r.compare(i)||r.compareBuild(i)};Xf.exports=dE});var ey=G((h7,Zf)=>{"use strict";var mE=rc(),pE=(c,t)=>c.sort((e,r)=>mE(e,r,t));Zf.exports=pE});var ry=G((f7,ty)=>{"use strict";var gE=rc(),hE=(c,t)=>c.sort((e,r)=>gE(r,e,t));ty.exports=hE});var os=G((y7,iy)=>{"use strict";var fE=Je(),yE=(c,t,e)=>fE(c,t,e)>0;iy.exports=yE});var ic=G((v7,ny)=>{"use strict";var vE=Je(),bE=(c,t,e)=>vE(c,t,e)<0;ny.exports=bE});var Dd=G((b7,sy)=>{"use strict";var wE=Je(),CE=(c,t,e)=>wE(c,t,e)===0;sy.exports=CE});var Id=G((w7,ay)=>{"use strict";var SE=Je(),RE=(c,t,e)=>SE(c,t,e)!==0;ay.exports=RE});var nc=G((C7,oy)=>{"use strict";var TE=Je(),EE=(c,t,e)=>TE(c,t,e)>=0;oy.exports=EE});var sc=G((S7,cy)=>{"use strict";var AE=Je(),xE=(c,t,e)=>AE(c,t,e)<=0;cy.exports=xE});var Md=G((R7,ly)=>{"use strict";var PE=Dd(),kE=Id(),DE=os(),IE=nc(),ME=ic(),FE=sc(),LE=(c,t,e,r)=>{switch(t){case"===":return typeof c=="object"&&(c=c.version),typeof e=="object"&&(e=e.version),c===e;case"!==":return typeof c=="object"&&(c=c.version),typeof e=="object"&&(e=e.version),c!==e;case"":case"=":case"==":return PE(c,e,r);case"!=":return kE(c,e,r);case">":return DE(c,e,r);case">=":return IE(c,e,r);case"<":return ME(c,e,r);case"<=":return FE(c,e,r);default:throw new TypeError(`Invalid operator: ${t}`)}};ly.exports=LE});var dy=G((T7,uy)=>{"use strict";var $E=Ae(),OE=sr(),{safeRe:ac,t:oc}=ki(),NE=(c,t)=>{if(c instanceof $E)return c;if(typeof c=="number"&&(c=String(c)),typeof c!="string")return null;t=t||{};let e=null;if(!t.rtl)e=c.match(t.includePrerelease?ac[oc.COERCEFULL]:ac[oc.COERCE]);else{let o=t.includePrerelease?ac[oc.COERCERTLFULL]:ac[oc.COERCERTL],l;for(;(l=o.exec(c))&&(!e||e.index+e[0].length!==c.length);)(!e||l.index+l[0].length!==e.index+e[0].length)&&(e=l),o.lastIndex=l.index+l[1].length+l[2].length;o.lastIndex=-1}if(e===null)return null;let r=e[2],i=e[3]||"0",n=e[4]||"0",s=t.includePrerelease&&e[5]?`-${e[5]}`:"",a=t.includePrerelease&&e[6]?`+${e[6]}`:"";return OE(`${r}.${i}.${n}${s}${a}`,t)};uy.exports=NE});var py=G((E7,my)=>{"use strict";var _E=sr(),VE=Pi(),zE=Ae(),BE=(c,t,e)=>{if(!VE.RELEASE_TYPES.includes(t))return null;let r=qE(c,e);return r&&GE(r,t)},qE=(c,t)=>{let e=c instanceof zE?c.version:c;return _E(e,t)},GE=(c,t)=>{if(jE(t))return c.version;switch(c.prerelease=[],t){case"major":c.minor=0,c.patch=0;break;case"minor":c.patch=0;break}return c.format()},jE=c=>c.startsWith("pre");my.exports=BE});var hy=G((A7,gy)=>{"use strict";var Fd=class{constructor(){this.max=1e3,this.map=new Map}get(t){let e=this.map.get(t);if(e!==void 0)return this.map.delete(t),this.map.set(t,e),e}delete(t){return this.map.delete(t)}set(t,e){if(!this.delete(t)&&e!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(t,e)}return this}};gy.exports=Fd});var Ye=G((x7,by)=>{"use strict";var HE=/\s+/g,Ld=class c{constructor(t,e){if(e=UE(e),t instanceof c)return t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease?t:new c(t.raw,e);if(t instanceof $d)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease,this.raw=t.trim().replace(HE," "),this.set=this.raw.split("||").map(r=>this.parseRange(r.trim())).filter(r=>r.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let r=this.set[0];if(this.set=this.set.filter(i=>!yy(i[0])),this.set.length===0)this.set=[r];else if(this.set.length>1){for(let i of this.set)if(i.length===1&&rA(i[0])){this.set=[i];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t<this.set.length;t++){t>0&&(this.formatted+="||");let e=this.set[t];for(let r=0;r<e.length;r++)r>0&&(this.formatted+=" "),this.formatted+=e[r].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){t=t.replace(tA,"");let r=((this.options.includePrerelease&&ZE)|(this.options.loose&&eA))+":"+t,i=fy.get(r);if(i)return i;let n=this.options.loose,s=n?$e[xe.HYPHENRANGELOOSE]:$e[xe.HYPHENRANGE];t=t.replace(s,pA(this.options.includePrerelease)),oe("hyphen replace",t),t=t.replace($e[xe.COMPARATORTRIM],JE),oe("comparator trim",t),t=t.replace($e[xe.TILDETRIM],YE),oe("tilde trim",t),t=t.replace($e[xe.CARETTRIM],XE),oe("caret trim",t);let a=t.split(" ").map(d=>iA(d,this.options)).join(" ").split(/\s+/).map(d=>mA(d,this.options));n&&(a=a.filter(d=>(oe("loose invalid filter",d,this.options),!!d.match($e[xe.COMPARATORLOOSE])))),oe("range list",a);let o=new Map,l=a.map(d=>new $d(d,this.options));for(let d of l){if(yy(d))return[d];o.set(d.value,d)}o.size>1&&o.has("")&&o.delete("");let u=[...o.values()];return fy.set(r,u),u}intersects(t,e){if(!(t instanceof c))throw new TypeError("a Range is required");return this.set.some(r=>vy(r,e)&&t.set.some(i=>vy(i,e)&&r.every(n=>i.every(s=>n.intersects(s,e)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new QE(t,this.options)}catch{return!1}for(let e=0;e<this.set.length;e++)if(gA(this.set[e],t,this.options))return!0;return!1}};by.exports=Ld;var WE=hy(),fy=new WE,UE=Yo(),$d=cs(),oe=as(),QE=Ae(),{safeRe:$e,src:KE,t:xe,comparatorTrimReplace:JE,tildeTrimReplace:YE,caretTrimReplace:XE}=ki(),{FLAG_INCLUDE_PRERELEASE:ZE,FLAG_LOOSE:eA}=Pi(),tA=new RegExp(KE[xe.BUILD],"g"),yy=c=>c.value==="<0.0.0-0",rA=c=>c.value==="",vy=(c,t)=>{let e=!0,r=c.slice(),i=r.pop();for(;e&&r.length;)e=r.every(n=>i.intersects(n,t)),i=r.pop();return e},iA=(c,t)=>(c=c.replace($e[xe.BUILD],""),oe("comp",c,t),c=oA(c,t),oe("caret",c),c=sA(c,t),oe("tildes",c),c=lA(c,t),oe("xrange",c),c=dA(c,t),oe("stars",c),c),ye=c=>!c||c.toLowerCase()==="x"||c==="*",nA=(c,t,e)=>ye(c)&&!ye(t)||ye(t)&&e&&!ye(e),sA=(c,t)=>c.trim().split(/\s+/).map(e=>aA(e,t)).join(" "),aA=(c,t)=>{let e=t.loose?$e[xe.TILDELOOSE]:$e[xe.TILDE],r=t.includePrerelease?"-0":"";return c.replace(e,(i,n,s,a,o)=>{oe("tilde",c,i,n,s,a,o);let l;return ye(n)?l="":ye(s)?l=`>=${n}.0.0${r} <${+n+1}.0.0-0`:ye(a)?l=`>=${n}.${s}.0${r} <${n}.${+s+1}.0-0`:o?(oe("replaceTilde pr",o),l=`>=${n}.${s}.${a}-${o} <${n}.${+s+1}.0-0`):l=`>=${n}.${s}.${a} <${n}.${+s+1}.0-0`,oe("tilde return",l),l})},oA=(c,t)=>c.trim().split(/\s+/).map(e=>cA(e,t)).join(" "),cA=(c,t)=>{oe("caret",c,t);let e=t.loose?$e[xe.CARETLOOSE]:$e[xe.CARET],r=t.includePrerelease?"-0":"";return c.replace(e,(i,n,s,a,o)=>{oe("caret",c,i,n,s,a,o);let l;return ye(n)?l="":ye(s)?l=`>=${n}.0.0${r} <${+n+1}.0.0-0`:ye(a)?n==="0"?l=`>=${n}.${s}.0${r} <${n}.${+s+1}.0-0`:l=`>=${n}.${s}.0${r} <${+n+1}.0.0-0`:o?(oe("replaceCaret pr",o),n==="0"?s==="0"?l=`>=${n}.${s}.${a}-${o} <${n}.${s}.${+a+1}-0`:l=`>=${n}.${s}.${a}-${o} <${n}.${+s+1}.0-0`:l=`>=${n}.${s}.${a}-${o} <${+n+1}.0.0-0`):(oe("no pr"),n==="0"?s==="0"?l=`>=${n}.${s}.${a} <${n}.${s}.${+a+1}-0`:l=`>=${n}.${s}.${a} <${n}.${+s+1}.0-0`:l=`>=${n}.${s}.${a} <${+n+1}.0.0-0`),oe("caret return",l),l})},lA=(c,t)=>(oe("replaceXRanges",c,t),c.split(/\s+/).map(e=>uA(e,t)).join(" ")),uA=(c,t)=>{c=c.trim();let e=t.loose?$e[xe.XRANGELOOSE]:$e[xe.XRANGE];return c.replace(e,(r,i,n,s,a,o)=>{if(oe("xRange",c,r,i,n,s,a,o),nA(n,s,a))return c;let l=ye(n),u=l||ye(s),d=u||ye(a),m=d;return i==="="&&m&&(i=""),o=t.includePrerelease?"-0":"",l?i===">"||i==="<"?r="<0.0.0-0":r="*":i&&m?(u&&(s=0),a=0,i===">"?(i=">=",u?(n=+n+1,s=0,a=0):(s=+s+1,a=0)):i==="<="&&(i="<",u?n=+n+1:s=+s+1),i==="<"&&(o="-0"),r=`${i+n}.${s}.${a}${o}`):u?r=`>=${n}.0.0${o} <${+n+1}.0.0-0`:d&&(r=`>=${n}.${s}.0${o} <${n}.${+s+1}.0-0`),oe("xRange return",r),r})},dA=(c,t)=>(oe("replaceStars",c,t),c.trim().replace($e[xe.STAR],"")),mA=(c,t)=>(oe("replaceGTE0",c,t),c.trim().replace($e[t.includePrerelease?xe.GTE0PRE:xe.GTE0],"")),pA=c=>(t,e,r,i,n,s,a,o,l,u,d,m)=>(ye(r)?e="":ye(i)?e=`>=${r}.0.0${c?"-0":""}`:ye(n)?e=`>=${r}.${i}.0${c?"-0":""}`:s?e=`>=${e}`:e=`>=${e}${c?"-0":""}`,ye(l)?o="":ye(u)?o=`<${+l+1}.0.0-0`:ye(d)?o=`<${l}.${+u+1}.0-0`:m?o=`<=${l}.${u}.${d}-${m}`:c?o=`<${l}.${u}.${+d+1}-0`:o=`<=${o}`,`${e} ${o}`.trim()),gA=(c,t,e)=>{for(let r=0;r<c.length;r++)if(!c[r].test(t))return!1;if(t.prerelease.length&&!e.includePrerelease){for(let r=0;r<c.length;r++)if(oe(c[r].semver),c[r].semver!==$d.ANY&&c[r].semver.prerelease.length>0){let i=c[r].semver;if(i.major===t.major&&i.minor===t.minor&&i.patch===t.patch)return!0}return!1}return!0}});var cs=G((P7,Ey)=>{"use strict";var ls=Symbol("SemVer ANY"),_d=class c{static get ANY(){return ls}constructor(t,e){if(e=wy(e),t instanceof c){if(t.loose===!!e.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Nd("comparator",t,e),this.options=e,this.loose=!!e.loose,this.parse(t),this.semver===ls?this.value="":this.value=this.operator+this.semver.version,Nd("comp",this)}parse(t){let e=this.options.loose?Cy[Sy.COMPARATORLOOSE]:Cy[Sy.COMPARATOR],r=t.match(e);if(!r)throw new TypeError(`Invalid comparator: ${t}`);this.operator=r[1]!==void 0?r[1]:"",this.operator==="="&&(this.operator=""),r[2]?this.semver=new Ry(r[2],this.options.loose):this.semver=ls}toString(){return this.value}test(t){if(Nd("Comparator.test",t,this.options.loose),this.semver===ls||t===ls)return!0;if(typeof t=="string")try{t=new Ry(t,this.options)}catch{return!1}return Od(t,this.operator,this.semver,this.options)}intersects(t,e){if(!(t instanceof c))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Ty(t.value,e).test(this.value):t.operator===""?t.value===""?!0:new Ty(this.value,e).test(t.semver):(e=wy(e),e.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!e.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||Od(this.semver,"<",t.semver,e)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||Od(this.semver,">",t.semver,e)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};Ey.exports=_d;var wy=Yo(),{safeRe:Cy,t:Sy}=ki(),Od=Md(),Nd=as(),Ry=Ae(),Ty=Ye()});var us=G((k7,Ay)=>{"use strict";var hA=Ye(),fA=(c,t,e)=>{try{t=new hA(t,e)}catch{return!1}return t.test(c)};Ay.exports=fA});var Py=G((D7,xy)=>{"use strict";var yA=Ye(),vA=(c,t)=>new yA(c,t).set.map(e=>e.map(r=>r.value).join(" ").trim().split(" "));xy.exports=vA});var Dy=G((I7,ky)=>{"use strict";var bA=Ae(),wA=Ye(),CA=(c,t,e)=>{let r=null,i=null,n=null;try{n=new wA(t,e)}catch{return null}return c.forEach(s=>{n.test(s)&&(!r||i.compare(s)===-1)&&(r=s,i=new bA(r,e))}),r};ky.exports=CA});var My=G((M7,Iy)=>{"use strict";var SA=Ae(),RA=Ye(),TA=(c,t,e)=>{let r=null,i=null,n=null;try{n=new RA(t,e)}catch{return null}return c.forEach(s=>{n.test(s)&&(!r||i.compare(s)===1)&&(r=s,i=new SA(r,e))}),r};Iy.exports=TA});var $y=G((F7,Ly)=>{"use strict";var Vd=Ae(),EA=Ye(),Fy=os(),AA=(c,t)=>{c=new EA(c,t);let e=new Vd("0.0.0");if(c.test(e)||(e=new Vd("0.0.0-0"),c.test(e)))return e;e=null;for(let r=0;r<c.set.length;++r){let i=c.set[r],n=null;i.forEach(s=>{let a=new Vd(s.semver.version);switch(s.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!n||Fy(a,n))&&(n=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${s.operator}`)}}),n&&(!e||Fy(e,n))&&(e=n)}return e&&c.test(e)?e:null};Ly.exports=AA});var Ny=G((L7,Oy)=>{"use strict";var xA=Ye(),PA=(c,t)=>{try{return new xA(c,t).range||"*"}catch{return null}};Oy.exports=PA});var cc=G(($7,By)=>{"use strict";var kA=Ae(),zy=cs(),{ANY:DA}=zy,IA=Ye(),MA=us(),_y=os(),Vy=ic(),FA=sc(),LA=nc(),$A=(c,t,e,r)=>{c=new kA(c,r),t=new IA(t,r);let i,n,s,a,o;switch(e){case">":i=_y,n=FA,s=Vy,a=">",o=">=";break;case"<":i=Vy,n=LA,s=_y,a="<",o="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(MA(c,t,r))return!1;for(let l=0;l<t.set.length;++l){let u=t.set[l],d=null,m=null;if(u.forEach(p=>{p.semver===DA&&(p=new zy(">=0.0.0")),d=d||p,m=m||p,i(p.semver,d.semver,r)?d=p:s(p.semver,m.semver,r)&&(m=p)}),d.operator===a||d.operator===o||(!m.operator||m.operator===a)&&n(c,m.semver))return!1;if(m.operator===o&&s(c,m.semver))return!1}return!0};By.exports=$A});var Gy=G((O7,qy)=>{"use strict";var OA=cc(),NA=(c,t,e)=>OA(c,t,">",e);qy.exports=NA});var Hy=G((N7,jy)=>{"use strict";var _A=cc(),VA=(c,t,e)=>_A(c,t,"<",e);jy.exports=VA});var Qy=G((_7,Uy)=>{"use strict";var Wy=Ye(),zA=(c,t,e)=>(c=new Wy(c,e),t=new Wy(t,e),c.intersects(t,e));Uy.exports=zA});var Jy=G((V7,Ky)=>{"use strict";var BA=us(),qA=Je();Ky.exports=(c,t,e)=>{let r=[],i=null,n=null,s=c.sort((u,d)=>qA(u,d,e));for(let u of s)BA(u,t,e)?(n=u,i||(i=u)):(n&&r.push([i,n]),n=null,i=null);i&&r.push([i,null]);let a=[];for(let[u,d]of r)u===d?a.push(u):!d&&u===s[0]?a.push("*"):d?u===s[0]?a.push(`<=${d}`):a.push(`${u} - ${d}`):a.push(`>=${u}`);let o=a.join(" || "),l=typeof t.raw=="string"?t.raw:String(t);return o.length<l.length?o:t}});var rv=G((z7,tv)=>{"use strict";var Yy=Ye(),qd=cs(),{ANY:zd}=qd,Bd=us(),Gd=Je(),GA=(c,t,e={})=>{if(c===t)return!0;c=new Yy(c,e),t=new Yy(t,e);let r=!1;e:for(let i of c.set){for(let n of t.set){let s=HA(i,n,e);if(r=r||s!==null,s)continue e}if(r)return!1}return!0},jA=[new qd(">=0.0.0-0")],Xy=[new qd(">=0.0.0")],HA=(c,t,e)=>{if(c===t)return!0;if(c.length===1&&c[0].semver===zd){if(t.length===1&&t[0].semver===zd)return!0;e.includePrerelease?c=jA:c=Xy}if(t.length===1&&t[0].semver===zd){if(e.includePrerelease)return!0;t=Xy}let r=new Set,i,n;for(let p of c)p.operator===">"||p.operator===">="?i=Zy(i,p,e):p.operator==="<"||p.operator==="<="?n=ev(n,p,e):r.add(p.semver);if(r.size>1)return null;let s;if(i&&n){if(s=Gd(i.semver,n.semver,e),s>0)return null;if(s===0&&(i.operator!==">="||n.operator!=="<="))return null}for(let p of r){if(i&&!Bd(p,String(i),e)||n&&!Bd(p,String(n),e))return null;for(let h of t)if(!Bd(p,String(h),e))return!1;return!0}let a,o,l,u,d=n&&!e.includePrerelease&&n.semver.prerelease.length?n.semver:!1,m=i&&!e.includePrerelease&&i.semver.prerelease.length?i.semver:!1;d&&d.prerelease.length===1&&n.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let p of t){if(u=u||p.operator===">"||p.operator===">=",l=l||p.operator==="<"||p.operator==="<=",i){if(m&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===m.major&&p.semver.minor===m.minor&&p.semver.patch===m.patch&&(m=!1),p.operator===">"||p.operator===">="){if(a=Zy(i,p,e),a===p&&a!==i)return!1}else if(i.operator===">="&&!p.test(i.semver))return!1}if(n){if(d&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===d.major&&p.semver.minor===d.minor&&p.semver.patch===d.patch&&(d=!1),p.operator==="<"||p.operator==="<="){if(o=ev(n,p,e),o===p&&o!==n)return!1}else if(n.operator==="<="&&!p.test(n.semver))return!1}if(!p.operator&&(n||i)&&s!==0)return!1}return!(i&&l&&!n&&s!==0||n&&u&&!i&&s!==0||m||d)},Zy=(c,t,e)=>{if(!c)return t;let r=Gd(c.semver,t.semver,e);return r>0?c:r<0||t.operator===">"&&c.operator===">="?t:c},ev=(c,t,e)=>{if(!c)return t;let r=Gd(c.semver,t.semver,e);return r<0?c:r>0||t.operator==="<"&&c.operator==="<="?t:c};tv.exports=GA});var av=G((B7,sv)=>{"use strict";var jd=ki(),iv=Pi(),WA=Ae(),nv=xd(),UA=sr(),QA=Pf(),KA=Df(),JA=Ff(),YA=Of(),XA=_f(),ZA=zf(),ex=qf(),tx=jf(),rx=Je(),ix=Qf(),nx=Jf(),sx=rc(),ax=ey(),ox=ry(),cx=os(),lx=ic(),ux=Dd(),dx=Id(),mx=nc(),px=sc(),gx=Md(),hx=dy(),fx=py(),yx=cs(),vx=Ye(),bx=us(),wx=Py(),Cx=Dy(),Sx=My(),Rx=$y(),Tx=Ny(),Ex=cc(),Ax=Gy(),xx=Hy(),Px=Qy(),kx=Jy(),Dx=rv();sv.exports={parse:UA,valid:QA,clean:KA,inc:JA,diff:YA,major:XA,minor:ZA,patch:ex,prerelease:tx,compare:rx,rcompare:ix,compareLoose:nx,compareBuild:sx,sort:ax,rsort:ox,gt:cx,lt:lx,eq:ux,neq:dx,gte:mx,lte:px,cmp:gx,coerce:hx,truncate:fx,Comparator:yx,Range:vx,satisfies:bx,toComparators:wx,maxSatisfying:Cx,minSatisfying:Sx,minVersion:Rx,validRange:Tx,outside:Ex,gtr:Ax,ltr:xx,intersects:Px,simplifyRange:kx,subset:Dx,SemVer:WA,re:jd.re,src:jd.src,tokens:jd.t,SEMVER_SPEC_VERSION:iv.SEMVER_SPEC_VERSION,RELEASE_TYPES:iv.RELEASE_TYPES,compareIdentifiers:nv.compareIdentifiers,rcompareIdentifiers:nv.rcompareIdentifiers}});import{randomUUID as pb}from"crypto";$c();var el={LOOP_WARNING:"loop.warning",LOOP_DETECTED:"loop.detected"},Bs=class{subscriptions=new Map;subscriptionsByEventType=new Map;subscriptionsByChannel=new Map;wildcardSubscriptions=new Set;eventHistory;maxHistorySize=Lc.MAX_HISTORY_SIZE;subscriptionCounter=0;middlewares=[];constructor(t=Lc.MAX_HISTORY_SIZE){this.maxHistorySize=t,this.eventHistory=new Sm(t)}registerMiddleware(t){this.middlewares.push(t),this.middlewares.sort((e,r)=>e.priority-r.priority)}removeMiddleware(t){let e=this.middlewares.findIndex(r=>r.name===t);return e>=0?(this.middlewares.splice(e,1),!0):!1}getMiddlewares(){return this.middlewares}async publish(t){let e=t;for(let o of this.middlewares)if(o.onEmit&&e&&(e=await o.onEmit(e),!e))return;this.eventHistory.push(e);let r=new Set,i=this.subscriptionsByEventType.get(e.type);if(i)for(let o of i)r.add(o);let n=this.subscriptionsByChannel.get(e.source);if(n)for(let o of n)r.add(o);for(let o of this.wildcardSubscriptions)r.add(o);let s=[];for(let o of r){let l=this.subscriptions.get(o);!l||!l.active||l.channel&&l.channel!==e.source||l.eventType!=="*"&&l.eventType!==e.type||s.push(l)}let a=e;for(let o of this.middlewares)if(o.onReceive&&a&&(a=await o.onReceive(a),!a))return;await Promise.allSettled(s.map(o=>o.handler(a)))}subscribe(t,e){let r=`sub_${++this.subscriptionCounter}`,i={id:r,eventType:t,handler:e,active:!0};return this.subscriptions.set(r,i),t==="*"?this.wildcardSubscriptions.add(r):(this.subscriptionsByEventType.has(t)||this.subscriptionsByEventType.set(t,new Set),this.subscriptionsByEventType.get(t).add(r)),{unsubscribe:()=>{i.active=!1,this.subscriptions.delete(r),t==="*"?this.wildcardSubscriptions.delete(r):this.subscriptionsByEventType.get(t)?.delete(r)},get active(){return i.active}}}subscribeToChannel(t,e){let r=`sub_${++this.subscriptionCounter}`,i={id:r,eventType:"*",channel:t,handler:e,active:!0};return this.subscriptions.set(r,i),this.subscriptionsByChannel.has(t)||this.subscriptionsByChannel.set(t,new Set),this.subscriptionsByChannel.get(t).add(r),{unsubscribe:()=>{i.active=!1,this.subscriptions.delete(r),this.subscriptionsByChannel.get(t)?.delete(r)},get active(){return i.active}}}async getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(r=>t.eventTypes.includes(r.type))),t.sources?.length&&(e=e.filter(r=>t.sources.includes(r.source))),t.fromTimestamp&&(e=e.filter(r=>r.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(r=>r.timestamp<=t.toTimestamp)),t.correlationId&&(e=e.filter(r=>r.correlationId===t.correlationId)),t.limit&&(e=e.slice(-t.limit))),e}async dispose(){this.subscriptions.clear(),this.subscriptionsByEventType.clear(),this.subscriptionsByChannel.clear(),this.wildcardSubscriptions.clear(),this.eventHistory.clear(),this.middlewares=[]}};$c();var qs=class{agents=new Map;maxAgents;memoryBranch=null;constructor(t=Hi.MAX_CONCURRENT_AGENTS){this.maxAgents=t}setMemoryBranch(t){this.memoryBranch=t}async spawn(t){if(!this.canSpawn())return g(new Error(`Cannot spawn agent: maximum concurrent agents (${this.maxAgents}) reached. Active: ${this.getActiveCount()}`));let e=t.config??{};if(t.progressiveContext?.strategy==="predictive"||process.env.AQE_PROGRESSIVE_CONTEXT_ENABLED==="true")try{let s=e.taskDescription||t.name||"",a=e.availableFiles||[];if(s&&a.length>0){let l=new tl(t.progressiveContext).predictFilesForTask(s,a);e={...e,availableFiles:l,contextFiles:l,initialFiles:l,progressiveContextApplied:!0}}}catch{}let i=w(),n={id:i,name:t.name,domain:t.domain,type:t.type,status:"running",capabilities:t.capabilities,config:e,startedAt:new Date};if(this.agents.set(i,n),this.memoryBranch)try{let s=this.memoryBranch.createBranch(i);n.config={...n.config,_memoryBranchPath:s.childPath,_memoryBranchRecordIngest:a=>{this.memoryBranch?.recordIngest(i,a)}}}catch(s){console.warn(`[AgentCoordinator] Memory branch creation failed for ${i}:`,s)}return f(i)}getStatus(t){return this.agents.get(t)?.status}listAgents(t){let e=Array.from(this.agents.values());return t&&(t.domain&&(e=e.filter(r=>r.domain===t.domain)),t.status&&(e=e.filter(r=>r.status===t.status)),t.type&&(e=e.filter(r=>r.type===t.type))),e.map(r=>({id:r.id,name:r.name,domain:r.domain,type:r.type,status:r.status,startedAt:r.startedAt}))}async stop(t){let e=this.agents.get(t);return e?e.status!=="running"?g(new Error(`Agent ${t} is not running (status: ${e.status})`)):(e.status="completed",e.completedAt=new Date,f(void 0)):g(new Error(`Agent not found: ${t}`))}getActiveCount(){return Array.from(this.agents.values()).filter(t=>t.status==="running"||t.status==="queued").length}canSpawn(){return this.getActiveCount()<this.maxAgents}async dispose(){let t=Array.from(this.agents.values()).filter(e=>e.status==="running");await Promise.all(t.map(e=>this.stop(e.id))),this.agents.clear()}markCompleted(t){let e=this.agents.get(t);e&&e.status==="running"&&(e.status="completed",e.completedAt=new Date,this.handleBranchOnComplete(t,"merge"))}markFailed(t){let e=this.agents.get(t);e&&e.status==="running"&&(e.status="failed",e.completedAt=new Date,this.handleBranchOnComplete(t,"discard"))}handleBranchOnComplete(t,e){if(!this.memoryBranch)return;let r=this.memoryBranch.getBranch(t);if(r)try{e==="merge"?this.memoryBranch.mergeBranch(r).catch(i=>{console.warn(`[AgentCoordinator] Branch merge failed for ${t}:`,i)}):this.memoryBranch.discardBranch(r)}catch(i){console.warn(`[AgentCoordinator] Branch ${e} failed for ${t}:`,i)}}cleanup(t=Hi.DEFAULT_AGENT_TTL_MS){let e=Date.now(),r=0;for(let[i,n]of this.agents.entries())(n.status==="completed"||n.status==="failed")&&n.completedAt&&e-n.completedAt.getTime()>t&&(this.agents.delete(i),r++);return r}},Sb={strategy:"full",maxInitialFiles:10,predictionThreshold:.7,trackFileRequests:!0},tl=class{config;fileRequests=[];preloadedFiles=new Set;constructor(t){this.config={...Sb,...t}}isEnabled(){return process.env.AQE_PROGRESSIVE_CONTEXT_ENABLED==="true"}predictFilesForTask(t,e){if(!this.isEnabled()||this.config.strategy==="full")return[...e];if(!t||t.trim().length===0)return e.slice(0,this.config.maxInitialFiles);if(e.length===0)return[];let r=this.extractKeywords(t);if(r.length===0)return e.slice(0,this.config.maxInitialFiles);let i=e.map(s=>({filePath:s,score:this.scoreFile(s,r)}));i.sort((s,a)=>a.score-s.score);let n=i.slice(0,this.config.maxInitialFiles).map(s=>s.filePath);return this.preloadedFiles=new Set(n),n}recordFileRequest(t){this.config.trackFileRequests&&this.fileRequests.push(t)}getPredictionAccuracy(){let t=this.preloadedFiles.size,e=this.fileRequests.filter(s=>s.wasPreloaded).length,r=new Set(this.fileRequests.map(s=>s.filePath)),i=[...r].filter(s=>this.preloadedFiles.has(s)).length,n=r.size>0?i/r.size:0;return{predicted:t,actuallyUsed:e,hitRate:n}}getFileRequestHistory(t){return t?this.fileRequests.filter(e=>e.agentId===t):[...this.fileRequests]}extractKeywords(t){let e=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","to","of","in","for","on","with","at","by","from","as","into","through","during","before","after","and","but","or","nor","not","so","yet","both","either","neither","each","every","all","any","few","more","most","other","some","such","no","only","same","than","too","very","just","because","if","when","while","that","this","these","those","it","its","they","them","their","we","our","you","your","he","she","his","her","i","me","my"]),r=t.toLowerCase().split(/[\s\-_./\\,;:!?()[\]{}'"]+/).filter(i=>i.length>1&&!e.has(i));return[...new Set(r)]}scoreFile(t,e){let r=t.toLowerCase(),i=r.split(/[\\/.]/).filter(s=>s.length>0),n=0;for(let s of e)if(i.includes(s))n+=2;else if(r.includes(s))n+=1;else for(let a of i)if(a.startsWith(s)||s.startsWith(a)){n+=.5;break}return e.length>0?n/(e.length*2):0}};_();var Rb=x.create("plugin-loader"),sn=class{constructor(t,e,r=!0){this.eventBus=t;this.memory=e}eventBus;memory;plugins=new Map;factories=new Map;loading=new Map;registerFactory(t,e){this.factories.set(t,e)}async load(t){let e=this.plugins.get(t);if(e)return e;let r=this.loading.get(t);if(r)return r;let i=this.factories.get(t);if(!i){let s=Array.from(this.factories.keys());throw new Error(`No factory registered for domain: ${t}
114
+ Format your response with: verdict (confirmed/rejected/uncertain), confidence (0-100), and reasoning.`}}});var Pi=G((ZJ,ff)=>{"use strict";var E0="2.0.0",A0=Number.MAX_SAFE_INTEGER||9007199254740991,x0=16,P0=250,k0=["major","premajor","minor","preminor","patch","prepatch","prerelease"];ff.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:x0,MAX_SAFE_BUILD_LENGTH:P0,MAX_SAFE_INTEGER:A0,RELEASE_TYPES:k0,SEMVER_SPEC_VERSION:E0,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var as=G((e7,yf)=>{"use strict";var D0=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...c)=>console.error("SEMVER",...c):()=>{};yf.exports=D0});var ki=G((ht,vf)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Ed,MAX_SAFE_BUILD_LENGTH:I0,MAX_LENGTH:M0}=Pi(),F0=as();ht=vf.exports={};var L0=ht.re=[],$0=ht.safeRe=[],F=ht.src=[],O0=ht.safeSrc=[],L=ht.t={},N0=0,Ad="[a-zA-Z0-9-]",_0=[["\\s",1],["\\d",M0],[Ad,I0]],V0=c=>{for(let[t,e]of _0)c=c.split(`${t}*`).join(`${t}{0,${e}}`).split(`${t}+`).join(`${t}{1,${e}}`);return c},W=(c,t,e)=>{let r=V0(t),i=N0++;F0(c,i,t),L[c]=i,F[i]=t,O0[i]=r,L0[i]=new RegExp(t,e?"g":void 0),$0[i]=new RegExp(r,e?"g":void 0)};W("NUMERICIDENTIFIER","0|[1-9]\\d*");W("NUMERICIDENTIFIERLOOSE","\\d+");W("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Ad}*`);W("MAINVERSION",`(${F[L.NUMERICIDENTIFIER]})\\.(${F[L.NUMERICIDENTIFIER]})\\.(${F[L.NUMERICIDENTIFIER]})`);W("MAINVERSIONLOOSE",`(${F[L.NUMERICIDENTIFIERLOOSE]})\\.(${F[L.NUMERICIDENTIFIERLOOSE]})\\.(${F[L.NUMERICIDENTIFIERLOOSE]})`);W("PRERELEASEIDENTIFIER",`(?:${F[L.NONNUMERICIDENTIFIER]}|${F[L.NUMERICIDENTIFIER]})`);W("PRERELEASEIDENTIFIERLOOSE",`(?:${F[L.NONNUMERICIDENTIFIER]}|${F[L.NUMERICIDENTIFIERLOOSE]})`);W("PRERELEASE",`(?:-(${F[L.PRERELEASEIDENTIFIER]}(?:\\.${F[L.PRERELEASEIDENTIFIER]})*))`);W("PRERELEASELOOSE",`(?:-?(${F[L.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${F[L.PRERELEASEIDENTIFIERLOOSE]})*))`);W("BUILDIDENTIFIER",`${Ad}+`);W("BUILD",`(?:\\+(${F[L.BUILDIDENTIFIER]}(?:\\.${F[L.BUILDIDENTIFIER]})*))`);W("FULLPLAIN",`v?${F[L.MAINVERSION]}${F[L.PRERELEASE]}?${F[L.BUILD]}?`);W("FULL",`^${F[L.FULLPLAIN]}$`);W("LOOSEPLAIN",`[v=\\s]*${F[L.MAINVERSIONLOOSE]}${F[L.PRERELEASELOOSE]}?${F[L.BUILD]}?`);W("LOOSE",`^${F[L.LOOSEPLAIN]}$`);W("GTLT","((?:<|>)?=?)");W("XRANGEIDENTIFIERLOOSE",`${F[L.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);W("XRANGEIDENTIFIER",`${F[L.NUMERICIDENTIFIER]}|x|X|\\*`);W("XRANGEPLAIN",`[v=\\s]*(${F[L.XRANGEIDENTIFIER]})(?:\\.(${F[L.XRANGEIDENTIFIER]})(?:\\.(${F[L.XRANGEIDENTIFIER]})(?:${F[L.PRERELEASE]})?${F[L.BUILD]}?)?)?`);W("XRANGEPLAINLOOSE",`[v=\\s]*(${F[L.XRANGEIDENTIFIERLOOSE]})(?:\\.(${F[L.XRANGEIDENTIFIERLOOSE]})(?:\\.(${F[L.XRANGEIDENTIFIERLOOSE]})(?:${F[L.PRERELEASELOOSE]})?${F[L.BUILD]}?)?)?`);W("XRANGE",`^${F[L.GTLT]}\\s*${F[L.XRANGEPLAIN]}$`);W("XRANGELOOSE",`^${F[L.GTLT]}\\s*${F[L.XRANGEPLAINLOOSE]}$`);W("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Ed}})(?:\\.(\\d{1,${Ed}}))?(?:\\.(\\d{1,${Ed}}))?`);W("COERCE",`${F[L.COERCEPLAIN]}(?:$|[^\\d])`);W("COERCEFULL",F[L.COERCEPLAIN]+`(?:${F[L.PRERELEASE]})?(?:${F[L.BUILD]})?(?:$|[^\\d])`);W("COERCERTL",F[L.COERCE],!0);W("COERCERTLFULL",F[L.COERCEFULL],!0);W("LONETILDE","(?:~>?)");W("TILDETRIM",`(\\s*)${F[L.LONETILDE]}\\s+`,!0);ht.tildeTrimReplace="$1~";W("TILDE",`^${F[L.LONETILDE]}${F[L.XRANGEPLAIN]}$`);W("TILDELOOSE",`^${F[L.LONETILDE]}${F[L.XRANGEPLAINLOOSE]}$`);W("LONECARET","(?:\\^)");W("CARETTRIM",`(\\s*)${F[L.LONECARET]}\\s+`,!0);ht.caretTrimReplace="$1^";W("CARET",`^${F[L.LONECARET]}${F[L.XRANGEPLAIN]}$`);W("CARETLOOSE",`^${F[L.LONECARET]}${F[L.XRANGEPLAINLOOSE]}$`);W("COMPARATORLOOSE",`^${F[L.GTLT]}\\s*(${F[L.LOOSEPLAIN]})$|^$`);W("COMPARATOR",`^${F[L.GTLT]}\\s*(${F[L.FULLPLAIN]})$|^$`);W("COMPARATORTRIM",`(\\s*)${F[L.GTLT]}\\s*(${F[L.LOOSEPLAIN]}|${F[L.XRANGEPLAIN]})`,!0);ht.comparatorTrimReplace="$1$2$3";W("HYPHENRANGE",`^\\s*(${F[L.XRANGEPLAIN]})\\s+-\\s+(${F[L.XRANGEPLAIN]})\\s*$`);W("HYPHENRANGELOOSE",`^\\s*(${F[L.XRANGEPLAINLOOSE]})\\s+-\\s+(${F[L.XRANGEPLAINLOOSE]})\\s*$`);W("STAR","(<|>)?=?\\s*\\*");W("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");W("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Yo=G((t7,bf)=>{"use strict";var z0=Object.freeze({loose:!0}),B0=Object.freeze({}),q0=c=>c?typeof c!="object"?z0:c:B0;bf.exports=q0});var xd=G((r7,Sf)=>{"use strict";var wf=/^[0-9]+$/,Cf=(c,t)=>{if(typeof c=="number"&&typeof t=="number")return c===t?0:c<t?-1:1;let e=wf.test(c),r=wf.test(t);return e&&r&&(c=+c,t=+t),c===t?0:e&&!r?-1:r&&!e?1:c<t?-1:1},G0=(c,t)=>Cf(t,c);Sf.exports={compareIdentifiers:Cf,rcompareIdentifiers:G0}});var Ae=G((i7,Tf)=>{"use strict";var Xo=as(),{MAX_LENGTH:Rf,MAX_SAFE_INTEGER:Zo}=Pi(),{safeRe:ec,t:tc}=ki(),j0=Yo(),{compareIdentifiers:Pd}=xd(),H0=(c,t)=>{let e=t.split(".");if(e.length>c.length)return!1;for(let r=0;r<e.length;r++)if(Pd(c[r],e[r])!==0)return!1;return!0},kd=class c{constructor(t,e){if(e=j0(e),t instanceof c){if(t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>Rf)throw new TypeError(`version is longer than ${Rf} characters`);Xo("SemVer",t,e),this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease;let r=t.trim().match(e.loose?ec[tc.LOOSE]:ec[tc.FULL]);if(!r)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>Zo||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Zo||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Zo||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let n=+i;if(n>=0&&n<Zo)return n}return i}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(Xo("SemVer.compare",this.version,this.options,t),!(t instanceof c)){if(typeof t=="string"&&t===this.version)return 0;t=new c(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof c||(t=new c(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof c||(t=new c(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let e=0;do{let r=this.prerelease[e],i=t.prerelease[e];if(Xo("prerelease compare",e,r,i),r===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(r===void 0)return-1;if(r===i)continue;return Pd(r,i)}while(++e)}compareBuild(t){t instanceof c||(t=new c(t,this.options));let e=0;do{let r=this.build[e],i=t.build[e];if(Xo("build compare",e,r,i),r===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(r===void 0)return-1;if(r===i)continue;return Pd(r,i)}while(++e)}inc(t,e,r){if(t.startsWith("pre")){if(!e&&r===!1)throw new Error("invalid increment argument: identifier is empty");if(e){let i=`-${e}`.match(this.options.loose?ec[tc.PRERELEASELOOSE]:ec[tc.PRERELEASE]);if(!i||i[1]!==e)throw new Error(`invalid identifier: ${e}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",e,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",e,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",e,r),this.inc("pre",e,r);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",e,r),this.inc("pre",e,r);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let i=Number(r)?1:0;if(this.prerelease.length===0)this.prerelease=[i];else{let n=this.prerelease.length;for(;--n>=0;)typeof this.prerelease[n]=="number"&&(this.prerelease[n]++,n=-2);if(n===-1){if(e===this.prerelease.join(".")&&r===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(e){let n=[e,i];if(r===!1&&(n=[e]),H0(this.prerelease,e)){let s=this.prerelease[e.split(".").length];isNaN(s)&&(this.prerelease=n)}else this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Tf.exports=kd});var sr=G((n7,Af)=>{"use strict";var Ef=Ae(),W0=(c,t,e=!1)=>{if(c instanceof Ef)return c;try{return new Ef(c,t)}catch(r){if(!e)return null;throw r}};Af.exports=W0});var Pf=G((s7,xf)=>{"use strict";var U0=sr(),Q0=(c,t)=>{let e=U0(c,t);return e?e.version:null};xf.exports=Q0});var Df=G((a7,kf)=>{"use strict";var K0=sr(),J0=(c,t)=>{let e=K0(c.trim().replace(/^[=v]+/,""),t);return e?e.version:null};kf.exports=J0});var Ff=G((o7,Mf)=>{"use strict";var If=Ae(),Y0=(c,t,e,r,i)=>{typeof e=="string"&&(i=r,r=e,e=void 0);try{return new If(c instanceof If?c.version:c,e).inc(t,r,i).version}catch{return null}};Mf.exports=Y0});var Of=G((c7,$f)=>{"use strict";var Lf=sr(),X0=(c,t)=>{let e=Lf(c,null,!0),r=Lf(t,null,!0),i=e.compare(r);if(i===0)return null;let n=i>0,s=n?e:r,a=n?r:e,o=!!s.prerelease.length;if(!!a.prerelease.length&&!o){if(!a.patch&&!a.minor)return"major";if(a.compareMain(s)===0)return a.minor&&!a.patch?"minor":"patch"}let u=o?"pre":"";return e.major!==r.major?u+"major":e.minor!==r.minor?u+"minor":e.patch!==r.patch?u+"patch":"prerelease"};$f.exports=X0});var _f=G((l7,Nf)=>{"use strict";var Z0=Ae(),eE=(c,t)=>new Z0(c,t).major;Nf.exports=eE});var zf=G((u7,Vf)=>{"use strict";var tE=Ae(),rE=(c,t)=>new tE(c,t).minor;Vf.exports=rE});var qf=G((d7,Bf)=>{"use strict";var iE=Ae(),nE=(c,t)=>new iE(c,t).patch;Bf.exports=nE});var jf=G((m7,Gf)=>{"use strict";var sE=sr(),aE=(c,t)=>{let e=sE(c,t);return e&&e.prerelease.length?e.prerelease:null};Gf.exports=aE});var Je=G((p7,Wf)=>{"use strict";var Hf=Ae(),oE=(c,t,e)=>new Hf(c,e).compare(new Hf(t,e));Wf.exports=oE});var Qf=G((g7,Uf)=>{"use strict";var cE=Je(),lE=(c,t,e)=>cE(t,c,e);Uf.exports=lE});var Jf=G((h7,Kf)=>{"use strict";var uE=Je(),dE=(c,t)=>uE(c,t,!0);Kf.exports=dE});var rc=G((f7,Xf)=>{"use strict";var Yf=Ae(),mE=(c,t,e)=>{let r=new Yf(c,e),i=new Yf(t,e);return r.compare(i)||r.compareBuild(i)};Xf.exports=mE});var ey=G((y7,Zf)=>{"use strict";var pE=rc(),gE=(c,t)=>c.sort((e,r)=>pE(e,r,t));Zf.exports=gE});var ry=G((v7,ty)=>{"use strict";var hE=rc(),fE=(c,t)=>c.sort((e,r)=>hE(r,e,t));ty.exports=fE});var os=G((b7,iy)=>{"use strict";var yE=Je(),vE=(c,t,e)=>yE(c,t,e)>0;iy.exports=vE});var ic=G((w7,ny)=>{"use strict";var bE=Je(),wE=(c,t,e)=>bE(c,t,e)<0;ny.exports=wE});var Dd=G((C7,sy)=>{"use strict";var CE=Je(),SE=(c,t,e)=>CE(c,t,e)===0;sy.exports=SE});var Id=G((S7,ay)=>{"use strict";var RE=Je(),TE=(c,t,e)=>RE(c,t,e)!==0;ay.exports=TE});var nc=G((R7,oy)=>{"use strict";var EE=Je(),AE=(c,t,e)=>EE(c,t,e)>=0;oy.exports=AE});var sc=G((T7,cy)=>{"use strict";var xE=Je(),PE=(c,t,e)=>xE(c,t,e)<=0;cy.exports=PE});var Md=G((E7,ly)=>{"use strict";var kE=Dd(),DE=Id(),IE=os(),ME=nc(),FE=ic(),LE=sc(),$E=(c,t,e,r)=>{switch(t){case"===":return typeof c=="object"&&(c=c.version),typeof e=="object"&&(e=e.version),c===e;case"!==":return typeof c=="object"&&(c=c.version),typeof e=="object"&&(e=e.version),c!==e;case"":case"=":case"==":return kE(c,e,r);case"!=":return DE(c,e,r);case">":return IE(c,e,r);case">=":return ME(c,e,r);case"<":return FE(c,e,r);case"<=":return LE(c,e,r);default:throw new TypeError(`Invalid operator: ${t}`)}};ly.exports=$E});var dy=G((A7,uy)=>{"use strict";var OE=Ae(),NE=sr(),{safeRe:ac,t:oc}=ki(),_E=(c,t)=>{if(c instanceof OE)return c;if(typeof c=="number"&&(c=String(c)),typeof c!="string")return null;t=t||{};let e=null;if(!t.rtl)e=c.match(t.includePrerelease?ac[oc.COERCEFULL]:ac[oc.COERCE]);else{let o=t.includePrerelease?ac[oc.COERCERTLFULL]:ac[oc.COERCERTL],l;for(;(l=o.exec(c))&&(!e||e.index+e[0].length!==c.length);)(!e||l.index+l[0].length!==e.index+e[0].length)&&(e=l),o.lastIndex=l.index+l[1].length+l[2].length;o.lastIndex=-1}if(e===null)return null;let r=e[2],i=e[3]||"0",n=e[4]||"0",s=t.includePrerelease&&e[5]?`-${e[5]}`:"",a=t.includePrerelease&&e[6]?`+${e[6]}`:"";return NE(`${r}.${i}.${n}${s}${a}`,t)};uy.exports=_E});var py=G((x7,my)=>{"use strict";var VE=sr(),zE=Pi(),BE=Ae(),qE=(c,t,e)=>{if(!zE.RELEASE_TYPES.includes(t))return null;let r=GE(c,e);return r&&jE(r,t)},GE=(c,t)=>{let e=c instanceof BE?c.version:c;return VE(e,t)},jE=(c,t)=>{if(HE(t))return c.version;switch(c.prerelease=[],t){case"major":c.minor=0,c.patch=0;break;case"minor":c.patch=0;break}return c.format()},HE=c=>c.startsWith("pre");my.exports=qE});var hy=G((P7,gy)=>{"use strict";var Fd=class{constructor(){this.max=1e3,this.map=new Map}get(t){let e=this.map.get(t);if(e!==void 0)return this.map.delete(t),this.map.set(t,e),e}delete(t){return this.map.delete(t)}set(t,e){if(!this.delete(t)&&e!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(t,e)}return this}};gy.exports=Fd});var Ye=G((k7,by)=>{"use strict";var WE=/\s+/g,Ld=class c{constructor(t,e){if(e=QE(e),t instanceof c)return t.loose===!!e.loose&&t.includePrerelease===!!e.includePrerelease?t:new c(t.raw,e);if(t instanceof $d)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=e,this.loose=!!e.loose,this.includePrerelease=!!e.includePrerelease,this.raw=t.trim().replace(WE," "),this.set=this.raw.split("||").map(r=>this.parseRange(r.trim())).filter(r=>r.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let r=this.set[0];if(this.set=this.set.filter(i=>!yy(i[0])),this.set.length===0)this.set=[r];else if(this.set.length>1){for(let i of this.set)if(i.length===1&&iA(i[0])){this.set=[i];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t<this.set.length;t++){t>0&&(this.formatted+="||");let e=this.set[t];for(let r=0;r<e.length;r++)r>0&&(this.formatted+=" "),this.formatted+=e[r].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){t=t.replace(rA,"");let r=((this.options.includePrerelease&&eA)|(this.options.loose&&tA))+":"+t,i=fy.get(r);if(i)return i;let n=this.options.loose,s=n?$e[xe.HYPHENRANGELOOSE]:$e[xe.HYPHENRANGE];t=t.replace(s,gA(this.options.includePrerelease)),oe("hyphen replace",t),t=t.replace($e[xe.COMPARATORTRIM],YE),oe("comparator trim",t),t=t.replace($e[xe.TILDETRIM],XE),oe("tilde trim",t),t=t.replace($e[xe.CARETTRIM],ZE),oe("caret trim",t);let a=t.split(" ").map(d=>nA(d,this.options)).join(" ").split(/\s+/).map(d=>pA(d,this.options));n&&(a=a.filter(d=>(oe("loose invalid filter",d,this.options),!!d.match($e[xe.COMPARATORLOOSE])))),oe("range list",a);let o=new Map,l=a.map(d=>new $d(d,this.options));for(let d of l){if(yy(d))return[d];o.set(d.value,d)}o.size>1&&o.has("")&&o.delete("");let u=[...o.values()];return fy.set(r,u),u}intersects(t,e){if(!(t instanceof c))throw new TypeError("a Range is required");return this.set.some(r=>vy(r,e)&&t.set.some(i=>vy(i,e)&&r.every(n=>i.every(s=>n.intersects(s,e)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new KE(t,this.options)}catch{return!1}for(let e=0;e<this.set.length;e++)if(hA(this.set[e],t,this.options))return!0;return!1}};by.exports=Ld;var UE=hy(),fy=new UE,QE=Yo(),$d=cs(),oe=as(),KE=Ae(),{safeRe:$e,src:JE,t:xe,comparatorTrimReplace:YE,tildeTrimReplace:XE,caretTrimReplace:ZE}=ki(),{FLAG_INCLUDE_PRERELEASE:eA,FLAG_LOOSE:tA}=Pi(),rA=new RegExp(JE[xe.BUILD],"g"),yy=c=>c.value==="<0.0.0-0",iA=c=>c.value==="",vy=(c,t)=>{let e=!0,r=c.slice(),i=r.pop();for(;e&&r.length;)e=r.every(n=>i.intersects(n,t)),i=r.pop();return e},nA=(c,t)=>(c=c.replace($e[xe.BUILD],""),oe("comp",c,t),c=cA(c,t),oe("caret",c),c=aA(c,t),oe("tildes",c),c=uA(c,t),oe("xrange",c),c=mA(c,t),oe("stars",c),c),ye=c=>!c||c.toLowerCase()==="x"||c==="*",sA=(c,t,e)=>ye(c)&&!ye(t)||ye(t)&&e&&!ye(e),aA=(c,t)=>c.trim().split(/\s+/).map(e=>oA(e,t)).join(" "),oA=(c,t)=>{let e=t.loose?$e[xe.TILDELOOSE]:$e[xe.TILDE],r=t.includePrerelease?"-0":"";return c.replace(e,(i,n,s,a,o)=>{oe("tilde",c,i,n,s,a,o);let l;return ye(n)?l="":ye(s)?l=`>=${n}.0.0${r} <${+n+1}.0.0-0`:ye(a)?l=`>=${n}.${s}.0${r} <${n}.${+s+1}.0-0`:o?(oe("replaceTilde pr",o),l=`>=${n}.${s}.${a}-${o} <${n}.${+s+1}.0-0`):l=`>=${n}.${s}.${a} <${n}.${+s+1}.0-0`,oe("tilde return",l),l})},cA=(c,t)=>c.trim().split(/\s+/).map(e=>lA(e,t)).join(" "),lA=(c,t)=>{oe("caret",c,t);let e=t.loose?$e[xe.CARETLOOSE]:$e[xe.CARET],r=t.includePrerelease?"-0":"";return c.replace(e,(i,n,s,a,o)=>{oe("caret",c,i,n,s,a,o);let l;return ye(n)?l="":ye(s)?l=`>=${n}.0.0${r} <${+n+1}.0.0-0`:ye(a)?n==="0"?l=`>=${n}.${s}.0${r} <${n}.${+s+1}.0-0`:l=`>=${n}.${s}.0${r} <${+n+1}.0.0-0`:o?(oe("replaceCaret pr",o),n==="0"?s==="0"?l=`>=${n}.${s}.${a}-${o} <${n}.${s}.${+a+1}-0`:l=`>=${n}.${s}.${a}-${o} <${n}.${+s+1}.0-0`:l=`>=${n}.${s}.${a}-${o} <${+n+1}.0.0-0`):(oe("no pr"),n==="0"?s==="0"?l=`>=${n}.${s}.${a} <${n}.${s}.${+a+1}-0`:l=`>=${n}.${s}.${a} <${n}.${+s+1}.0-0`:l=`>=${n}.${s}.${a} <${+n+1}.0.0-0`),oe("caret return",l),l})},uA=(c,t)=>(oe("replaceXRanges",c,t),c.split(/\s+/).map(e=>dA(e,t)).join(" ")),dA=(c,t)=>{c=c.trim();let e=t.loose?$e[xe.XRANGELOOSE]:$e[xe.XRANGE];return c.replace(e,(r,i,n,s,a,o)=>{if(oe("xRange",c,r,i,n,s,a,o),sA(n,s,a))return c;let l=ye(n),u=l||ye(s),d=u||ye(a),m=d;return i==="="&&m&&(i=""),o=t.includePrerelease?"-0":"",l?i===">"||i==="<"?r="<0.0.0-0":r="*":i&&m?(u&&(s=0),a=0,i===">"?(i=">=",u?(n=+n+1,s=0,a=0):(s=+s+1,a=0)):i==="<="&&(i="<",u?n=+n+1:s=+s+1),i==="<"&&(o="-0"),r=`${i+n}.${s}.${a}${o}`):u?r=`>=${n}.0.0${o} <${+n+1}.0.0-0`:d&&(r=`>=${n}.${s}.0${o} <${n}.${+s+1}.0-0`),oe("xRange return",r),r})},mA=(c,t)=>(oe("replaceStars",c,t),c.trim().replace($e[xe.STAR],"")),pA=(c,t)=>(oe("replaceGTE0",c,t),c.trim().replace($e[t.includePrerelease?xe.GTE0PRE:xe.GTE0],"")),gA=c=>(t,e,r,i,n,s,a,o,l,u,d,m)=>(ye(r)?e="":ye(i)?e=`>=${r}.0.0${c?"-0":""}`:ye(n)?e=`>=${r}.${i}.0${c?"-0":""}`:s?e=`>=${e}`:e=`>=${e}${c?"-0":""}`,ye(l)?o="":ye(u)?o=`<${+l+1}.0.0-0`:ye(d)?o=`<${l}.${+u+1}.0-0`:m?o=`<=${l}.${u}.${d}-${m}`:c?o=`<${l}.${u}.${+d+1}-0`:o=`<=${o}`,`${e} ${o}`.trim()),hA=(c,t,e)=>{for(let r=0;r<c.length;r++)if(!c[r].test(t))return!1;if(t.prerelease.length&&!e.includePrerelease){for(let r=0;r<c.length;r++)if(oe(c[r].semver),c[r].semver!==$d.ANY&&c[r].semver.prerelease.length>0){let i=c[r].semver;if(i.major===t.major&&i.minor===t.minor&&i.patch===t.patch)return!0}return!1}return!0}});var cs=G((D7,Ey)=>{"use strict";var ls=Symbol("SemVer ANY"),_d=class c{static get ANY(){return ls}constructor(t,e){if(e=wy(e),t instanceof c){if(t.loose===!!e.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Nd("comparator",t,e),this.options=e,this.loose=!!e.loose,this.parse(t),this.semver===ls?this.value="":this.value=this.operator+this.semver.version,Nd("comp",this)}parse(t){let e=this.options.loose?Cy[Sy.COMPARATORLOOSE]:Cy[Sy.COMPARATOR],r=t.match(e);if(!r)throw new TypeError(`Invalid comparator: ${t}`);this.operator=r[1]!==void 0?r[1]:"",this.operator==="="&&(this.operator=""),r[2]?this.semver=new Ry(r[2],this.options.loose):this.semver=ls}toString(){return this.value}test(t){if(Nd("Comparator.test",t,this.options.loose),this.semver===ls||t===ls)return!0;if(typeof t=="string")try{t=new Ry(t,this.options)}catch{return!1}return Od(t,this.operator,this.semver,this.options)}intersects(t,e){if(!(t instanceof c))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Ty(t.value,e).test(this.value):t.operator===""?t.value===""?!0:new Ty(this.value,e).test(t.semver):(e=wy(e),e.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!e.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||Od(this.semver,"<",t.semver,e)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||Od(this.semver,">",t.semver,e)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};Ey.exports=_d;var wy=Yo(),{safeRe:Cy,t:Sy}=ki(),Od=Md(),Nd=as(),Ry=Ae(),Ty=Ye()});var us=G((I7,Ay)=>{"use strict";var fA=Ye(),yA=(c,t,e)=>{try{t=new fA(t,e)}catch{return!1}return t.test(c)};Ay.exports=yA});var Py=G((M7,xy)=>{"use strict";var vA=Ye(),bA=(c,t)=>new vA(c,t).set.map(e=>e.map(r=>r.value).join(" ").trim().split(" "));xy.exports=bA});var Dy=G((F7,ky)=>{"use strict";var wA=Ae(),CA=Ye(),SA=(c,t,e)=>{let r=null,i=null,n=null;try{n=new CA(t,e)}catch{return null}return c.forEach(s=>{n.test(s)&&(!r||i.compare(s)===-1)&&(r=s,i=new wA(r,e))}),r};ky.exports=SA});var My=G((L7,Iy)=>{"use strict";var RA=Ae(),TA=Ye(),EA=(c,t,e)=>{let r=null,i=null,n=null;try{n=new TA(t,e)}catch{return null}return c.forEach(s=>{n.test(s)&&(!r||i.compare(s)===1)&&(r=s,i=new RA(r,e))}),r};Iy.exports=EA});var $y=G(($7,Ly)=>{"use strict";var Vd=Ae(),AA=Ye(),Fy=os(),xA=(c,t)=>{c=new AA(c,t);let e=new Vd("0.0.0");if(c.test(e)||(e=new Vd("0.0.0-0"),c.test(e)))return e;e=null;for(let r=0;r<c.set.length;++r){let i=c.set[r],n=null;i.forEach(s=>{let a=new Vd(s.semver.version);switch(s.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!n||Fy(a,n))&&(n=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${s.operator}`)}}),n&&(!e||Fy(e,n))&&(e=n)}return e&&c.test(e)?e:null};Ly.exports=xA});var Ny=G((O7,Oy)=>{"use strict";var PA=Ye(),kA=(c,t)=>{try{return new PA(c,t).range||"*"}catch{return null}};Oy.exports=kA});var cc=G((N7,By)=>{"use strict";var DA=Ae(),zy=cs(),{ANY:IA}=zy,MA=Ye(),FA=us(),_y=os(),Vy=ic(),LA=sc(),$A=nc(),OA=(c,t,e,r)=>{c=new DA(c,r),t=new MA(t,r);let i,n,s,a,o;switch(e){case">":i=_y,n=LA,s=Vy,a=">",o=">=";break;case"<":i=Vy,n=$A,s=_y,a="<",o="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(FA(c,t,r))return!1;for(let l=0;l<t.set.length;++l){let u=t.set[l],d=null,m=null;if(u.forEach(p=>{p.semver===IA&&(p=new zy(">=0.0.0")),d=d||p,m=m||p,i(p.semver,d.semver,r)?d=p:s(p.semver,m.semver,r)&&(m=p)}),d.operator===a||d.operator===o||(!m.operator||m.operator===a)&&n(c,m.semver))return!1;if(m.operator===o&&s(c,m.semver))return!1}return!0};By.exports=OA});var Gy=G((_7,qy)=>{"use strict";var NA=cc(),_A=(c,t,e)=>NA(c,t,">",e);qy.exports=_A});var Hy=G((V7,jy)=>{"use strict";var VA=cc(),zA=(c,t,e)=>VA(c,t,"<",e);jy.exports=zA});var Qy=G((z7,Uy)=>{"use strict";var Wy=Ye(),BA=(c,t,e)=>(c=new Wy(c,e),t=new Wy(t,e),c.intersects(t,e));Uy.exports=BA});var Jy=G((B7,Ky)=>{"use strict";var qA=us(),GA=Je();Ky.exports=(c,t,e)=>{let r=[],i=null,n=null,s=c.sort((u,d)=>GA(u,d,e));for(let u of s)qA(u,t,e)?(n=u,i||(i=u)):(n&&r.push([i,n]),n=null,i=null);i&&r.push([i,null]);let a=[];for(let[u,d]of r)u===d?a.push(u):!d&&u===s[0]?a.push("*"):d?u===s[0]?a.push(`<=${d}`):a.push(`${u} - ${d}`):a.push(`>=${u}`);let o=a.join(" || "),l=typeof t.raw=="string"?t.raw:String(t);return o.length<l.length?o:t}});var rv=G((q7,tv)=>{"use strict";var Yy=Ye(),qd=cs(),{ANY:zd}=qd,Bd=us(),Gd=Je(),jA=(c,t,e={})=>{if(c===t)return!0;c=new Yy(c,e),t=new Yy(t,e);let r=!1;e:for(let i of c.set){for(let n of t.set){let s=WA(i,n,e);if(r=r||s!==null,s)continue e}if(r)return!1}return!0},HA=[new qd(">=0.0.0-0")],Xy=[new qd(">=0.0.0")],WA=(c,t,e)=>{if(c===t)return!0;if(c.length===1&&c[0].semver===zd){if(t.length===1&&t[0].semver===zd)return!0;e.includePrerelease?c=HA:c=Xy}if(t.length===1&&t[0].semver===zd){if(e.includePrerelease)return!0;t=Xy}let r=new Set,i,n;for(let p of c)p.operator===">"||p.operator===">="?i=Zy(i,p,e):p.operator==="<"||p.operator==="<="?n=ev(n,p,e):r.add(p.semver);if(r.size>1)return null;let s;if(i&&n){if(s=Gd(i.semver,n.semver,e),s>0)return null;if(s===0&&(i.operator!==">="||n.operator!=="<="))return null}for(let p of r){if(i&&!Bd(p,String(i),e)||n&&!Bd(p,String(n),e))return null;for(let h of t)if(!Bd(p,String(h),e))return!1;return!0}let a,o,l,u,d=n&&!e.includePrerelease&&n.semver.prerelease.length?n.semver:!1,m=i&&!e.includePrerelease&&i.semver.prerelease.length?i.semver:!1;d&&d.prerelease.length===1&&n.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let p of t){if(u=u||p.operator===">"||p.operator===">=",l=l||p.operator==="<"||p.operator==="<=",i){if(m&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===m.major&&p.semver.minor===m.minor&&p.semver.patch===m.patch&&(m=!1),p.operator===">"||p.operator===">="){if(a=Zy(i,p,e),a===p&&a!==i)return!1}else if(i.operator===">="&&!p.test(i.semver))return!1}if(n){if(d&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===d.major&&p.semver.minor===d.minor&&p.semver.patch===d.patch&&(d=!1),p.operator==="<"||p.operator==="<="){if(o=ev(n,p,e),o===p&&o!==n)return!1}else if(n.operator==="<="&&!p.test(n.semver))return!1}if(!p.operator&&(n||i)&&s!==0)return!1}return!(i&&l&&!n&&s!==0||n&&u&&!i&&s!==0||m||d)},Zy=(c,t,e)=>{if(!c)return t;let r=Gd(c.semver,t.semver,e);return r>0?c:r<0||t.operator===">"&&c.operator===">="?t:c},ev=(c,t,e)=>{if(!c)return t;let r=Gd(c.semver,t.semver,e);return r<0?c:r>0||t.operator==="<"&&c.operator==="<="?t:c};tv.exports=jA});var av=G((G7,sv)=>{"use strict";var jd=ki(),iv=Pi(),UA=Ae(),nv=xd(),QA=sr(),KA=Pf(),JA=Df(),YA=Ff(),XA=Of(),ZA=_f(),ex=zf(),tx=qf(),rx=jf(),ix=Je(),nx=Qf(),sx=Jf(),ax=rc(),ox=ey(),cx=ry(),lx=os(),ux=ic(),dx=Dd(),mx=Id(),px=nc(),gx=sc(),hx=Md(),fx=dy(),yx=py(),vx=cs(),bx=Ye(),wx=us(),Cx=Py(),Sx=Dy(),Rx=My(),Tx=$y(),Ex=Ny(),Ax=cc(),xx=Gy(),Px=Hy(),kx=Qy(),Dx=Jy(),Ix=rv();sv.exports={parse:QA,valid:KA,clean:JA,inc:YA,diff:XA,major:ZA,minor:ex,patch:tx,prerelease:rx,compare:ix,rcompare:nx,compareLoose:sx,compareBuild:ax,sort:ox,rsort:cx,gt:lx,lt:ux,eq:dx,neq:mx,gte:px,lte:gx,cmp:hx,coerce:fx,truncate:yx,Comparator:vx,Range:bx,satisfies:wx,toComparators:Cx,maxSatisfying:Sx,minSatisfying:Rx,minVersion:Tx,validRange:Ex,outside:Ax,gtr:xx,ltr:Px,intersects:kx,simplifyRange:Dx,subset:Ix,SemVer:UA,re:jd.re,src:jd.src,tokens:jd.t,SEMVER_SPEC_VERSION:iv.SEMVER_SPEC_VERSION,RELEASE_TYPES:iv.RELEASE_TYPES,compareIdentifiers:nv.compareIdentifiers,rcompareIdentifiers:nv.rcompareIdentifiers}});import{randomUUID as pb}from"crypto";$c();var el={LOOP_WARNING:"loop.warning",LOOP_DETECTED:"loop.detected"},Bs=class{subscriptions=new Map;subscriptionsByEventType=new Map;subscriptionsByChannel=new Map;wildcardSubscriptions=new Set;eventHistory;maxHistorySize=Lc.MAX_HISTORY_SIZE;subscriptionCounter=0;middlewares=[];constructor(t=Lc.MAX_HISTORY_SIZE){this.maxHistorySize=t,this.eventHistory=new Sm(t)}registerMiddleware(t){this.middlewares.push(t),this.middlewares.sort((e,r)=>e.priority-r.priority)}removeMiddleware(t){let e=this.middlewares.findIndex(r=>r.name===t);return e>=0?(this.middlewares.splice(e,1),!0):!1}getMiddlewares(){return this.middlewares}async publish(t){let e=t;for(let o of this.middlewares)if(o.onEmit&&e&&(e=await o.onEmit(e),!e))return;this.eventHistory.push(e);let r=new Set,i=this.subscriptionsByEventType.get(e.type);if(i)for(let o of i)r.add(o);let n=this.subscriptionsByChannel.get(e.source);if(n)for(let o of n)r.add(o);for(let o of this.wildcardSubscriptions)r.add(o);let s=[];for(let o of r){let l=this.subscriptions.get(o);!l||!l.active||l.channel&&l.channel!==e.source||l.eventType!=="*"&&l.eventType!==e.type||s.push(l)}let a=e;for(let o of this.middlewares)if(o.onReceive&&a&&(a=await o.onReceive(a),!a))return;await Promise.allSettled(s.map(o=>o.handler(a)))}subscribe(t,e){let r=`sub_${++this.subscriptionCounter}`,i={id:r,eventType:t,handler:e,active:!0};return this.subscriptions.set(r,i),t==="*"?this.wildcardSubscriptions.add(r):(this.subscriptionsByEventType.has(t)||this.subscriptionsByEventType.set(t,new Set),this.subscriptionsByEventType.get(t).add(r)),{unsubscribe:()=>{i.active=!1,this.subscriptions.delete(r),t==="*"?this.wildcardSubscriptions.delete(r):this.subscriptionsByEventType.get(t)?.delete(r)},get active(){return i.active}}}subscribeToChannel(t,e){let r=`sub_${++this.subscriptionCounter}`,i={id:r,eventType:"*",channel:t,handler:e,active:!0};return this.subscriptions.set(r,i),this.subscriptionsByChannel.has(t)||this.subscriptionsByChannel.set(t,new Set),this.subscriptionsByChannel.get(t).add(r),{unsubscribe:()=>{i.active=!1,this.subscriptions.delete(r),this.subscriptionsByChannel.get(t)?.delete(r)},get active(){return i.active}}}async getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(r=>t.eventTypes.includes(r.type))),t.sources?.length&&(e=e.filter(r=>t.sources.includes(r.source))),t.fromTimestamp&&(e=e.filter(r=>r.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(r=>r.timestamp<=t.toTimestamp)),t.correlationId&&(e=e.filter(r=>r.correlationId===t.correlationId)),t.limit&&(e=e.slice(-t.limit))),e}async dispose(){this.subscriptions.clear(),this.subscriptionsByEventType.clear(),this.subscriptionsByChannel.clear(),this.wildcardSubscriptions.clear(),this.eventHistory.clear(),this.middlewares=[]}};$c();var qs=class{agents=new Map;maxAgents;memoryBranch=null;constructor(t=Hi.MAX_CONCURRENT_AGENTS){this.maxAgents=t}setMemoryBranch(t){this.memoryBranch=t}async spawn(t){if(!this.canSpawn())return g(new Error(`Cannot spawn agent: maximum concurrent agents (${this.maxAgents}) reached. Active: ${this.getActiveCount()}`));let e=t.config??{};if(t.progressiveContext?.strategy==="predictive"||process.env.AQE_PROGRESSIVE_CONTEXT_ENABLED==="true")try{let s=e.taskDescription||t.name||"",a=e.availableFiles||[];if(s&&a.length>0){let l=new tl(t.progressiveContext).predictFilesForTask(s,a);e={...e,availableFiles:l,contextFiles:l,initialFiles:l,progressiveContextApplied:!0}}}catch{}let i=w(),n={id:i,name:t.name,domain:t.domain,type:t.type,status:"running",capabilities:t.capabilities,config:e,startedAt:new Date};if(this.agents.set(i,n),this.memoryBranch)try{let s=this.memoryBranch.createBranch(i);n.config={...n.config,_memoryBranchPath:s.childPath,_memoryBranchRecordIngest:a=>{this.memoryBranch?.recordIngest(i,a)}}}catch(s){console.warn(`[AgentCoordinator] Memory branch creation failed for ${i}:`,s)}return f(i)}getStatus(t){return this.agents.get(t)?.status}listAgents(t){let e=Array.from(this.agents.values());return t&&(t.domain&&(e=e.filter(r=>r.domain===t.domain)),t.status&&(e=e.filter(r=>r.status===t.status)),t.type&&(e=e.filter(r=>r.type===t.type))),e.map(r=>({id:r.id,name:r.name,domain:r.domain,type:r.type,status:r.status,startedAt:r.startedAt}))}async stop(t){let e=this.agents.get(t);return e?e.status!=="running"?g(new Error(`Agent ${t} is not running (status: ${e.status})`)):(e.status="completed",e.completedAt=new Date,f(void 0)):g(new Error(`Agent not found: ${t}`))}getActiveCount(){return Array.from(this.agents.values()).filter(t=>t.status==="running"||t.status==="queued").length}canSpawn(){return this.getActiveCount()<this.maxAgents}async dispose(){let t=Array.from(this.agents.values()).filter(e=>e.status==="running");await Promise.all(t.map(e=>this.stop(e.id))),this.agents.clear()}markCompleted(t){let e=this.agents.get(t);e&&e.status==="running"&&(e.status="completed",e.completedAt=new Date,this.handleBranchOnComplete(t,"merge"))}markFailed(t){let e=this.agents.get(t);e&&e.status==="running"&&(e.status="failed",e.completedAt=new Date,this.handleBranchOnComplete(t,"discard"))}handleBranchOnComplete(t,e){if(!this.memoryBranch)return;let r=this.memoryBranch.getBranch(t);if(r)try{e==="merge"?this.memoryBranch.mergeBranch(r).catch(i=>{console.warn(`[AgentCoordinator] Branch merge failed for ${t}:`,i)}):this.memoryBranch.discardBranch(r)}catch(i){console.warn(`[AgentCoordinator] Branch ${e} failed for ${t}:`,i)}}cleanup(t=Hi.DEFAULT_AGENT_TTL_MS){let e=Date.now(),r=0;for(let[i,n]of this.agents.entries())(n.status==="completed"||n.status==="failed")&&n.completedAt&&e-n.completedAt.getTime()>t&&(this.agents.delete(i),r++);return r}},Sb={strategy:"full",maxInitialFiles:10,predictionThreshold:.7,trackFileRequests:!0},tl=class{config;fileRequests=[];preloadedFiles=new Set;constructor(t){this.config={...Sb,...t}}isEnabled(){return process.env.AQE_PROGRESSIVE_CONTEXT_ENABLED==="true"}predictFilesForTask(t,e){if(!this.isEnabled()||this.config.strategy==="full")return[...e];if(!t||t.trim().length===0)return e.slice(0,this.config.maxInitialFiles);if(e.length===0)return[];let r=this.extractKeywords(t);if(r.length===0)return e.slice(0,this.config.maxInitialFiles);let i=e.map(s=>({filePath:s,score:this.scoreFile(s,r)}));i.sort((s,a)=>a.score-s.score);let n=i.slice(0,this.config.maxInitialFiles).map(s=>s.filePath);return this.preloadedFiles=new Set(n),n}recordFileRequest(t){this.config.trackFileRequests&&this.fileRequests.push(t)}getPredictionAccuracy(){let t=this.preloadedFiles.size,e=this.fileRequests.filter(s=>s.wasPreloaded).length,r=new Set(this.fileRequests.map(s=>s.filePath)),i=[...r].filter(s=>this.preloadedFiles.has(s)).length,n=r.size>0?i/r.size:0;return{predicted:t,actuallyUsed:e,hitRate:n}}getFileRequestHistory(t){return t?this.fileRequests.filter(e=>e.agentId===t):[...this.fileRequests]}extractKeywords(t){let e=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","to","of","in","for","on","with","at","by","from","as","into","through","during","before","after","and","but","or","nor","not","so","yet","both","either","neither","each","every","all","any","few","more","most","other","some","such","no","only","same","than","too","very","just","because","if","when","while","that","this","these","those","it","its","they","them","their","we","our","you","your","he","she","his","her","i","me","my"]),r=t.toLowerCase().split(/[\s\-_./\\,;:!?()[\]{}'"]+/).filter(i=>i.length>1&&!e.has(i));return[...new Set(r)]}scoreFile(t,e){let r=t.toLowerCase(),i=r.split(/[\\/.]/).filter(s=>s.length>0),n=0;for(let s of e)if(i.includes(s))n+=2;else if(r.includes(s))n+=1;else for(let a of i)if(a.startsWith(s)||s.startsWith(a)){n+=.5;break}return e.length>0?n/(e.length*2):0}};_();var Rb=x.create("plugin-loader"),sn=class{constructor(t,e,r=!0){this.eventBus=t;this.memory=e}eventBus;memory;plugins=new Map;factories=new Map;loading=new Map;registerFactory(t,e){this.factories.set(t,e)}async load(t){let e=this.plugins.get(t);if(e)return e;let r=this.loading.get(t);if(r)return r;let i=this.factories.get(t);if(!i){let s=Array.from(this.factories.keys());throw new Error(`No factory registered for domain: ${t}
115
115
  This usually means the domain is not enabled in your config.
116
116
  Registered domains: ${s.join(", ")}
117
- Fix: Add '${t}' to domains.enabled in .agentic-qe/config.yaml, or run 'aqe init --auto-migrate' to enable all domains.`)}let n=this.loadPlugin(t,i);this.loading.set(t,n);try{let s=await n;return this.plugins.set(t,s),s}finally{this.loading.delete(t)}}async loadPlugin(t,e){let r=await e(this.eventBus,this.memory);for(let i of r.dependencies)this.isLoaded(i)||await this.load(i);return await r.initialize(),r}async unload(t){let e=this.plugins.get(t);if(e){for(let[r,i]of this.plugins.entries())if(i.dependencies.includes(t))throw new Error(`Cannot unload ${t}: domain ${r} depends on it`);await e.dispose(),this.plugins.delete(t)}}isLoaded(t){return this.plugins.has(t)}getLoaded(){return Array.from(this.plugins.keys())}async loadAll(){let t=Array.from(this.factories.keys()),e=this.topologicalSort(t);for(let r of e)await this.load(r)}topologicalSort(t){let e=[],r=new Set,i=new Set,n=s=>{if(r.has(s))return;if(i.has(s))throw new Error(`Circular dependency detected involving: ${s}`);i.add(s);let o=this.plugins.get(s)?.dependencies??[];for(let l of o)t.includes(l)&&n(l);i.delete(s),r.add(s),e.push(s)};for(let s of t)n(s);return e}getPlugin(t){return this.plugins.get(t)}async disposeAll(){let t=[...this.getLoaded()].reverse();for(let e of t)try{await this.unload(e)}catch(r){Rb.debug("Plugin unload failed, force removing",{domain:e,error:r instanceof Error?r.message:String(r)}),this.plugins.delete(e)}}};Fc();bs();_();var an=x.create("anti-drift-middleware"),Tb={maxIdenticalCalls:3,windowMs:3e4,steeringMessage:"Loop detected: the same tool call has been repeated multiple times. Consider an alternative approach or different parameters.",enableFleetLearning:!1};function Xm(c){let t=2166136261;for(let e=0;e<c.length;e++)t^=c.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}var Gs=class{config;callHistory=new Map;totalCallsTracked=0;loopsDetected=0;constructor(t){this.config={...Tb,...t}}trackCall(t,e,r){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return{isLoop:!1,callCount:1,signature:this.createSignature(e,r),action:"allow"};let i=this.createSignature(e,r);this.totalCallsTracked++,this.callHistory.has(t)||this.callHistory.set(t,[]);let n=this.callHistory.get(t);n.push(i);let s=Date.now()-this.config.windowMs,a=n.findIndex(l=>l.timestamp>=s);a>0?n.splice(0,a):a===-1&&(n.length=0,n.push(i));let o=n.filter(l=>l.hash===i.hash).length;return o>=this.config.maxIdenticalCalls?(this.loopsDetected++,{isLoop:!0,callCount:o,signature:i,action:"steer",steeringMessage:this.config.steeringMessage}):o===this.config.maxIdenticalCalls-1?{isLoop:!1,callCount:o,signature:i,action:"warn"}:{isLoop:!1,callCount:o,signature:i,action:"allow"}}getMetrics(){return{totalCallsTracked:this.totalCallsTracked,loopsDetected:this.loopsDetected}}clear(){this.callHistory.clear(),this.totalCallsTracked=0,this.loopsDetected=0}createSignature(t,e){let r=JSON.stringify(e??""),i=Xm(r),n=`${t}:${r}`;return{hash:Xm(n),toolName:t,argsFingerprint:i,timestamp:Date.now()}}},rp={"quality-gate":.05,coverage:.1,"test-generation":.15,learning:.2,default:.12},Eb={thresholds:rp,agentId:"unknown",maxHistorySize:200,fallbackDimension:64},Ab=/^(?:Queen[A-Z]|(?:Task|Agent|Workflow|Step|Protocol|Action)[A-Z])/;function xb(c){let t=c.slice(c.lastIndexOf(".")+1);return Ab.test(t)}var Zm=6e4,Pb=256;function ep(c,t){let e=new Float64Array(t),r=2166136261,i=16777619;for(let a=0;a<c.length;a++){let o=c.charCodeAt(a);r^=o,r=Math.imul(r,16777619),i^=o,i=Math.imul(i,2166136261);let l=(r>>>0)%t;e[l]+=(i>>>0)/4294967295*2-1}let n=0;for(let a=0;a<t;a++)n+=e[a]*e[a];n=Math.sqrt(n);let s=new Array(t);for(let a=0;a<t;a++)s[a]=n===0?0:e[a]/n;return s}var tp=!1,Zr=!1,js=null;async function kb(){if(tp)return Zr;tp=!0;try{let c=await import("./real-embeddings-RQRVOKVM.js");if(typeof c.isTransformerAvailable=="function"&&c.isTransformerAvailable())js=c.computeRealEmbedding,Zr=!0;else try{await c.computeRealEmbedding("probe"),js=c.computeRealEmbedding,Zr=!0}catch(t){an.debug("Transformer probe embedding failed",{error:t instanceof Error?t.message:String(t)}),Zr=!1}}catch(c){an.debug("Transformer module import failed",{error:c instanceof Error?c.message:String(c)}),Zr=!1}return Zr}var Hs=class{name="semantic-anti-drift";priority=10;config;history=[];totalChecked=0;driftCount=0;similaritySum=0;unverifiedCount=0;evictedSuppressedWarnings=0;driftWarnings=new Map;emittedPayloadText=new WeakMap;embeddingWarningAt=-1/0;suppressedEmbeddingWarnings=0;constructor(t){this.config={...Eb,...t,thresholds:{...rp,...t?.thresholds}}}async onEmit(t){let e=JSON.stringify(t.payload),r=await this.embedForEvent(e,t,"emit");if(r===null)return t;let i=this.resolveCategory(t.type),n=this.config.thresholds[i]??this.config.thresholds.default,s={embedding:r,driftThreshold:n,sourceAgentId:this.config.agentId,hopCount:0,emittedAt:Date.now()};return this.emittedPayloadText.set(s,e),{...t,semanticFingerprint:s}}async onReceive(t){let e=t.semanticFingerprint;if(!e)return t;let r=JSON.stringify(t.payload),i=1,n=this.emittedPayloadText.get(e);if(this.emittedPayloadText.delete(e),n!==r){let u=await this.embedForEvent(r,t,"receive");if(u===null)return t;i=Mt(u,e.embedding)}let a=1-i>e.driftThreshold;this.totalChecked++,this.similaritySum+=i;let o={drifted:a,cosineSimilarity:i,threshold:e.driftThreshold,eventType:t.type,hopCount:e.hopCount+1,checkedAt:Date.now()};if(this.history.push(o),this.history.length>this.config.maxHistorySize&&this.history.shift(),a){this.driftCount++;let u=xb(t.type);if(this.warnDrift(t,o,u),await this.emitDriftEvent(t,o),!u)return null}let l={...e,hopCount:e.hopCount+1};return{...t,semanticFingerprint:l}}getDriftHistory(){return this.history}getStats(){return{totalChecked:this.totalChecked,driftCount:this.driftCount,averageSimilarity:this.totalChecked>0?this.similaritySum/this.totalChecked:0,unverifiedCount:this.unverifiedCount}}validateConfig(){for(let[t,e]of Object.entries(this.config.thresholds))if(typeof e!="number"||e<0||e>1)return g(new Error(`Invalid threshold for "${t}": must be between 0 and 1, got ${e}`));return this.config.maxHistorySize<=0?g(new Error("maxHistorySize must be positive")):this.config.fallbackDimension<=0?g(new Error("fallbackDimension must be positive")):f(void 0)}async embed(t){if(await kb()&&js){let r=await js(t);return r.some(i=>i!==0)?r:ep(t,r.length||this.config.fallbackDimension)}return ep(t,this.config.fallbackDimension)}async embedForEvent(t,e,r){try{return await this.embed(t)}catch{this.unverifiedCount++;let i=Date.now();return i-this.embeddingWarningAt<Zm?this.suppressedEmbeddingWarnings++:(an.warn("Anti-drift embedding unavailable; event delivered without verification",{eventType:e.type,source:e.source,stage:r,suppressedSinceLastWarning:this.suppressedEmbeddingWarnings}),this.embeddingWarningAt=i,this.suppressedEmbeddingWarnings=0),null}}resolveCategory(t){let e=t.toLowerCase();for(let r of Object.keys(this.config.thresholds))if(r!=="default"&&e.includes(r))return r;return"default"}warnDrift(t,e,r){let i=`${t.type}|${String(t.source)}`,n=Date.now(),s=this.driftWarnings.get(i);if(s&&n-s.lastAt<Zm){s.suppressed++;return}!s&&this.driftWarnings.size>=Pb&&this.evictOldestDriftWarning();let a=s?.suppressed??0,o=this.evictedSuppressedWarnings;this.evictedSuppressedWarnings=0,this.driftWarnings.delete(i),this.driftWarnings.set(i,{lastAt:n,suppressed:0}),an.warn(r?"Semantic drift detected on a control-plane event; delivered anyway":"Semantic drift detected; event dropped",{eventType:t.type,source:t.source,cosineSimilarity:Number(e.cosineSimilarity.toFixed(4)),cosineDistance:Number((1-e.cosineSimilarity).toFixed(4)),threshold:e.threshold,hopCount:e.hopCount,...a>0?{suppressedSinceLastWarning:a}:{},...o>0?{suppressedForEvictedKeys:o}:{}})}evictOldestDriftWarning(){let t=this.driftWarnings.keys().next();t.done||(this.evictedSuppressedWarnings+=this.driftWarnings.get(t.value)?.suppressed??0,this.driftWarnings.delete(t.value))}async emitDriftEvent(t,e){if(!this.config.onDriftDetected)return;let r={id:`drift-${t.id}-${Date.now()}`,type:"SemanticDriftDetected",timestamp:new Date,source:t.source,correlationId:t.correlationId,payload:{originalEventId:t.id,originalEventType:t.type,cosineSimilarity:e.cosineSimilarity,threshold:e.threshold,hopCount:e.hopCount,agentId:this.config.agentId}};try{await this.config.onDriftDetected(r)}catch(i){an.debug("onDriftDetected callback failed",{error:i instanceof Error?i.message:String(i)})}}};$c();yr();import*as Gi from"path";import*as Dc from"fs";yr();import{randomUUID as Db}from"crypto";var rl="aqe/bridge/captured-experiences/cursor",Ib=5e3,Mb=100,Ws=class{constructor(t,e,r={}){this.eventBus=t;this.memory=e;this.intervalMs=r.intervalMs??Ib,this.batchSize=r.batchSize??Mb}eventBus;memory;cursor=0;intervalId;draining=!1;intervalMs;batchSize;async start(){if(this.intervalId)return;let t=await this.memory.get(rl);this.cursor=typeof t=="number"?t:0,await this.drainSafe(),this.intervalId=setInterval(()=>{this.drainSafe()},this.intervalMs),this.intervalId.unref?.()}async stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0)}async drainOnce(){return this.drainSafe()}async drainSafe(){if(this.draining)return 0;this.draining=!0;try{let t=await this.drain();return await Nc(this.memory,"bridge",{success:!0}),t}catch(t){return console.warn("[CapturedExperienceBridge] drain failed:",t instanceof Error?t.message:t),await Nc(this.memory,"bridge",{success:!1,error:t instanceof Error?t:String(t)}),0}finally{this.draining=!1}}async drain(){let t=fr();if(!t.isInitialized())return 0;let e=t.getDatabase();if(!e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='captured_experiences'").get())return 0;let i=e.prepare(`SELECT rowid, id, task, agent, domain, success, quality,
117
+ Fix: Add '${t}' to domains.enabled in .agentic-qe/config.yaml, or run 'aqe init --auto-migrate' to enable all domains.`)}let n=this.loadPlugin(t,i);this.loading.set(t,n);try{let s=await n;return this.plugins.set(t,s),s}finally{this.loading.delete(t)}}async loadPlugin(t,e){let r=await e(this.eventBus,this.memory);for(let i of r.dependencies)this.isLoaded(i)||await this.load(i);return await r.initialize(),r}async unload(t){let e=this.plugins.get(t);if(e){for(let[r,i]of this.plugins.entries())if(i.dependencies.includes(t))throw new Error(`Cannot unload ${t}: domain ${r} depends on it`);await e.dispose(),this.plugins.delete(t)}}isLoaded(t){return this.plugins.has(t)}getLoaded(){return Array.from(this.plugins.keys())}async loadAll(){let t=Array.from(this.factories.keys()),e=this.topologicalSort(t);for(let r of e)await this.load(r)}topologicalSort(t){let e=[],r=new Set,i=new Set,n=s=>{if(r.has(s))return;if(i.has(s))throw new Error(`Circular dependency detected involving: ${s}`);i.add(s);let o=this.plugins.get(s)?.dependencies??[];for(let l of o)t.includes(l)&&n(l);i.delete(s),r.add(s),e.push(s)};for(let s of t)n(s);return e}getPlugin(t){return this.plugins.get(t)}async disposeAll(){let t=[...this.getLoaded()].reverse();for(let e of t)try{await this.unload(e)}catch(r){Rb.debug("Plugin unload failed, force removing",{domain:e,error:r instanceof Error?r.message:String(r)}),this.plugins.delete(e)}}};Fc();bs();_();var an=x.create("anti-drift-middleware"),Tb={maxIdenticalCalls:3,windowMs:3e4,steeringMessage:"Loop detected: the same tool call has been repeated multiple times. Consider an alternative approach or different parameters.",enableFleetLearning:!1};function Xm(c){let t=2166136261;for(let e=0;e<c.length;e++)t^=c.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}var Gs=class{config;callHistory=new Map;totalCallsTracked=0;loopsDetected=0;constructor(t){this.config={...Tb,...t}}trackCall(t,e,r){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return{isLoop:!1,callCount:1,signature:this.createSignature(e,r),action:"allow"};let i=this.createSignature(e,r);this.totalCallsTracked++,this.callHistory.has(t)||this.callHistory.set(t,[]);let n=this.callHistory.get(t);n.push(i);let s=Date.now()-this.config.windowMs,a=n.findIndex(l=>l.timestamp>=s);a>0?n.splice(0,a):a===-1&&(n.length=0,n.push(i));let o=n.filter(l=>l.hash===i.hash).length;return o>=this.config.maxIdenticalCalls?(this.loopsDetected++,{isLoop:!0,callCount:o,signature:i,action:"steer",steeringMessage:this.config.steeringMessage}):o===this.config.maxIdenticalCalls-1?{isLoop:!1,callCount:o,signature:i,action:"warn"}:{isLoop:!1,callCount:o,signature:i,action:"allow"}}getMetrics(){return{totalCallsTracked:this.totalCallsTracked,loopsDetected:this.loopsDetected}}clear(){this.callHistory.clear(),this.totalCallsTracked=0,this.loopsDetected=0}createSignature(t,e){let r=JSON.stringify(e??""),i=Xm(r),n=`${t}:${r}`;return{hash:Xm(n),toolName:t,argsFingerprint:i,timestamp:Date.now()}}},rp={"quality-gate":.05,coverage:.1,"test-generation":.15,learning:.2,default:.12},Eb={thresholds:rp,agentId:"unknown",maxHistorySize:200,fallbackDimension:64},Ab=/^(?:Queen[A-Z]|(?:Task|Agent|Workflow|Step|Protocol|Action)[A-Z])/;function xb(c){let t=c.slice(c.lastIndexOf(".")+1);return Ab.test(t)}var Zm=6e4,Pb=256;function ep(c,t){let e=new Float64Array(t),r=2166136261,i=16777619;for(let a=0;a<c.length;a++){let o=c.charCodeAt(a);r^=o,r=Math.imul(r,16777619),i^=o,i=Math.imul(i,2166136261);let l=(r>>>0)%t;e[l]+=(i>>>0)/4294967295*2-1}let n=0;for(let a=0;a<t;a++)n+=e[a]*e[a];n=Math.sqrt(n);let s=new Array(t);for(let a=0;a<t;a++)s[a]=n===0?0:e[a]/n;return s}var tp=!1,Zr=!1,js=null;async function kb(){if(tp)return Zr;tp=!0;try{let c=await import("./real-embeddings-ZWXS5ZFV.js");if(typeof c.isTransformerAvailable=="function"&&c.isTransformerAvailable())js=c.computeRealEmbedding,Zr=!0;else try{await c.computeRealEmbedding("probe"),js=c.computeRealEmbedding,Zr=!0}catch(t){an.debug("Transformer probe embedding failed",{error:t instanceof Error?t.message:String(t)}),Zr=!1}}catch(c){an.debug("Transformer module import failed",{error:c instanceof Error?c.message:String(c)}),Zr=!1}return Zr}var Hs=class{name="semantic-anti-drift";priority=10;config;history=[];totalChecked=0;driftCount=0;similaritySum=0;unverifiedCount=0;evictedSuppressedWarnings=0;driftWarnings=new Map;emittedPayloadText=new WeakMap;embeddingWarningAt=-1/0;suppressedEmbeddingWarnings=0;constructor(t){this.config={...Eb,...t,thresholds:{...rp,...t?.thresholds}}}async onEmit(t){let e=JSON.stringify(t.payload),r=await this.embedForEvent(e,t,"emit");if(r===null)return t;let i=this.resolveCategory(t.type),n=this.config.thresholds[i]??this.config.thresholds.default,s={embedding:r,driftThreshold:n,sourceAgentId:this.config.agentId,hopCount:0,emittedAt:Date.now()};return this.emittedPayloadText.set(s,e),{...t,semanticFingerprint:s}}async onReceive(t){let e=t.semanticFingerprint;if(!e)return t;let r=JSON.stringify(t.payload),i=1,n=this.emittedPayloadText.get(e);if(this.emittedPayloadText.delete(e),n!==r){let u=await this.embedForEvent(r,t,"receive");if(u===null)return t;i=Mt(u,e.embedding)}let a=1-i>e.driftThreshold;this.totalChecked++,this.similaritySum+=i;let o={drifted:a,cosineSimilarity:i,threshold:e.driftThreshold,eventType:t.type,hopCount:e.hopCount+1,checkedAt:Date.now()};if(this.history.push(o),this.history.length>this.config.maxHistorySize&&this.history.shift(),a){this.driftCount++;let u=xb(t.type);if(this.warnDrift(t,o,u),await this.emitDriftEvent(t,o),!u)return null}let l={...e,hopCount:e.hopCount+1};return{...t,semanticFingerprint:l}}getDriftHistory(){return this.history}getStats(){return{totalChecked:this.totalChecked,driftCount:this.driftCount,averageSimilarity:this.totalChecked>0?this.similaritySum/this.totalChecked:0,unverifiedCount:this.unverifiedCount}}validateConfig(){for(let[t,e]of Object.entries(this.config.thresholds))if(typeof e!="number"||e<0||e>1)return g(new Error(`Invalid threshold for "${t}": must be between 0 and 1, got ${e}`));return this.config.maxHistorySize<=0?g(new Error("maxHistorySize must be positive")):this.config.fallbackDimension<=0?g(new Error("fallbackDimension must be positive")):f(void 0)}async embed(t){if(await kb()&&js){let r=await js(t);return r.some(i=>i!==0)?r:ep(t,r.length||this.config.fallbackDimension)}return ep(t,this.config.fallbackDimension)}async embedForEvent(t,e,r){try{return await this.embed(t)}catch{this.unverifiedCount++;let i=Date.now();return i-this.embeddingWarningAt<Zm?this.suppressedEmbeddingWarnings++:(an.warn("Anti-drift embedding unavailable; event delivered without verification",{eventType:e.type,source:e.source,stage:r,suppressedSinceLastWarning:this.suppressedEmbeddingWarnings}),this.embeddingWarningAt=i,this.suppressedEmbeddingWarnings=0),null}}resolveCategory(t){let e=t.toLowerCase();for(let r of Object.keys(this.config.thresholds))if(r!=="default"&&e.includes(r))return r;return"default"}warnDrift(t,e,r){let i=`${t.type}|${String(t.source)}`,n=Date.now(),s=this.driftWarnings.get(i);if(s&&n-s.lastAt<Zm){s.suppressed++;return}!s&&this.driftWarnings.size>=Pb&&this.evictOldestDriftWarning();let a=s?.suppressed??0,o=this.evictedSuppressedWarnings;this.evictedSuppressedWarnings=0,this.driftWarnings.delete(i),this.driftWarnings.set(i,{lastAt:n,suppressed:0}),an.warn(r?"Semantic drift detected on a control-plane event; delivered anyway":"Semantic drift detected; event dropped",{eventType:t.type,source:t.source,cosineSimilarity:Number(e.cosineSimilarity.toFixed(4)),cosineDistance:Number((1-e.cosineSimilarity).toFixed(4)),threshold:e.threshold,hopCount:e.hopCount,...a>0?{suppressedSinceLastWarning:a}:{},...o>0?{suppressedForEvictedKeys:o}:{}})}evictOldestDriftWarning(){let t=this.driftWarnings.keys().next();t.done||(this.evictedSuppressedWarnings+=this.driftWarnings.get(t.value)?.suppressed??0,this.driftWarnings.delete(t.value))}async emitDriftEvent(t,e){if(!this.config.onDriftDetected)return;let r={id:`drift-${t.id}-${Date.now()}`,type:"SemanticDriftDetected",timestamp:new Date,source:t.source,correlationId:t.correlationId,payload:{originalEventId:t.id,originalEventType:t.type,cosineSimilarity:e.cosineSimilarity,threshold:e.threshold,hopCount:e.hopCount,agentId:this.config.agentId}};try{await this.config.onDriftDetected(r)}catch(i){an.debug("onDriftDetected callback failed",{error:i instanceof Error?i.message:String(i)})}}};$c();yr();import*as Gi from"path";import*as Dc from"fs";yr();import{randomUUID as Db}from"crypto";var rl="aqe/bridge/captured-experiences/cursor",Ib=5e3,Mb=100,Ws=class{constructor(t,e,r={}){this.eventBus=t;this.memory=e;this.intervalMs=r.intervalMs??Ib,this.batchSize=r.batchSize??Mb}eventBus;memory;cursor=0;intervalId;draining=!1;intervalMs;batchSize;async start(){if(this.intervalId)return;let t=await this.memory.get(rl);this.cursor=typeof t=="number"?t:0,await this.drainSafe(),this.intervalId=setInterval(()=>{this.drainSafe()},this.intervalMs),this.intervalId.unref?.()}async stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0)}async drainOnce(){return this.drainSafe()}async drainSafe(){if(this.draining)return 0;this.draining=!0;try{let t=await this.drain();return await Nc(this.memory,"bridge",{success:!0}),t}catch(t){return console.warn("[CapturedExperienceBridge] drain failed:",t instanceof Error?t.message:t),await Nc(this.memory,"bridge",{success:!1,error:t instanceof Error?t:String(t)}),0}finally{this.draining=!1}}async drain(){let t=fr();if(!t.isInitialized())return 0;let e=t.getDatabase();if(!e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='captured_experiences'").get())return 0;let i=e.prepare(`SELECT rowid, id, task, agent, domain, success, quality,
118
118
  duration_ms, source, completed_at
119
119
  FROM captured_experiences
120
120
  WHERE rowid > ?
@@ -1922,7 +1922,7 @@ ${o},
1922
1922
  `,e+=` });
1923
1923
  `)}return e+=` });
1924
1924
 
1925
- `,e}static convertParsedFile(t){return{functions:t.functions.map(e=>({name:e.name,parameters:e.parameters.map(r=>({name:r.name,type:r.type,optional:r.isOptional,defaultValue:r.defaultValue})),returnType:e.returnType,isAsync:e.isAsync,isExported:e.isPublic,complexity:e.complexity,startLine:e.startLine,endLine:e.endLine,body:e.body})),classes:t.classes.map(e=>({name:e.name,methods:e.methods.map(r=>({name:r.name,parameters:r.parameters.map(i=>({name:i.name,type:i.type,optional:i.isOptional,defaultValue:i.defaultValue})),returnType:r.returnType,isAsync:r.isAsync,isExported:r.isPublic,complexity:r.complexity,startLine:r.startLine,endLine:r.endLine,body:r.body})),properties:e.properties.map(r=>({name:r.name,type:r.type,isPrivate:!r.isPublic,isReadonly:r.isReadonly})),isExported:e.isPublic,hasConstructor:e.methods.some(r=>r.name==="constructor"),constructorParams:e.methods.find(r=>r.name==="constructor")?.parameters.map(r=>({name:r.name,type:r.type,optional:r.isOptional,defaultValue:r.defaultValue}))}))}}};var zb=Us,Bb="vitest",wn=class{cache=new Map;create(t){let e=Qs(t)??t,r=this.cache.get(e);if(r)return r;let i=this.createGenerator(e);return this.cache.set(e,i),i}supports(t){return Qs(t)!==void 0}getDefault(){return Bb}getSupportedFrameworks(){return[...zb]}createGenerator(t){switch(t){case"jest":return new ti("jest");case"vitest":return new ti("vitest");case"mocha":return new un;case"pytest":return new qt;case"node-test":return new dn;case"junit5":case"testng":return new mn;case"xunit":case"nunit":return new gn;case"go-test":return new pn;case"rust-test":return new hn;case"swift-testing":case"xctest":return new fn;case"kotlin-junit":return new yn;case"flutter-test":return new vn;case"jest-rn":return new bn;case"playwright":case"cypress":throw new Error(`Generator for '${t}' not yet implemented`);default:throw new Error(`Unsupported test framework: ${t}`)}}clearCache(){this.cache.clear()}},VI=new wn;var Ys=class{async generateTDDTests(t){let{feature:e,behavior:r,framework:i,phase:n}=t;switch(n){case"red":return this.generateRedPhaseTest(e,r,i);case"green":return this.generateGreenPhaseCode(e,r,i);case"refactor":return this.generateRefactoringSuggestions(e,r);default:throw new Error(`Unknown TDD phase: ${n}`)}}generateRedPhaseTest(t,e,r){let i=this.camelCase(t),n=this.generateAssertionsFromBehavior(e,i);return{phase:"red",testCode:`describe('${t}', () => {
1925
+ `,e}static convertParsedFile(t){return{functions:t.functions.map(e=>({name:e.name,parameters:e.parameters.map(r=>({name:r.name,type:r.type,optional:r.isOptional,defaultValue:r.defaultValue})),returnType:e.returnType,isAsync:e.isAsync,isExported:e.isPublic,complexity:e.complexity,startLine:e.startLine,endLine:e.endLine,body:e.body})),classes:t.classes.map(e=>({name:e.name,methods:e.methods.map(r=>({name:r.name,parameters:r.parameters.map(i=>({name:i.name,type:i.type,optional:i.isOptional,defaultValue:i.defaultValue})),returnType:r.returnType,isAsync:r.isAsync,isExported:r.isPublic,complexity:r.complexity,startLine:r.startLine,endLine:r.endLine,body:r.body})),properties:e.properties.map(r=>({name:r.name,type:r.type,isPrivate:!r.isPublic,isReadonly:r.isReadonly})),isExported:e.isPublic,hasConstructor:e.methods.some(r=>r.name==="constructor"),constructorParams:e.methods.find(r=>r.name==="constructor")?.parameters.map(r=>({name:r.name,type:r.type,optional:r.isOptional,defaultValue:r.defaultValue}))}))}}};var zb=Us,Bb="vitest",wn=class{cache=new Map;create(t){let e=Qs(t)??t,r=this.cache.get(e);if(r)return r;let i=this.createGenerator(e);return this.cache.set(e,i),i}supports(t){return Qs(t)!==void 0}getDefault(){return Bb}getSupportedFrameworks(){return[...zb]}createGenerator(t){switch(t){case"jest":return new ti("jest");case"vitest":return new ti("vitest");case"mocha":return new un;case"pytest":return new qt;case"node-test":return new dn;case"junit5":case"testng":return new mn;case"xunit":case"nunit":return new gn;case"go-test":return new pn;case"rust-test":return new hn;case"swift-testing":case"xctest":return new fn;case"kotlin-junit":return new yn;case"flutter-test":return new vn;case"jest-rn":return new bn;case"playwright":case"cypress":throw new Error(`Generator for '${t}' not yet implemented`);default:throw new Error(`Unsupported test framework: ${t}`)}}clearCache(){this.cache.clear()}},zI=new wn;var Ys=class{async generateTDDTests(t){let{feature:e,behavior:r,framework:i,phase:n}=t;switch(n){case"red":return this.generateRedPhaseTest(e,r,i);case"green":return this.generateGreenPhaseCode(e,r,i);case"refactor":return this.generateRefactoringSuggestions(e,r);default:throw new Error(`Unknown TDD phase: ${n}`)}}generateRedPhaseTest(t,e,r){let i=this.camelCase(t),n=this.generateAssertionsFromBehavior(e,i);return{phase:"red",testCode:`describe('${t}', () => {
1926
1926
  it('${e}', () => {
1927
1927
  // Red phase: This test should fail initially
1928
1928
  ${n}
@@ -2047,7 +2047,7 @@ ${t}
2047
2047
  Return a JSON array of test suggestions, each with: { "name": "test name", "description": "what to test", "type": "unit|integration|edge" }`},{role:"user",content:`Analyze this ${r} code and suggest test cases:
2048
2048
  \`\`\`${this.getCodeFenceLanguage(r)}
2049
2049
  ${t}
2050
- \`\`\``}],model:i,maxTokens:1024,temperature:.5,agentType:"qe-test-architect"});if(n.content)try{let s=n.content.match(/\[[\s\S]*\]/);if(s)return D(s[0]).map(o=>o.name)}catch{}return[]}catch{return ta.warn("LLM suggestion generation failed:"),[]}}async generateTests(t){try{xs(t.behaviorExamples);let e=yp({sourceFiles:t.sourceFiles,language:t.language,framework:t.framework,projectRoot:t.projectRoot}),r=t.framework||e?.framework||"vitest",i=t.language||e?.language,{sourceFiles:n,testType:s,patterns:a=[]}=t;if(t.behaviorExamples?.length&&n.length!==1)return g(new yt("behaviorExamples requires exactly one source file"));if(n.length===0)return g(new Error("No source files provided"));let o=[],l=[],u=[];for(let m of n){let p=await this.generateTestsForFile(m,s,r,a,i,t);p.success&&(o.push(...p.value.tests),l.push(...p.value.patternsUsed),u.push(...p.value.patternIds))}if(process.env.AQE_HOLDOUT_TESTING_ENABLED==="true")for(let m of o)ow(m.id)&&(m.holdout=!0);let d=null;return await this.storeGenerationMetadata(o,l),f({tests:o,coverageEstimate:d,patternsUsed:Array.from(new Set(l)),patternIds:Array.from(new Set(u))})}catch(e){return g(y(e))}}async generateForCoverageGap(t,e,r){try{if(e.length===0)return f([]);let i=[],n=this.groupConsecutiveLines(e),s=this.generatorFactory.supports(r)?r:this.config.defaultFramework;for(let a of n){let o=await this.generateTestForLines(t,a,s);o&&i.push(o)}return f(i)}catch(i){return g(y(i))}}async generateTDDTests(t){try{let e=await this.tddGenerator.generateTDDTests(t);return f(e)}catch(e){return g(y(e))}}async generatePropertyTests(t){try{let e=await this.propertyTestGenerator.generatePropertyTests(t);return f(e)}catch(e){return g(y(e))}}async generateTestData(t){try{let e=await this.testDataGenerator.generateTestData(t);return f(e)}catch(e){return g(y(e))}}async generateTestsForFile(t,e,r,i,n,s){let a=this.getTestFilePath(t,r),o=[],l=[],u=await this.findApplicablePatterns(t,i);o.push(...u.map(Y=>Y.name)),l.push(...u.map(Y=>Y.id));let d=null,m="";try{m=Qr(t,{outsideRoot:"allow"}),d=await this.analyzeSourceCode(m,t)}catch{}let p,h;this.memory&&m&&await this.hasKGVectors()&&(p=await this.queryKGDependencies(t,m),h=await this.queryKGSimilarCode(m));let v=this.generatorFactory.create(r),b=this.extractModuleName(t),C=s?.importPathOverrides?.[t]??this.getImportPath(t),S={moduleName:b,importPath:C,testType:e,patterns:u,analysis:d??void 0,dependencies:p,similarCode:h},R=(s?.behaviorExamples?.length??0)>0,E=/\.(?:[cm]?[jt]s|[jt]sx)$/i.test(t),T=(this.usesDefaultGenerator||R)&&e==="unit"&&E&&["vitest","jest","node-test"].includes(r);if(R&&!T)throw new yt("Behavior examples require JavaScript/TypeScript and vitest, jest, or node-test");let I=()=>ap(m,t,s?.importPathOverrides?.[t]??Cr.resolve(t),r,s?.behaviorExamples,e),O=this.isLLMEnhancementAvailable()&&!!m&&!R,q=T&&!O?I():void 0,j=q?.code??v.generateTests(S),$=!1;if(O){let Y=await this.enhanceTestWithLLM(j,m,d,t,S,s?.importPathOverrides?.[t]===void 0);$=Y.enhanced,$?j=Y.code:T&&(q=I(),j=q.code)}let ee={id:w(),name:`${b} tests`,sourceFile:t,testFile:a,testCode:j,type:e,assertions:q&&!$?q.assertions:this.countAssertions(j),...!$&&q?{generationMode:q.mode,generationLimits:q.limits}:{},language:n,framework:r,llmEnhanced:$};if(s?.compileValidation&&n)try{let Y=await bp.validate(j,n,s.projectRoot);ee.compilationValidated=Y.compiles,Y.compiles||(ee.compilationErrors=Y.errors.map(Ic=>Ic.message))}catch{}return this.qualityGate&&(ee.qualityGateResult=this.qualityGate.validate(j,t,m||void 0)),f({tests:[ee],patternsUsed:o,patternIds:l})}async generateTestForLines(t,e,r){if(e.length===0)return null;let i=w(),n=this.getTestFilePath(t,r),s=this.extractModuleName(t),a=this.getImportPath(t),l=this.generatorFactory.create(r).generateCoverageTests(s,a,e);return{id:i,name:`Coverage test for lines ${e[0]}-${e[e.length-1]}`,sourceFile:t,testFile:n,testCode:l,type:"unit",assertions:this.countAssertions(l)}}async analyzeSourceCode(t,e){let r=Cr.extname(e),i=zt(r);if(i&&i!=="typescript"&&i!=="javascript"){let l=await Ji.parseFile(t,e,i);if(l)return qt.convertParsedFile(l)}let n=A.createSourceFile(Cr.basename(e),t,A.ScriptTarget.Latest,!0,A.ScriptKind.TS),s=[],a=[],o=l=>{if(A.isFunctionDeclaration(l)&&l.name)s.push(this.extractFunctionInfo(l,n));else if(A.isVariableStatement(l)){for(let u of l.declarationList.declarations)if(A.isVariableDeclaration(u)&&u.initializer&&(A.isArrowFunction(u.initializer)||A.isFunctionExpression(u.initializer))){let d=u.name.getText(n);s.push(this.extractArrowFunctionInfo(d,u.initializer,n,l))}}else A.isClassDeclaration(l)&&l.name&&a.push(this.extractClassInfo(l,n));A.forEachChild(l,o)};return A.forEachChild(n,o),{functions:s,classes:a}}extractFunctionInfo(t,e){let r=t.name?.getText(e)||"anonymous",i=this.extractParameters(t.parameters,e),n=t.type?.getText(e),s=t.modifiers?.some(u=>u.kind===A.SyntaxKind.AsyncKeyword)??!1,a=t.modifiers?.some(u=>u.kind===A.SyntaxKind.ExportKeyword)??!1,{line:o}=e.getLineAndCharacterOfPosition(t.getStart(e)),{line:l}=e.getLineAndCharacterOfPosition(t.getEnd());return{name:r,parameters:i,returnType:n,isAsync:s,isExported:a,complexity:this.calculateComplexity(t),startLine:o+1,endLine:l+1,body:t.body?.getText(e)}}extractArrowFunctionInfo(t,e,r,i){let n=this.extractParameters(e.parameters,r),s=e.type?.getText(r),a=e.modifiers?.some(d=>d.kind===A.SyntaxKind.AsyncKeyword)??!1,o=A.isVariableStatement(i)&&(i.modifiers?.some(d=>d.kind===A.SyntaxKind.ExportKeyword)??!1),{line:l}=r.getLineAndCharacterOfPosition(e.getStart(r)),{line:u}=r.getLineAndCharacterOfPosition(e.getEnd());return{name:t,parameters:n,returnType:s,isAsync:a,isExported:o,complexity:this.calculateComplexity(e),startLine:l+1,endLine:u+1,body:e.body?.getText(r)}}extractClassInfo(t,e){let r=t.name?.getText(e)||"AnonymousClass",i=[],n=[],s=!1,a,o=t.modifiers?.some(l=>l.kind===A.SyntaxKind.ExportKeyword)??!1;for(let l of t.members)if(A.isMethodDeclaration(l)){let u=l.name.getText(e),d=this.extractParameters(l.parameters,e),m=l.type?.getText(e),p=l.modifiers?.some(b=>b.kind===A.SyntaxKind.AsyncKeyword)??!1,{line:h}=e.getLineAndCharacterOfPosition(l.getStart(e)),{line:v}=e.getLineAndCharacterOfPosition(l.getEnd());i.push({name:u,parameters:d,returnType:m,isAsync:p,isExported:!1,complexity:this.calculateComplexity(l),startLine:h+1,endLine:v+1,body:l.body?.getText(e)})}else if(A.isConstructorDeclaration(l))s=!0,a=this.extractParameters(l.parameters,e);else if(A.isPropertyDeclaration(l)){let u=l.name.getText(e),d=l.type?.getText(e),m=l.modifiers?.some(h=>h.kind===A.SyntaxKind.PrivateKeyword)??!1,p=l.modifiers?.some(h=>h.kind===A.SyntaxKind.ReadonlyKeyword)??!1;n.push({name:u,type:d,isPrivate:m,isReadonly:p})}return{name:r,methods:i,properties:n,isExported:o,hasConstructor:s,constructorParams:a}}extractParameters(t,e){let r=0,i=0;return t.map(n=>{let s=n.name.getText(e),a=n.type?.getText(e);return A.isObjectBindingPattern(n.name)?(r++,s=r>1?`options${r}`:"options",a||(a=`{ ${n.name.elements.map(l=>`${l.name.getText(e)}: unknown`).join(", ")} }`)):A.isArrayBindingPattern(n.name)&&(i++,s=i>1?`items${i}`:"items",a||(a="unknown[]")),{name:s,type:a,optional:n.questionToken!==void 0,defaultValue:n.initializer?.getText(e)}})}calculateComplexity(t){let e=1,r=i=>{switch(i.kind){case A.SyntaxKind.IfStatement:case A.SyntaxKind.ForStatement:case A.SyntaxKind.ForInStatement:case A.SyntaxKind.ForOfStatement:case A.SyntaxKind.WhileStatement:case A.SyntaxKind.DoStatement:case A.SyntaxKind.CaseClause:case A.SyntaxKind.CatchClause:case A.SyntaxKind.ConditionalExpression:e++;break;case A.SyntaxKind.BinaryExpression:{let n=i;(n.operatorToken.kind===A.SyntaxKind.AmpersandAmpersandToken||n.operatorToken.kind===A.SyntaxKind.BarBarToken)&&e++;break}}A.forEachChild(i,r)};return A.forEachChild(t,r),e}async hasKGVectors(){try{let t=new Array(384).fill(0);return t[0]=1,(await this.memory.vectorSearch(t,1)).length>0}catch{return!1}}async queryKGDependencies(t,e){try{let r=[],i=[],n=[],s=[],a=e.matchAll(/(?:import|from)\s+['"]([^'"]+)['"]/g);for(let m of a)r.push(m[1]);if(t.endsWith(".py")){let m=e.matchAll(/(?:^|\n)\s*(?:from\s+(\S+)\s+import|import\s+(\S+))/g);for(let p of m){let h=p[1]||p[2];h&&/^[a-zA-Z_][\w.]*$/.test(h)&&r.push(h)}}let u=t.replace(/\\/g,"/").split("/").pop()?.replace(/\.(ts|js|tsx|jsx|py)$/,"")||"",d=await this.memory.search(`code-intelligence:kg:node:*${u}*`,50,{namespace:"code-intelligence:kg"});for(let m of d){if(!m.includes(u))continue;let p=m.split(":"),h=p[p.length-2],v=p[p.length-1];h==="function"&&n.push(v)}return r.length===0&&i.length===0&&n.length===0&&s.length===0?void 0:{imports:r,importedBy:i,callees:n,callers:s}}catch{return}}async queryKGSimilarCode(t){try{let e=this.generatePseudoEmbedding(t),r=await this.memory.vectorSearch(e,5);if(r.length===0)return;let i=[];for(let n of r){if(n.score<.1)continue;let s=n.metadata,a=s?.file||n.key,o=s?.name||s?.type||n.key.split(":").pop()||"";i.push({file:a,snippet:o,score:n.score})}return i.length>0?{snippets:i}:void 0}catch{return}}generatePseudoEmbedding(t){let r=new Array(384).fill(0),i=t.split(/[^a-zA-Z0-9_$]+/).filter(s=>s.length>1);for(let s=0;s<i.length;s++){let a=i[s];for(let o=0;o<a.length&&o<r.length;o++)r[(s+o)%384]+=a.charCodeAt(o)/1e3}let n=Math.sqrt(r.reduce((s,a)=>s+a*a,0));if(n>0)for(let s=0;s<384;s++)r[s]/=n;return r}getCodeFenceLanguage(t){try{let{FRAMEWORK_TO_LANGUAGE:e}=(ei(),Wr(cp)),r=e?.[t];if(r){let i=Cp(r);if(i)return i.codeFenceLanguage}}catch{}return"typescript"}convertParsedToCodeAnalysis(t){return qt.convertParsedFile(t)}async findApplicablePatterns(t,e){let r=[];try{let{getUnifiedMemory:i}=await import("./unified-memory-AGDZQ5XD.js"),n=i().getDatabase();for(let o of e){let l=n.prepare(`SELECT id, name, description, pattern_type, usage_count, quality_score
2050
+ \`\`\``}],model:i,maxTokens:1024,temperature:.5,agentType:"qe-test-architect"});if(n.content)try{let s=n.content.match(/\[[\s\S]*\]/);if(s)return D(s[0]).map(o=>o.name)}catch{}return[]}catch{return ta.warn("LLM suggestion generation failed:"),[]}}async generateTests(t){try{xs(t.behaviorExamples);let e=yp({sourceFiles:t.sourceFiles,language:t.language,framework:t.framework,projectRoot:t.projectRoot}),r=t.framework||e?.framework||"vitest",i=t.language||e?.language,{sourceFiles:n,testType:s,patterns:a=[]}=t;if(t.behaviorExamples?.length&&n.length!==1)return g(new yt("behaviorExamples requires exactly one source file"));if(n.length===0)return g(new Error("No source files provided"));let o=[],l=[],u=[];for(let m of n){let p=await this.generateTestsForFile(m,s,r,a,i,t);p.success&&(o.push(...p.value.tests),l.push(...p.value.patternsUsed),u.push(...p.value.patternIds))}if(process.env.AQE_HOLDOUT_TESTING_ENABLED==="true")for(let m of o)ow(m.id)&&(m.holdout=!0);let d=null;return await this.storeGenerationMetadata(o,l),f({tests:o,coverageEstimate:d,patternsUsed:Array.from(new Set(l)),patternIds:Array.from(new Set(u))})}catch(e){return g(y(e))}}async generateForCoverageGap(t,e,r){try{if(e.length===0)return f([]);let i=[],n=this.groupConsecutiveLines(e),s=this.generatorFactory.supports(r)?r:this.config.defaultFramework;for(let a of n){let o=await this.generateTestForLines(t,a,s);o&&i.push(o)}return f(i)}catch(i){return g(y(i))}}async generateTDDTests(t){try{let e=await this.tddGenerator.generateTDDTests(t);return f(e)}catch(e){return g(y(e))}}async generatePropertyTests(t){try{let e=await this.propertyTestGenerator.generatePropertyTests(t);return f(e)}catch(e){return g(y(e))}}async generateTestData(t){try{let e=await this.testDataGenerator.generateTestData(t);return f(e)}catch(e){return g(y(e))}}async generateTestsForFile(t,e,r,i,n,s){let a=this.getTestFilePath(t,r),o=[],l=[],u=await this.findApplicablePatterns(t,i);o.push(...u.map(Y=>Y.name)),l.push(...u.map(Y=>Y.id));let d=null,m="";try{m=Qr(t,{outsideRoot:"allow"}),d=await this.analyzeSourceCode(m,t)}catch{}let p,h;this.memory&&m&&await this.hasKGVectors()&&(p=await this.queryKGDependencies(t,m),h=await this.queryKGSimilarCode(m));let v=this.generatorFactory.create(r),b=this.extractModuleName(t),C=s?.importPathOverrides?.[t]??this.getImportPath(t),S={moduleName:b,importPath:C,testType:e,patterns:u,analysis:d??void 0,dependencies:p,similarCode:h},R=(s?.behaviorExamples?.length??0)>0,E=/\.(?:[cm]?[jt]s|[jt]sx)$/i.test(t),T=(this.usesDefaultGenerator||R)&&e==="unit"&&E&&["vitest","jest","node-test"].includes(r);if(R&&!T)throw new yt("Behavior examples require JavaScript/TypeScript and vitest, jest, or node-test");let I=()=>ap(m,t,s?.importPathOverrides?.[t]??Cr.resolve(t),r,s?.behaviorExamples,e),O=this.isLLMEnhancementAvailable()&&!!m&&!R,q=T&&!O?I():void 0,j=q?.code??v.generateTests(S),$=!1;if(O){let Y=await this.enhanceTestWithLLM(j,m,d,t,S,s?.importPathOverrides?.[t]===void 0);$=Y.enhanced,$?j=Y.code:T&&(q=I(),j=q.code)}let ee={id:w(),name:`${b} tests`,sourceFile:t,testFile:a,testCode:j,type:e,assertions:q&&!$?q.assertions:this.countAssertions(j),...!$&&q?{generationMode:q.mode,generationLimits:q.limits}:{},language:n,framework:r,llmEnhanced:$};if(s?.compileValidation&&n)try{let Y=await bp.validate(j,n,s.projectRoot);ee.compilationValidated=Y.compiles,Y.compiles||(ee.compilationErrors=Y.errors.map(Ic=>Ic.message))}catch{}return this.qualityGate&&(ee.qualityGateResult=this.qualityGate.validate(j,t,m||void 0)),f({tests:[ee],patternsUsed:o,patternIds:l})}async generateTestForLines(t,e,r){if(e.length===0)return null;let i=w(),n=this.getTestFilePath(t,r),s=this.extractModuleName(t),a=this.getImportPath(t),l=this.generatorFactory.create(r).generateCoverageTests(s,a,e);return{id:i,name:`Coverage test for lines ${e[0]}-${e[e.length-1]}`,sourceFile:t,testFile:n,testCode:l,type:"unit",assertions:this.countAssertions(l)}}async analyzeSourceCode(t,e){let r=Cr.extname(e),i=zt(r);if(i&&i!=="typescript"&&i!=="javascript"){let l=await Ji.parseFile(t,e,i);if(l)return qt.convertParsedFile(l)}let n=A.createSourceFile(Cr.basename(e),t,A.ScriptTarget.Latest,!0,A.ScriptKind.TS),s=[],a=[],o=l=>{if(A.isFunctionDeclaration(l)&&l.name)s.push(this.extractFunctionInfo(l,n));else if(A.isVariableStatement(l)){for(let u of l.declarationList.declarations)if(A.isVariableDeclaration(u)&&u.initializer&&(A.isArrowFunction(u.initializer)||A.isFunctionExpression(u.initializer))){let d=u.name.getText(n);s.push(this.extractArrowFunctionInfo(d,u.initializer,n,l))}}else A.isClassDeclaration(l)&&l.name&&a.push(this.extractClassInfo(l,n));A.forEachChild(l,o)};return A.forEachChild(n,o),{functions:s,classes:a}}extractFunctionInfo(t,e){let r=t.name?.getText(e)||"anonymous",i=this.extractParameters(t.parameters,e),n=t.type?.getText(e),s=t.modifiers?.some(u=>u.kind===A.SyntaxKind.AsyncKeyword)??!1,a=t.modifiers?.some(u=>u.kind===A.SyntaxKind.ExportKeyword)??!1,{line:o}=e.getLineAndCharacterOfPosition(t.getStart(e)),{line:l}=e.getLineAndCharacterOfPosition(t.getEnd());return{name:r,parameters:i,returnType:n,isAsync:s,isExported:a,complexity:this.calculateComplexity(t),startLine:o+1,endLine:l+1,body:t.body?.getText(e)}}extractArrowFunctionInfo(t,e,r,i){let n=this.extractParameters(e.parameters,r),s=e.type?.getText(r),a=e.modifiers?.some(d=>d.kind===A.SyntaxKind.AsyncKeyword)??!1,o=A.isVariableStatement(i)&&(i.modifiers?.some(d=>d.kind===A.SyntaxKind.ExportKeyword)??!1),{line:l}=r.getLineAndCharacterOfPosition(e.getStart(r)),{line:u}=r.getLineAndCharacterOfPosition(e.getEnd());return{name:t,parameters:n,returnType:s,isAsync:a,isExported:o,complexity:this.calculateComplexity(e),startLine:l+1,endLine:u+1,body:e.body?.getText(r)}}extractClassInfo(t,e){let r=t.name?.getText(e)||"AnonymousClass",i=[],n=[],s=!1,a,o=t.modifiers?.some(l=>l.kind===A.SyntaxKind.ExportKeyword)??!1;for(let l of t.members)if(A.isMethodDeclaration(l)){let u=l.name.getText(e),d=this.extractParameters(l.parameters,e),m=l.type?.getText(e),p=l.modifiers?.some(b=>b.kind===A.SyntaxKind.AsyncKeyword)??!1,{line:h}=e.getLineAndCharacterOfPosition(l.getStart(e)),{line:v}=e.getLineAndCharacterOfPosition(l.getEnd());i.push({name:u,parameters:d,returnType:m,isAsync:p,isExported:!1,complexity:this.calculateComplexity(l),startLine:h+1,endLine:v+1,body:l.body?.getText(e)})}else if(A.isConstructorDeclaration(l))s=!0,a=this.extractParameters(l.parameters,e);else if(A.isPropertyDeclaration(l)){let u=l.name.getText(e),d=l.type?.getText(e),m=l.modifiers?.some(h=>h.kind===A.SyntaxKind.PrivateKeyword)??!1,p=l.modifiers?.some(h=>h.kind===A.SyntaxKind.ReadonlyKeyword)??!1;n.push({name:u,type:d,isPrivate:m,isReadonly:p})}return{name:r,methods:i,properties:n,isExported:o,hasConstructor:s,constructorParams:a}}extractParameters(t,e){let r=0,i=0;return t.map(n=>{let s=n.name.getText(e),a=n.type?.getText(e);return A.isObjectBindingPattern(n.name)?(r++,s=r>1?`options${r}`:"options",a||(a=`{ ${n.name.elements.map(l=>`${l.name.getText(e)}: unknown`).join(", ")} }`)):A.isArrayBindingPattern(n.name)&&(i++,s=i>1?`items${i}`:"items",a||(a="unknown[]")),{name:s,type:a,optional:n.questionToken!==void 0,defaultValue:n.initializer?.getText(e)}})}calculateComplexity(t){let e=1,r=i=>{switch(i.kind){case A.SyntaxKind.IfStatement:case A.SyntaxKind.ForStatement:case A.SyntaxKind.ForInStatement:case A.SyntaxKind.ForOfStatement:case A.SyntaxKind.WhileStatement:case A.SyntaxKind.DoStatement:case A.SyntaxKind.CaseClause:case A.SyntaxKind.CatchClause:case A.SyntaxKind.ConditionalExpression:e++;break;case A.SyntaxKind.BinaryExpression:{let n=i;(n.operatorToken.kind===A.SyntaxKind.AmpersandAmpersandToken||n.operatorToken.kind===A.SyntaxKind.BarBarToken)&&e++;break}}A.forEachChild(i,r)};return A.forEachChild(t,r),e}async hasKGVectors(){try{let t=new Array(384).fill(0);return t[0]=1,(await this.memory.vectorSearch(t,1)).length>0}catch{return!1}}async queryKGDependencies(t,e){try{let r=[],i=[],n=[],s=[],a=e.matchAll(/(?:import|from)\s+['"]([^'"]+)['"]/g);for(let m of a)r.push(m[1]);if(t.endsWith(".py")){let m=e.matchAll(/(?:^|\n)\s*(?:from\s+(\S+)\s+import|import\s+(\S+))/g);for(let p of m){let h=p[1]||p[2];h&&/^[a-zA-Z_][\w.]*$/.test(h)&&r.push(h)}}let u=t.replace(/\\/g,"/").split("/").pop()?.replace(/\.(ts|js|tsx|jsx|py)$/,"")||"",d=await this.memory.search(`code-intelligence:kg:node:*${u}*`,50,{namespace:"code-intelligence:kg"});for(let m of d){if(!m.includes(u))continue;let p=m.split(":"),h=p[p.length-2],v=p[p.length-1];h==="function"&&n.push(v)}return r.length===0&&i.length===0&&n.length===0&&s.length===0?void 0:{imports:r,importedBy:i,callees:n,callers:s}}catch{return}}async queryKGSimilarCode(t){try{let e=this.generatePseudoEmbedding(t),r=await this.memory.vectorSearch(e,5);if(r.length===0)return;let i=[];for(let n of r){if(n.score<.1)continue;let s=n.metadata,a=s?.file||n.key,o=s?.name||s?.type||n.key.split(":").pop()||"";i.push({file:a,snippet:o,score:n.score})}return i.length>0?{snippets:i}:void 0}catch{return}}generatePseudoEmbedding(t){let r=new Array(384).fill(0),i=t.split(/[^a-zA-Z0-9_$]+/).filter(s=>s.length>1);for(let s=0;s<i.length;s++){let a=i[s];for(let o=0;o<a.length&&o<r.length;o++)r[(s+o)%384]+=a.charCodeAt(o)/1e3}let n=Math.sqrt(r.reduce((s,a)=>s+a*a,0));if(n>0)for(let s=0;s<384;s++)r[s]/=n;return r}getCodeFenceLanguage(t){try{let{FRAMEWORK_TO_LANGUAGE:e}=(ei(),Wr(cp)),r=e?.[t];if(r){let i=Cp(r);if(i)return i.codeFenceLanguage}}catch{}return"typescript"}convertParsedToCodeAnalysis(t){return qt.convertParsedFile(t)}async findApplicablePatterns(t,e){let r=[];try{let{getUnifiedMemory:i}=await import("./unified-memory-FL26RTV3.js"),n=i().getDatabase();for(let o of e){let l=n.prepare(`SELECT id, name, description, pattern_type, usage_count, quality_score
2051
2051
  FROM qe_patterns WHERE id = ? OR name = ? LIMIT 1`).get(o,o);l&&r.push({id:l.id,name:l.name,structure:l.pattern_type,examples:l.usage_count,applicability:l.quality_score})}let s=t.split(".").pop()||"",a=n.prepare(`SELECT id, name, description, pattern_type, usage_count, quality_score
2052
2052
  FROM qe_patterns
2053
2053
  WHERE qe_domain = 'test-generation'
@@ -2137,7 +2137,7 @@ Individual assessments:`),t.forEach(s=>{let a=this.countsAsAgreement(s)?"\u2713
2137
2137
  created_at TEXT DEFAULT (datetime('now')),
2138
2138
  updated_at TEXT DEFAULT (datetime('now'))
2139
2139
  );
2140
- `,Wl={loadOnInit:!0,autoSaveInterval:0,maxPatternsToLoad:1e4,enableCrossProcessSharing:!0},ca=class{baseEngine;config;persistence=null;db=null;prepared=new Map;initialized=!1;initPromise=null;pendingSaves=new Map;saveTimer=null;consecutiveSaveFailures=0;serverClient=null;constructor(t){this.config={...Wl,...t},this.baseEngine=new $m(t),this.serverClient=t.serverClient??null}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{this.persistence=Ss(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.ensureSchema(),this.prepareStatements(),this.config.loadOnInit&&await this.loadPatterns();let{isSONAThreeLoopEnabled:t}=await import("./feature-flags-O7ZXDDCD.js");if(t()){this.baseEngine.initThreeLoopEngine(),this.baseEngine.setFisherPersistence((r,i,n,s,a)=>{this.saveFisherMatrix(r,i,n,s,a)},this.config.domain);let e=this._loadFisherMatrixUnsafe(this.config.domain);if(e){let r=this.baseEngine.getThreeLoopEngine();r&&(r.restoreFisher({fisherDiagonal:e.fisherDiagonal,optimalParams:e.optimalParams,baseWeights:e.baseWeights,requestCount:e.requestCount}),ai.info("Three-loop engine restored Fisher state from SQLite",{domain:this.config.domain,requestCount:e.requestCount,taskBoundaries:e.taskBoundaries}))}else{let r=this._loadRequestCountUnsafe(this.config.domain);if(r!==null){let i=this.baseEngine.getThreeLoopEngine();i&&(i.restoreRequestCount(r),ai.info("Three-loop engine restored request count independently of Fisher state",{domain:this.config.domain,requestCount:r}))}}ai.info("Three-loop engine initialized with Fisher persistence",{domain:this.config.domain})}this.initialized=!0,console.log(`[PersistentSONAEngine] Initialized: domain=${this.config.domain}`)}catch(t){throw this.initPromise=null,new Error(`Failed to initialize PersistentSONAEngine: ${P(t)}`)}}ensureSchema(){if(!this.db)throw new Error("Database not initialized");this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='sona_patterns'").get()||(console.log("[PersistentSONAEngine] Creating sona_patterns table"),this.db.exec(Vp)),this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='sona_fisher_matrices'").get()||(console.log("[PersistentSONAEngine] Creating sona_fisher_matrices table"),this.db.exec(zp))}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("getById",this.db.prepare("SELECT * FROM sona_patterns WHERE id = ?")),this.prepared.set("getByDomain",this.db.prepare(`
2140
+ `,Wl={loadOnInit:!0,autoSaveInterval:0,maxPatternsToLoad:1e4,enableCrossProcessSharing:!0},ca=class{baseEngine;config;persistence=null;db=null;prepared=new Map;initialized=!1;initPromise=null;pendingSaves=new Map;saveTimer=null;consecutiveSaveFailures=0;serverClient=null;constructor(t){this.config={...Wl,...t},this.baseEngine=new $m(t),this.serverClient=t.serverClient??null}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{this.persistence=Ss(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.ensureSchema(),this.prepareStatements(),this.config.loadOnInit&&await this.loadPatterns();let{isSONAThreeLoopEnabled:t}=await import("./feature-flags-DKXMDVPE.js");if(t()){this.baseEngine.initThreeLoopEngine(),this.baseEngine.setFisherPersistence((r,i,n,s,a)=>{this.saveFisherMatrix(r,i,n,s,a)},this.config.domain);let e=this._loadFisherMatrixUnsafe(this.config.domain);if(e){let r=this.baseEngine.getThreeLoopEngine();r&&(r.restoreFisher({fisherDiagonal:e.fisherDiagonal,optimalParams:e.optimalParams,baseWeights:e.baseWeights,requestCount:e.requestCount}),ai.info("Three-loop engine restored Fisher state from SQLite",{domain:this.config.domain,requestCount:e.requestCount,taskBoundaries:e.taskBoundaries}))}else{let r=this._loadRequestCountUnsafe(this.config.domain);if(r!==null){let i=this.baseEngine.getThreeLoopEngine();i&&(i.restoreRequestCount(r),ai.info("Three-loop engine restored request count independently of Fisher state",{domain:this.config.domain,requestCount:r}))}}ai.info("Three-loop engine initialized with Fisher persistence",{domain:this.config.domain})}this.initialized=!0,console.log(`[PersistentSONAEngine] Initialized: domain=${this.config.domain}`)}catch(t){throw this.initPromise=null,new Error(`Failed to initialize PersistentSONAEngine: ${P(t)}`)}}ensureSchema(){if(!this.db)throw new Error("Database not initialized");this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='sona_patterns'").get()||(console.log("[PersistentSONAEngine] Creating sona_patterns table"),this.db.exec(Vp)),this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='sona_fisher_matrices'").get()||(console.log("[PersistentSONAEngine] Creating sona_fisher_matrices table"),this.db.exec(zp))}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("getById",this.db.prepare("SELECT * FROM sona_patterns WHERE id = ?")),this.prepared.set("getByDomain",this.db.prepare(`
2141
2141
  SELECT * FROM sona_patterns
2142
2142
  WHERE domain = ?
2143
2143
  ORDER BY confidence DESC, updated_at DESC
@@ -2269,7 +2269,7 @@ Individual assessments:`),t.forEach(s=>{let a=this.countsAsAgreement(s)?"\u2713
2269
2269
  `))}async getQValue(t,e,r,i){this.ensureInitialized();let n=this.prepared.get("getQValue");if(!n)throw new Error("Statement not prepared");let s=i??this.config.defaultAlgorithm;return n.get(t,e,r,s)?.q_value??0}async setQValue(t,e,r,i,n,s){this.ensureInitialized();let a=this.prepared.get("upsertQValue");if(!a)throw new Error("Statement not prepared");let o=w(),l=s?.algorithm??this.config.defaultAlgorithm;a.run(o,l,t,e,r,i,n??null,s?.domain??null)}async incrementVisits(t,e,r,i){this.ensureInitialized();let n=this.prepared.get("incrementVisits");if(!n)throw new Error("Statement not prepared");let s=i??this.config.defaultAlgorithm;n.run(t,e,r,s)}async getTopActions(t,e,r=10,i){this.ensureInitialized();let n=this.prepared.get("getTopActions");if(!n)throw new Error("Statement not prepared");let s=i??this.config.defaultAlgorithm;return n.all(t,e,s,r).map(o=>this.rowToEntry(o))}async exportForAgent(t,e){this.ensureInitialized();let r=this.prepared.get("getAllForAgent");if(!r)throw new Error("Statement not prepared");let i=e??this.config.defaultAlgorithm,n=r.all(t,i),s=new Map;for(let a of n){let o=a.state_key,l=a.action_key,u=a.q_value;s.has(o)||s.set(o,new Map),s.get(o).set(l,u)}return s}async importFromMap(t,e,r){if(this.ensureInitialized(),!this.db)throw new Error("Database not initialized");let i=this.prepared.get("upsertQValue");if(!i)throw new Error("Statement not prepared");let n=r?.algorithm??this.config.defaultAlgorithm;this.db.transaction(()=>{for(let[a,o]of e)for(let[l,u]of o){let d=w();i.run(d,n,t,a,l,u,null,r?.domain??null)}})()}async pruneOldEntries(t){this.ensureInitialized();let e=this.prepared.get("pruneOld");if(!e)throw new Error("Statement not prepared");return e.run(t).changes}async getStats(){this.ensureInitialized();let t=this.prepared.get("getStats"),e=this.prepared.get("countByAlgorithm"),r=this.prepared.get("countByDomain");if(!t||!e||!r)throw new Error("Statements not prepared");let i=t.get(),n=e.all(),s=r.all(),a={};for(let l of n)a[l.algorithm]=l.count;let o={};for(let l of s)l.domain&&(o[l.domain]=l.count);return{totalEntries:i.total_entries,uniqueAgents:i.unique_agents,uniqueStates:i.unique_states,byAlgorithm:a,byDomain:o,averageVisits:i.avg_visits??0,averageQValue:i.avg_q_value??0,oldestEntry:i.oldest_entry?new Date(i.oldest_entry):null,newestEntry:i.newest_entry?new Date(i.newest_entry):null}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}async getEntry(t,e,r,i){this.ensureInitialized();let n=this.prepared.get("getEntry");if(!n)throw new Error("Statement not prepared");let s=i??this.config.defaultAlgorithm,a=n.get(t,e,r,s);return a?this.rowToEntry(a):null}async deleteEntry(t,e,r,i){this.ensureInitialized();let n=this.prepared.get("deleteEntry");if(!n)throw new Error("Statement not prepared");let s=i??this.config.defaultAlgorithm;return n.run(t,e,r,s).changes>0}isInitialized(){return this.initialized}getDbPath(){return this.persistence?.getDbPath()??""}ensureInitialized(){if(!this.initialized)throw new Error("QValueStore not initialized. Call initialize() first.")}rowToEntry(t){return{id:t.id,algorithm:t.algorithm,agentId:t.agent_id,stateKey:t.state_key,actionKey:t.action_key,qValue:t.q_value,visits:t.visits,lastReward:t.last_reward,domain:t.domain,createdAt:new Date(t.created_at),updatedAt:new Date(t.updated_at)}}};X();_();var Gp=x.create("rl-base-algorithm"),jp={learningRate:.001,discountFactor:.99,episodes:1e3,maxSteps:1e3,batchSize:32,replayBufferSize:1e4,targetUpdateFrequency:100,explorationRate:.3,explorationDecay:.995,minExplorationRate:.01},Iw={enabled:!1,autoSaveInterval:10},ve=class{constructor(t,e,r={},i=[],n={}){this.type=t;this.category=e;this.config={...jp,...r},this.rewardSignals=i,this.persistenceConfig={...Iw,...n},this.stats=this.createInitialStats()}type;category;config;stats;replayBuffer=[];episodeCount=0;totalReward=0;rewardHistory=[];initialized=!1;rewardSignals=[];persistenceConfig;qValueStore=null;lastSaveEpisode=0;enablePersistence(t,e){this.persistenceConfig.enabled=!0,this.persistenceConfig.agentId=t,e&&(this.persistenceConfig.dbPath=e)}isPersistenceEnabled(){return this.persistenceConfig.enabled&&!!this.persistenceConfig.agentId}getPersistenceAgentId(){return this.persistenceConfig.agentId}async train(t){if(this.addToReplayBuffer(t),this.replayBuffer.length>=this.config.batchSize){let e=this.sampleBatch();return this.trainBatch(e)}return this.getStats()}async trainBatch(t){this.initialized||await this.initialize();let e=Date.now();try{this.episodeCount++;let r=t.reduce((n,s)=>n+s.reward,0);this.totalReward+=r,this.rewardHistory.push(r),this.rewardHistory.length>1e3&&this.rewardHistory.shift();let i=await this.trainCore(t);return this.stats={...i,episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((n,s)=>n+s,0)/this.rewardHistory.length,trainingTimeMs:Date.now()-e,timestamp:new Date},this.config.explorationRate=Math.max(this.config.minExplorationRate,this.config.explorationRate*this.config.explorationDecay),this.stats.explorationRate=this.config.explorationRate,await this.autoSaveToPersistence(),this.stats}catch(r){throw new ua(`Training failed for ${this.type}: ${r.message}`,this.type,r)}}async autoSaveToPersistence(){if(!this.isPersistenceEnabled()||this.persistenceConfig.autoSaveInterval<=0)return;if(this.episodeCount-this.lastSaveEpisode>=this.persistenceConfig.autoSaveInterval)try{await this.saveToStore(this.persistenceConfig.agentId,this.qValueStore??void 0),this.lastSaveEpisode=this.episodeCount}catch(e){console.warn(`[${this.type}] Auto-save failed:`,e.message)}}async update(t){let e={...this.config};if(this.config={...this.config,...t},this.config.learningRate<=0||this.config.learningRate>1)throw new jt(`Invalid learning rate: ${this.config.learningRate}`,this.type);if(this.config.discountFactor<0||this.config.discountFactor>1)throw new jt(`Invalid discount factor: ${this.config.discountFactor}`,this.type);if(this.config.explorationRate<0||this.config.explorationRate>1)throw new jt(`Invalid exploration rate: ${this.config.explorationRate}`,this.type);await this.handleConfigUpdate(e,this.config)}getStats(){return{...this.stats}}async reset(){this.isPersistenceEnabled()&&this.episodeCount>0&&await this.saveToStore(this.persistenceConfig.agentId,this.qValueStore??void 0),this.replayBuffer=[],this.episodeCount=0,this.totalReward=0,this.rewardHistory=[],this.lastSaveEpisode=0,this.config.explorationRate=jp.explorationRate,this.stats=this.createInitialStats(),await this.resetAlgorithm()}async close(){this.isPersistenceEnabled()&&this.episodeCount>this.lastSaveEpisode&&await this.saveToStore(this.persistenceConfig.agentId,this.qValueStore??void 0),this.qValueStore&&(await this.qValueStore.close(),this.qValueStore=null)}async exportModel(){return{type:this.type,category:this.category,version:this.getVersion(),config:this.config,stats:this.stats,replayBufferSize:this.replayBuffer.length,exportedAt:new Date().toISOString(),customData:await this.exportCustomData()}}async importModel(t){if(t.type!==this.type)throw new jt(`Model type mismatch: expected ${this.type}, got ${t.type}`,this.type);if(t.category!==this.category)throw new jt(`Algorithm category mismatch: expected ${this.category}, got ${t.category}`,this.type);t.config&&(this.config={...this.config,...t.config}),t.stats&&(this.stats={...this.stats,...t.stats}),t.customData&&await this.importCustomData(t.customData),this.initialized=!0}getInfo(){let t=this.getAlgorithmInfo();return{...t,stats:this.stats,hyperparameters:{...t.hyperparameters,learningRate:this.config.learningRate,discountFactor:this.config.discountFactor,explorationRate:this.config.explorationRate,batchSize:this.config.batchSize}}}async saveToStore(t,e){let r=e??new Ht;await r.initialize();let i=await this.exportModel();await r.setQValue(t,"__model_state__","__weights__",0,void 0,{algorithm:this.type,domain:JSON.stringify(i)})}async loadFromStore(t,e){let r=e??new Ht;await r.initialize();try{let i=await r.getQValue(t,"__model_state__","__weights__",this.type),n=await r.getEntry(t,"__model_state__","__weights__",this.type);if(!n?.domain)return!1;let s=D(n.domain);return await this.importModel(s),!0}catch(i){return Gp.debug("Model load from store failed",{algorithm:this.type,error:i instanceof Error?i.message:String(i)}),!1}}async storeQValue(t,e,r,i,n,s){let a=s??new Ht;await a.initialize(),await a.setQValue(t,e,r,i,n,{algorithm:this.type})}async retrieveQValue(t,e,r,i){let n=i??new Ht;await n.initialize();try{return await n.getQValue(t,e,r,this.type)}catch(s){return Gp.debug("Q-value retrieval failed",{agentId:t,stateKey:e,actionKey:r,error:s instanceof Error?s.message:String(s)}),null}}calculateReward(t){let e={},r=0,i=[];for(let n of this.rewardSignals){let s=n.calculate(t);e[n.name]=s,r+=s,s!==0&&i.push(`${n.name}: ${s.toFixed(3)} (${n.description})`)}return{totalReward:Math.max(-1,Math.min(1,r)),components:e,reasoning:i.join("; ")||"No reward signals triggered",timestamp:new Date}}addToReplayBuffer(t){this.replayBuffer.push(t),this.replayBuffer.length>this.config.replayBufferSize&&this.replayBuffer.shift()}sampleBatch(t){let e=t||this.config.batchSize,r=this.replayBuffer;if(r.length===0)return[];if(r.length<=e)return[...r];let i=new Set;for(;i.size<Math.min(e,r.length);)i.add(Se(0,r.length));return Array.from(i).map(n=>r[n])}epsilonGreedy(t,e){return z()<this.config.explorationRate?t():e()}normalizeFeatures(t){if(t.length===0)return[];let e=Math.max(...t.map(Math.abs));return e===0?t:t.map(r=>r/e)}stateToKey(t){let e=t.features.map((r,i)=>`${i}:${Math.round(r*100)/100}`).join(",");return`${t.id}|${e}`}async initialize(){this.isPersistenceEnabled()&&(await this.initializePersistence(),await this.loadFromStore(this.persistenceConfig.agentId)&&console.log(`[${this.type}] Loaded persisted state for agent: ${this.persistenceConfig.agentId}`)),this.initialized=!0}async initializePersistence(){this.qValueStore||(this.qValueStore=new Ht,await this.qValueStore.initialize())}async resetAlgorithm(){}async handleConfigUpdate(t,e){}async exportCustomData(){return{}}async importCustomData(t){}getVersion(){return"1.0.0"}createInitialStats(){return{episode:0,totalReward:0,averageReward:0,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}};bs();var Mw={contextLength:10,embeddingDim:384,numHeads:4,numLayers:3,feedForwardDim:256,maxReturn:100},oi=class extends ve{trajectories=[];dtConfig;stateEmbeddings=new Map;actionEmbeddings=new Map;constructor(t={}){super("decision-transformer","offline-rl"),this.dtConfig={...Mw,...t}}async predict(t){this.initialized||await this.initialize();let e=this.retrieveContext(t),r=this.calculateReturnToGo(e),i=this.generateAction(t,e,r),n=this.calculateConfidence(e,r);return{action:i,confidence:n,value:r,reasoning:this.generateReasoning(t,i,e,r)}}async trainCore(t){let e=this.groupIntoTrajectories(t);for(let i of e)this.calculateReturns(i);this.trajectories.push(...e),this.trajectories.length>1e3&&(this.trajectories=this.trajectories.slice(-1e3)),this.updateEmbeddings(e);let r=e.reduce((i,n)=>i+n.returns[n.returns.length-1],0)/e.length;return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:Math.abs(r-this.targetReturn()),explorationRate:0,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"1.0.0",description:"Decision Transformer for Test Case Prioritization",capabilities:["Offline RL from historical data","Attention-based sequence modeling","Return-to-go conditioning","Context-aware decisions"],hyperparameters:{contextLength:this.dtConfig.contextLength,embeddingDim:this.dtConfig.embeddingDim,numHeads:this.dtConfig.numHeads,numLayers:this.dtConfig.numLayers},stats:this.stats}}retrieveContext(t){let e=this.trajectories.map(r=>{let i=this.calculateSimilarity(t,r);return{traj:r,similarity:i}});return e.sort((r,i)=>i.similarity-r.similarity),e.slice(0,this.dtConfig.contextLength).map(r=>r.traj)}calculateSimilarity(t,e){for(let r of e.states)if(this.statesMatch(t,r))return 1;if(e.states.length>0){let r=e.states[e.states.length-1];return Mt(t.features,r.features)}return 0}statesMatch(t,e){return t.id===e.id||Math.abs(t.features[0]-e.features[0])<.1}calculateReturnToGo(t){if(t.length===0)return 0;let e=t.flatMap(r=>r.returns);return e.reduce((r,i)=>r+i,0)/e.length}calculateReturns(t){let e=[],r=0;for(let i=t.rewards.length-1;i>=0;i--)r=t.rewards[i]+this.config.discountFactor*r,e.unshift(r);t.returns=e}targetReturn(){return this.dtConfig.maxReturn*.8}generateAction(t,e,r){for(let i of e)for(let n=0;n<i.states.length;n++)if(this.statesMatch(t,i.states[n])&&i.returns[n]>r*.8)return{...i.actions[n]};return this.getHeuristicAction(t)}getHeuristicAction(t){return{type:"prioritize",value:t.features[0]>.7?"high":"standard",metadata:{heuristic:!0}}}updateEmbeddings(t){for(let e of t){for(let r of e.states)this.stateEmbeddings.has(r.id)||this.stateEmbeddings.set(r.id,this.hashEmbedding(r.id));for(let r of e.actions){let i=this.actionToKey(r);this.actionEmbeddings.has(i)||this.actionEmbeddings.set(i,this.hashEmbedding(i))}}}hashEmbedding(t){let e=[],r=this.dtConfig.embeddingDim;for(let i=0;i<r;i++){let n=this.simpleHash(t+i);e.push((n%200-100)/100)}return e}simpleHash(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return Math.abs(e)}actionToKey(t){return`${t.type}:${JSON.stringify(t.value)}`}groupIntoTrajectories(t){let e=[],r=null;for(let i of t)i.done||!r?(r&&e.push(r),r={states:[i.state],actions:[i.action],rewards:[i.reward],returns:[]}):(r.states.push(i.state),r.actions.push(i.action),r.rewards.push(i.reward));return r&&e.push(r),e}calculateConfidence(t,e){if(t.length===0)return .3;let r=Math.min(1,t.length/this.dtConfig.contextLength),i=Math.min(1,e/this.targetReturn());return .3+r*.4+i*.3}generateReasoning(t,e,r,i){if(r.length===0)return"Decision Transformer: No similar historical contexts, using heuristic";let n=r.reduce((s,a)=>s+a.returns[a.returns.length-1]||0,0)/r.length;return`Decision Transformer: Found ${r.length} similar contexts (avg return: ${n.toFixed(2)}), selecting ${e.type} action with return-to-go ${i.toFixed(2)}`}async exportCustomData(){return{trajectories:this.trajectories,stateEmbeddings:Object.fromEntries(this.stateEmbeddings),actionEmbeddings:Object.fromEntries(this.actionEmbeddings),dtConfig:this.dtConfig}}async importCustomData(t){t.trajectories&&(this.trajectories=t.trajectories),t.stateEmbeddings&&(this.stateEmbeddings=new Map(Object.entries(t.stateEmbeddings))),t.actionEmbeddings&&(this.actionEmbeddings=new Map(Object.entries(t.actionEmbeddings))),t.dtConfig&&(this.dtConfig={...this.dtConfig,...t.dtConfig})}async resetAlgorithm(){this.trajectories=[],this.stateEmbeddings.clear(),this.actionEmbeddings.clear()}};vt();_();var Hp={enabled:!0,coherenceThreshold:.1,blockOnHumanLane:!0,enrichOnRetrievalLane:!0,embeddingDimension:384},Fw=x.create("test-generation/coherence-gate"),da=class extends Error{constructor(e,r,i){super(e);this.contradictions=r;this.lane=i;this.name="CoherenceError"}contradictions;lane},Ul=class{constructor(t=384){this.dimension=t}dimension;async embed(t){let e=new Array(this.dimension).fill(0),r=t.toLowerCase().trim();for(let n=0;n<r.length;n++){let s=r.charCodeAt(n),a=n%this.dimension;e[a]+=Math.sin(s*(n+1)*.1),e[(a+1)%this.dimension]+=Math.cos(s*(n+1)*.1)}let i=Math.sqrt(e.reduce((n,s)=>n+s*s,0));if(i>0)for(let n=0;n<e.length;n++)e[n]/=i;return e}},ma=class{constructor(t,e,r={}){this.coherenceService=t;this.config={...Hp,...r},this.embeddingService=e||new Ul(this.config.embeddingDimension)}coherenceService;config;embeddingService;async checkRequirementCoherence(t){let e=Date.now();if(!this.config.enabled||!this.coherenceService)return this.createPassingResult(e,!0);if(t.length===0)return this.createPassingResult(e,!1);if(t.length===1)return this.createPassingResult(e,!1);try{let r=await this.requirementsToNodes(t),i=await this.coherenceService.checkCoherence(r);return this.transformCoherenceResult(i,t,Date.now()-e)}catch(r){return Fw.error("Coherence check failed:",r instanceof Error?r:void 0),{isCoherent:!0,energy:0,lane:"reflex",contradictions:[],recommendations:[{type:"add-context",requirementId:"",description:"Coherence check failed. Manual review recommended.",suggestedResolution:"Review requirements manually before proceeding."}],durationMs:Date.now()-e,usedFallback:!0}}}async enrichSpecification(t,e){if(e.length===0)return t;let r={...t,requirements:[...t.requirements],context:{...t.context}},i=new Map;for(let n of e)switch(n.type){case"clarify":this.addClarificationNote(i,n);break;case"add-context":r.context={...r.context,coherenceRecommendations:[...r.context?.coherenceRecommendations||[],n.description]};break;case"resolve-ambiguity":this.addDisambiguationNote(i,n);break;case"split-requirement":r.context={...r.context,requirementsSuggestedForSplit:[...r.context?.requirementsSuggestedForSplit||[],n.requirementId]};break}return r.requirements=r.requirements.map(n=>{let s=i.get(n.id);return s?{...n,metadata:{...n.metadata,...s.metadata}}:n}),r.context={...r.context,enrichedAt:new Date().toISOString(),enrichmentCount:e.length},r}async validateAndEnrich(t){let e=await this.checkRequirementCoherence(t.requirements);if(this.config.blockOnHumanLane&&e.lane==="human")return g(new da("Requirements contain unresolvable contradictions that require human review",e.contradictions,e.lane));if(this.config.enrichOnRetrievalLane&&e.lane==="retrieval"){let r=await this.enrichSpecification(t,e.recommendations);return f(r)}return f(t)}isAvailable(){return this.coherenceService?.isInitialized()??!1}async requirementsToNodes(t){let e=[];for(let r of t){let i=await this.embeddingService.embed(r.description);e.push({id:r.id,embedding:i,weight:this.priorityToWeight(r.priority),metadata:{description:r.description,source:r.source,...r.metadata}})}return e}transformCoherenceResult(t,e,r){let i=new Map(e.map(a=>[a.id,a])),n=t.contradictions.map(a=>({requirementId1:a.nodeIds[0],requirementId2:a.nodeIds[1],severity:this.mapSeverity(a.severity),description:a.description,confidence:a.confidence,suggestedResolution:a.resolution||this.generateResolutionSuggestion(i.get(a.nodeIds[0]),i.get(a.nodeIds[1]),a.severity)})),s=this.generateRecommendations(t,n,e);return{isCoherent:t.isCoherent,energy:t.energy,lane:t.lane,contradictions:n,recommendations:s,durationMs:r,usedFallback:t.usedFallback}}generateRecommendations(t,e,r){let i=[];for(let s of t.recommendations)i.push({type:"add-context",requirementId:"",description:s});for(let s of e)s.severity==="critical"||s.severity==="high"?i.push({type:"resolve-ambiguity",requirementId:s.requirementId1,description:`Potential conflict with requirement ${s.requirementId2}: ${s.description}`,suggestedResolution:s.suggestedResolution}):i.push({type:"clarify",requirementId:s.requirementId1,description:`Minor tension with requirement ${s.requirementId2}: ${s.description}`});let n=r.filter(s=>s.description.length>200||s.description.includes(" and ")&&s.description.includes(" or "));for(let s of n)i.push({type:"split-requirement",requirementId:s.id,description:"Complex requirement may benefit from splitting into smaller, focused requirements"});return i}generateResolutionSuggestion(t,e,r){return!t||!e?"Review and reconcile conflicting requirements.":r==="critical"?`Requirements "${t.id}" and "${e.id}" appear to be mutually exclusive. Consider removing one or explicitly documenting the conditions under which each applies.`:r==="high"?`Requirements "${t.id}" and "${e.id}" may conflict. Add clarification about their relationship and precedence.`:`Minor tension between "${t.id}" and "${e.id}". Consider adding context to clarify their relationship.`}createPassingResult(t,e){return{isCoherent:!0,energy:0,lane:"reflex",contradictions:[],recommendations:[],durationMs:Date.now()-t,usedFallback:e}}priorityToWeight(t){switch(t){case"high":return 1;case"medium":return .7;case"low":return .4;default:return .5}}mapSeverity(t){switch(t){case"critical":return"critical";case"high":return"high";case"medium":return"medium";default:return"low"}}addClarificationNote(t,e){let r=t.get(e.requirementId)||{metadata:{}},i=r.metadata?.clarificationNotes||[];i.push(e.description),t.set(e.requirementId,{...r,metadata:{...r.metadata,clarificationNotes:i,needsClarification:!0}})}addDisambiguationNote(t,e){let r=t.get(e.requirementId)||{metadata:{}},i=r.metadata?.disambiguationNotes||[];i.push(e.description),t.set(e.requirementId,{...r,metadata:{...r.metadata,disambiguationNotes:i,needsDisambiguation:!0,suggestedResolution:e.suggestedResolution}})}};function Ql(c,t,e){return new ma(c,t,e)}var Lw={maxConcurrentWorkflows:5,defaultTimeout:6e4,enablePatternLearning:!0,publishEvents:!0,enableQESONA:!0,enableFlashAttention:!0,enableDecisionTransformer:!0,sonaPatternType:"test-generation",flashAttentionWorkload:"test-similarity",enableCoherenceGate:!0,blockOnIncoherentRequirements:!0,enrichOnRetrievalLane:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2,enableFreeTier:!1},Z=x.create("test-generation");function $w(c){let t=c.match(/```(?:[a-zA-Z0-9]+)?\n([\s\S]*?)\n```/);return(t?t[1]:c).trim()}function Ow(c){return c.replace(/\.([cm]?[jt]sx?)$/,".test.$1")}var Ln=class extends ie{constructor(e,r,i,n={},s,a,o,l){let u={...Lw,...n};super(e,"test-generation",u,{verifyFindingTypes:["test-pattern-selection","mock-strategy","edge-case-generation","assertion-strategy"],...u.consensusConfig});this.memory=r;this.agentCoordinator=i;this.coherenceService=a;this.hookRegistry=o;this.testGenerator=Sr({memory:r,llmRouter:s}),this.patternMatcher=new Rr(r),this.freeTierExecutor=ln({config:this.config,agentType:"qe-test-architect",taskKind:"test-generation",llmRouter:s,routingFeedback:l,logger:Z}),this.config.enableCoherenceGate&&a&&(this.coherenceGate=Ql(a,void 0,{enabled:!0,blockOnHumanLane:this.config.blockOnIncoherentRequirements,enrichOnRetrievalLane:this.config.enrichOnRetrievalLane}))}memory;agentCoordinator;coherenceService;hookRegistry;testGenerator;patternMatcher;freeTierExecutor=null;qesona=null;flashAttention=null;decisionTransformer=null;testEmbeddings=new Map;recentDreamInsights=[];coherenceGate=null;async onInitialize(){if(this.config.enableQESONA)try{this.qesona=await De({domain:"test-generation",loadOnInit:!0,autoSaveInterval:6e4,patternClusters:50,minConfidence:.5}),Z.info("PersistentSONAEngine initialized for test-generation domain")}catch(e){Z.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),Z.warn("Continuing without SONA pattern persistence"),this.qesona=null}if(this.config.enableFlashAttention)try{this.flashAttention=await tt(this.config.flashAttentionWorkload,{dim:384,strategy:"flash",blockSize:64}),Z.info("QEFlashAttention initialized for test-similarity")}catch{Z.warn("QEFlashAttention unavailable (optional native module), continuing without it"),this.flashAttention=null}if(this.config.enableDecisionTransformer)try{this.decisionTransformer=new oi({contextLength:10,embeddingDim:384}),Z.info("DecisionTransformer created for test case selection")}catch{Z.warn("DecisionTransformer unavailable (optional native module), continuing without it"),this.decisionTransformer=null}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState(),this.flashAttention&&(this.flashAttention.dispose(),this.flashAttention=null),this.decisionTransformer&&(await this.decisionTransformer.reset(),this.decisionTransformer=null),this.qesona&&(await this.qesona.close(),this.qesona=null),this.testEmbeddings.clear()}getActiveWorkflows(){return super.getActiveWorkflows()}async generateTests(e){let r=w();try{if(this.startWorkflow(r,"generate"),this.freeTierExecutor&&!e.behaviorExamples?.length)try{let l=await this.tryFreeTierGeneration(e);if(l)return this.completeWorkflow(r),Z.info(`Free-tier local generation produced ${l.tests.length} test file(s); skipped paid path`),f(l)}catch{Z.debug("Free-tier generation failed; falling back to the normal path")}if(this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Z.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return g(new Error("Test generation paused: topology is in critical state"));let i=[];if(this.hookRegistry)try{let l=e.sourceFiles?.[0]||"",u=await this.hookRegistry.emit(Lm.PreTestGeneration,{targetFile:l,testType:e.testType,framework:e.framework,language:l.split(".").pop()||"typescript"});for(let d of u)d.success&&d.data?.patterns&&i.push(...d.data.patterns),d.guidance&&Z.info(`Hook guidance: ${d.guidance.join("; ")}`)}catch{Z.debug("PreTestGeneration hook failed:")}if(!this.agentCoordinator.canSpawn())return g(new Error("Agent limit reached, cannot spawn test generation agents"));let n=await this.spawnTestGeneratorAgent(r,e);if(!n.success)return this.failWorkflow(r,n.error.message),g(n.error);this.addAgentToWorkflow(r,n.value);let s=[...e.patterns||[],...i];if(this.config.enableQESONA&&this.qesona){let l=await this.adaptTestGenerationPatterns(e);l.length>0&&(s=l,Z.info(`Adapted ${l.length} patterns using QESONA`))}let a=s;if(this.config.enablePatternLearning&&a.length===0){let l=await this.patternMatcher.findMatchingPatterns({testType:e.testType,framework:e.framework});l.success&&l.value.length>0&&(a=l.value.map(u=>u.pattern.id))}let o=await this.testGenerator.generateTests({...e,patterns:a});if(o.success){if(this.completeWorkflow(r),this.config.enableFlashAttention&&this.flashAttention){let u=await this.findSimilarTests(o.value.tests);u.length>0&&Z.info(`Found ${u.length} similar tests using Flash Attention`)}if(this.config.enableDecisionTransformer&&this.decisionTransformer){let u=await this.prioritizeTestCases(o.value.tests,e);Z.info(`Prioritized ${u.length} tests using DecisionTransformer`)}if(this.config.publishEvents){await this.publishTestSuiteCreated(o.value,e);for(let u of o.value.tests)await this.publishTestGenerated(u,e.framework??"vitest",o.value.patternsUsed)}let l=o.value.coverageEstimate;if(l!==null&&dr()&&this.qesona?.isThreeLoopEnabled()){let u=o.value;this.qesona.instantAdapt([u.tests.length/20,l/100,u.patternsUsed.length/10,e.sourceFiles.length/20,(e.coverageTarget??80)/100,u.tests.filter(d=>d.type==="unit").length/20]);try{if(this.qesona.recordOutcome(1),this.qesona.shouldConsolidate())try{this.qesona.backgroundConsolidate()}catch{}}catch{}}this.config.enableQESONA&&this.qesona&&await this.storeTestGenerationPattern(o.value,e),this.config.enablePatternLearning&&await this.learnFromGeneration(o.value)}else this.failWorkflow(r,o.error.message),this.config.publishEvents&&await this.publishGenerationFailed(o.error,"generateTests");return await this.agentCoordinator.stop(n.value),o}catch(i){let n=y(i);return this.failWorkflow(r,n.message),this.config.publishEvents&&await this.publishGenerationFailed(n,"generateTests"),{success:!1,error:n}}}async tryFreeTierGeneration(e){if(!this.freeTierExecutor||!e.sourceFiles||e.sourceFiles.length!==1)return null;let r=e.sourceFiles[0];if(!r)return null;let i="";try{i=await Re(r,{outsideRoot:"allow"})}catch{return null}if(!i.trim())return null;let n=e.framework??"vitest",s=[{role:"system",content:`You write ${n} tests. Output ONLY a single fenced code block \u2014 no prose.`},{role:"user",content:`Write ${n} ${e.testType??"unit"} tests for this file (aim for ~${e.coverageTarget??80}% coverage). Use real assertions.
2270
2270
 
2271
2271
  \`\`\`
2272
- `+i.slice(0,6e3)+"\n```"}],a=m=>{let p=/\b(test|it|describe)\s*\(/.test(m),h=/\b(expect|assert)\s*\(/.test(m);return p&&h?{passed:!0}:{passed:!1,feedback:"output must contain a test (test/it/describe) with an assertion (expect/assert)"}},o=await this.freeTierExecutor.execute({agentId:`test-gen:${r}`,messages:s,verify:a,escalate:!0,bestOfK:this.config.freeTierBestOfK??2,repairAttempts:this.config.freeTierRepairAttempts??1});if(!o.ok)return null;let l=$w(o.content),u=(l.match(/\b(?:expect|assert)\s*\(/g)??[]).length;return u===0?null:{tests:[{id:w(),name:`free-tier:${r.split("/").pop()??r}`,sourceFile:r,testFile:Ow(r),testCode:l,type:e.testType??"unit",assertions:u,framework:n,llmEnhanced:!0}],coverageEstimate:null,patternsUsed:["free-tier-local",`tier:${o.tierUsed}`]}}async generateTDDTests(e){let r=w();try{this.startWorkflow(r,"tdd");let i=await this.spawnTDDAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),g(i.error);this.addAgentToWorkflow(r,i.value);let n=await this.testGenerator.generateTDDTests(e);return n.success?(this.completeWorkflow(r),this.updateWorkflowProgress(r,this.getTDDProgress(e.phase))):this.failWorkflow(r,n.error.message),await this.agentCoordinator.stop(i.value),n}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async generatePropertyTests(e){let r=w();try{this.startWorkflow(r,"property");let i=await this.spawnPropertyTestAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),g(i.error);this.addAgentToWorkflow(r,i.value);let n=await this.testGenerator.generatePropertyTests(e);return n.success?this.completeWorkflow(r):this.failWorkflow(r,n.error.message),await this.agentCoordinator.stop(i.value),n}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async generateTestData(e){let r=w();try{this.startWorkflow(r,"data");let i=await this.testGenerator.generateTestData(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async learnPatterns(e){let r=w();try{this.startWorkflow(r,"learn");let i=await this.patternMatcher.learnPatterns(e);return i.success?(this.completeWorkflow(r),this.config.publishEvents&&await this.publishPatternLearned(i.value)):this.failWorkflow(r,i.error.message),i}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async spawnTestGeneratorAgent(e,r){let i={name:`test-generator-${e.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["test-generation",r.testType,r.framework??"vitest"],config:{workflowId:e,sourceFiles:r.sourceFiles,coverageTarget:r.coverageTarget}};return this.agentCoordinator.spawn(i)}async spawnTDDAgent(e,r){let i={name:`tdd-agent-${e.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["tdd",r.framework,r.phase],config:{workflowId:e,feature:r.feature,behavior:r.behavior}};return this.agentCoordinator.spawn(i)}async spawnPropertyTestAgent(e,r){let i={name:`property-test-agent-${e.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["property-testing","fast-check"],config:{workflowId:e,function:r.function,properties:r.properties}};return this.agentCoordinator.spawn(i)}async publishTestGenerated(e,r,i){let n={testId:e.id,testFile:e.testFile,framework:r,sourceFile:e.sourceFile,testType:e.type,patternsUsed:i},s=N(Ki.TestGenerated,"test-generation",n);await this.eventBus.publish(s)}async publishTestSuiteCreated(e,r){let i={suiteId:w(),testCount:e.tests.length,sourceFiles:r.sourceFiles,coverageEstimate:e.coverageEstimate},n=N(Ki.TestSuiteCreated,"test-generation",i);await this.eventBus.publish(n)}async publishPatternLearned(e){let r=N(Ki.PatternLearned,"test-generation",{patternCount:e.patterns.length,confidence:e.confidence,patternIds:e.patterns.map(i=>i.id)});await this.eventBus.publish(r)}async publishGenerationFailed(e,r){let i=N(Ki.GenerationFailed,"test-generation",{error:e.message,context:r,timestamp:new Date().toISOString()});await this.eventBus.publish(i)}getTDDProgress(e){switch(e){case"red":return 33;case"green":return 66;case"refactor":return 100;default:return 0}}subscribeToEvents(){this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGapDetected.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.subscribeToDreamEvents()}subscribeToDreamEvents(){this.eventBus.subscribe(bt.DreamCycleCompleted,this.handleDreamCycleCompleted.bind(this))}async handleDreamCycleCompleted(e){let{insights:r,cycleId:i}=e.payload;if(!r||r.length===0)return;let n=r.filter(s=>{let a=s.suggestedAction?.toLowerCase().includes(this.domainName)||s.suggestedAction?.toLowerCase().includes("test")||s.suggestedAction?.toLowerCase().includes("coverage"),o=s.sourceConcepts.some(u=>u.toLowerCase().includes("test")||u.toLowerCase().includes(this.domainName)||u.toLowerCase().includes("coverage")||u.toLowerCase().includes("edge-case")),l=s.type==="optimization"||s.type==="gap_detection"||s.type==="novel_association";return a||o||l&&s.actionable});if(n.length!==0){Z.info(`[${this.domainName}] Received ${n.length} relevant dream insights from cycle ${i}`);for(let s of n)s.confidenceScore>.7&&s.actionable&&await this.applyDreamInsight(s,i),this.recentDreamInsights.push({...s,receivedAt:new Date});this.recentDreamInsights.length>50&&(this.recentDreamInsights=this.recentDreamInsights.slice(-50))}}async applyDreamInsight(e,r){if(Z.info(`[${this.domainName}] Applying dream insight: ${e.description.slice(0,100)}...`),this.qesona)try{let i={id:`dream-insight-${e.id}`,features:this.encodeInsightAsFeatures(e),metadata:{insightType:e.type,cycleId:r,sourceConcepts:e.sourceConcepts}},n={type:"dream-insight",value:e.suggestedAction||e.description},s=this.qesona.createPattern(i,n,{reward:e.confidenceScore,success:!0,quality:e.noveltyScore},"dream-derived",this.domainName,{insightId:e.id,cycleId:r,description:e.description,suggestedAction:e.suggestedAction});Z.info(`[${this.domainName}] Created SONA pattern ${s.id} from dream insight`)}catch(i){Z.error(`[${this.domainName}] Failed to store dream insight pattern`,i instanceof Error?i:void 0)}await this.memory.set(`${this.domainName}:dream-insight:${e.id}`,{insight:e,cycleId:r,appliedAt:new Date().toISOString()},{namespace:this.domainName,ttl:86400*7})}getRecentDreamInsights(e){let r=Date.now()-864e5;return this.recentDreamInsights.filter(i=>{let n=i.receivedAt.getTime()>r,s=!e||i.type===e;return n&&s})}async enhanceWithDreamInsights(e){let r=[],n=this.getRecentDreamInsights().filter(s=>(s.type==="novel_association"||s.type==="gap_detection")&&s.actionable&&s.confidenceScore>.6);for(let s of n)s.suggestedAction&&(e.sourceFiles.some(o=>s.sourceConcepts.some(l=>o.toLowerCase().includes(l.toLowerCase())))||s.suggestedAction.toLowerCase().includes(e.testType))&&r.push(s.suggestedAction);return r.slice(0,5)}encodeInsightAsFeatures(e){let r=[],i={pattern_merge:.2,novel_association:.4,optimization:.6,gap_detection:.8};for(r.push(i[e.type]||.5),r.push(e.confidenceScore),r.push(e.noveltyScore),r.push(e.actionable?1:0),r.push(Math.min(1,e.sourceConcepts.length/10));r.length<384;)r.push(0);return r.slice(0,384)}async handleCoverageGapDetected(e){if(!He(e.payload))return;let r=e.payload,i=await this.testGenerator.generateForCoverageGap(r.file,r.uncoveredLines,"jest");if(i.success&&i.value.length>0)for(let n of i.value)await this.publishTestGenerated(n,"jest")}async handleTestRunCompleted(e){}async learnFromGeneration(e){let r=e.patternIds??[];if(r.length!==0)try{let{getUnifiedMemory:i}=await import("./unified-memory-AGDZQ5XD.js"),{recordPatternUsage:n}=await import("./pattern-usage-recorder-ESR42RME.js"),s=i().getDatabase();for(let a of r)n(s,{patternId:a,success:!0})}catch(i){Z.warn("Pattern usage recording skipped",{error:i instanceof Error?i.message:String(i)})}}async adaptTestGenerationPatterns(e){if(!this.qesona)return[];try{let r={id:`test-gen-${Date.now()}`,features:this.encodeRequestAsFeatures(e),metadata:{testType:e.testType,framework:e.framework,sourceFileCount:e.sourceFiles.length}},i=await this.qesona.adaptPattern(r,this.config.sonaPatternType,"test-generation");return i.success&&i.pattern?(Z.info(`QESONA adapted pattern with ${i.similarity.toFixed(3)} similarity in ${i.adaptationTimeMs.toFixed(2)}ms`),[i.pattern.id]):[]}catch(r){return Z.error("QESONA pattern adaptation failed:",r instanceof Error?r:void 0),[]}}async storeTestGenerationPattern(e,r){if(!(!this.qesona||e.coverageEstimate===null))try{let i={id:`test-gen-${Date.now()}`,features:this.encodeRequestAsFeatures(r),metadata:{testCount:e.tests.length,coverageEstimate:e.coverageEstimate,success:!0}},n={type:"generate-tests",value:{testType:r.testType,framework:r.framework,patternsUsed:e.patternsUsed}},s=this.qesona.createPattern(i,n,{reward:e.coverageEstimate/100,success:!0,quality:e.coverageEstimate/100},this.config.sonaPatternType,"test-generation",{testCount:e.tests.length,framework:r.framework,testType:r.testType});Z.info(`Stored test generation pattern ${s.id} in QESONA`)}catch(i){Z.error("Failed to store pattern in QESONA:",i instanceof Error?i:void 0)}}async findSimilarTests(e){if(!this.flashAttention)return[];let r=[];try{for(let n of e){let s=this.generateTestEmbedding(n);this.testEmbeddings.set(n.id,s)}let i=await this.loadExistingTestEmbeddings();if(i.length===0)return[];for(let n of e){let s=this.testEmbeddings.get(n.id);if(!s)continue;let o=(await this.flashAttention.computeTestSimilarity(s,i.map(l=>l.embedding),5)).filter(l=>l.similarity>.7).map(l=>({testId:i[l.index].testId,similarity:l.similarity}));o.length>0&&r.push({test:n,similarTests:o})}return r}catch(i){return Z.error("Flash Attention similarity detection failed:",i instanceof Error?i:void 0),[]}}async prioritizeTestCases(e,r){if(!this.decisionTransformer)return e;try{let i={id:`prioritize-${Date.now()}`,features:[e.length/100,(r.coverageTarget||80)/100,r.testType==="unit"?.2:r.testType==="integration"?.5:.8,r.framework==="jest"?.3:r.framework==="vitest"?.4:.5],metadata:{testCount:e.length,framework:r.framework,testType:r.testType}},n=await this.decisionTransformer.predict(i);return Z.info(`DecisionTransformer prediction: ${n.reasoning}`),n.confidence>.7?e.sort((s,a)=>a.assertions-s.assertions):e}catch(i){return Z.error("DecisionTransformer prioritization failed:",i instanceof Error?i:void 0),e}}getQESONAStats(){return this.qesona?this.qesona.getStats():null}getFlashAttentionMetrics(){return this.flashAttention?this.flashAttention.getMetrics():null}async checkRequirementCoherence(e){return this.coherenceGate?this.coherenceGate.checkRequirementCoherence(e):{isCoherent:!0,energy:0,lane:"reflex",contradictions:[],recommendations:[],durationMs:0,usedFallback:!0}}isCoherenceGateAvailable(){return this.coherenceGate?.isAvailable()??!1}async verifyAndEnrichSpec(e){if(!this.coherenceGate||!this.config.enableCoherenceGate)return e;let r=await this.coherenceGate.validateAndEnrich(e);if(r.success)return r.value;throw r.error}async verifyTestPatternSelection(e,r){let i=U({id:w(),type:"test-pattern-selection",confidence:r,description:`Verify test pattern: ${e.name} (${e.type})`,payload:e,detectedBy:"test-generation-coordinator",severity:r>.9?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Z.info(`Test pattern '${e.name}' verified by consensus`),!0):(Z.warn(`Test pattern '${e.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyMockStrategy(e,r){let i=U({id:w(),type:"mock-strategy",confidence:r,description:`Verify mock strategy for ${e.target}: ${e.mockType}`,payload:e,detectedBy:"test-generation-coordinator",severity:r>.85?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Z.info(`Mock strategy for '${e.target}' verified by consensus`),!0):(Z.warn(`Mock strategy for '${e.target}' NOT verified`),!1)}return!0}async verifyEdgeCaseGeneration(e,r){let i=U({id:w(),type:"edge-case-generation",confidence:r,description:`Verify edge case: ${e.description}`,payload:e,detectedBy:"test-generation-coordinator",severity:"high"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Z.info(`Edge case '${e.description.slice(0,50)}...' verified by consensus`),!0):(Z.warn(`Edge case NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}encodeRequestAsFeatures(e){let r=[];for(r.push(e.testType==="unit"?.2:e.testType==="integration"?.5:.8),r.push(e.framework==="jest"?.25:e.framework==="vitest"?.5:e.framework==="mocha"?.75:.9),r.push(Math.min(1,e.sourceFiles.length/50)),r.push((e.coverageTarget||80)/100);r.length<384;)r.push(0);return r.slice(0,384)}generateTestEmbedding(e){let r=[],i=this.simpleHash(e.name);for(let n=0;n<64;n++)r.push((i>>n%32&1)*2-1);for(r.push(e.type==="unit"?.2:e.type==="integration"?.5:.8),r.push(Math.min(1,e.assertions/20));r.length<384;)r.push(0);return new Float32Array(r.slice(0,384))}async loadExistingTestEmbeddings(){try{let e=await this.memory.search("test-embedding:*",1e3),r=[];for(let i of e){let n=await this.memory.get(i);n&&r.push({testId:n.testId,embedding:new Float32Array(n.embedding)})}return r}catch{return[]}}simpleHash(e){let r=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);r=(r<<5)-r+n,r=r|0}return Math.abs(r)}async loadWorkflowState(){let e=await this.memory.get("test-generation:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("test-generation:coordinator:workflows",e,{namespace:"test-generation",persist:!0})}};k();var pa=class extends te{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;testGenerator=null;patternMatcher=null;pluginConfig;get name(){return"test-generation"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{generateTests:this.generateTests.bind(this),generateTDDTests:this.generateTDDTests.bind(this),generatePropertyTests:this.generatePropertyTests.bind(this),generateTestData:this.generateTestData.bind(this),learnPatterns:this.learnPatterns.bind(this),getCoordinator:()=>this.coordinator,getTestGenerator:()=>this.testGenerator,getPatternMatcher:()=>this.patternMatcher}}getTaskHandlers(){return new Map([["generate-tests",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.testType,i=e.framework;if(!Array.isArray(e.sourceFiles)||e.sourceFiles.length===0)return g(new Error("Invalid generate-tests payload: missing sourceFiles"));let n=await Ft("generate-tests","sourceFiles",e.sourceFiles,{maxBytes:Ur});if(!n.success)return n;let a={sourceFiles:n.value,testType:r??"unit",framework:i??"vitest",coverageTarget:e.coverageTarget,patterns:e.patterns};return this.coordinator.generateTests(a)}],["generate-tdd-tests",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.feature,i=e.behavior,n=e.framework,s=e.phase;return!r||!i?g(new Error("Invalid generate-tdd-tests payload: missing feature or behavior")):this.coordinator.generateTDDTests({feature:r,behavior:i,framework:n??"vitest",phase:s??"red"})}],["generate-property-tests",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.function,i=e.properties;return!r||!i||i.length===0?g(new Error("Invalid generate-property-tests payload: missing function or properties")):this.coordinator.generatePropertyTests({function:r,properties:i,constraints:e.constraints})}],["generate-test-data",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.schema,i=e.count;return r?this.coordinator.generateTestData({schema:r,count:i??10,locale:e.locale,preserveRelationships:e.preserveRelationships}):g(new Error("Invalid generate-test-data payload: missing schema"))}]])}async onInitialize(){this.testGenerator=Sr({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.testGenerator),this.patternMatcher=new Rr(this.memory,this.pluginConfig.patternMatcher);let e;if(this.pluginConfig.coordinator?.enableFreeTier===!0||process.env.AQE_FREE_TIER==="1"){e=new Is(1e4,{enableEMACalibration:!0,enableAutoEscalation:!0});try{await e.initialize()}catch{}}this.coordinator=new Ln(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter,void 0,void 0,e),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.testGenerator=null,this.patternMatcher=null}subscribeToEvents(){this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this)),this.eventBus.subscribe("learning-optimization.PatternConsolidated",this.handlePatternConsolidation.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;case"code-intelligence.ImpactAnalysisCompleted":await this.handleImpactAnalysis(e);break;default:break}}async generateTests(e){this.ensureInitialized();try{let r=await this.coordinator.generateTests(e);return r.success?this.trackSuccessfulGeneration(r.value):this.trackFailedGeneration(r.error),r}catch(r){return this.handleError(r)}}async generateTDDTests(e){this.ensureInitialized();try{return await this.coordinator.generateTDDTests(e)}catch(r){return this.handleError(r)}}async generatePropertyTests(e){this.ensureInitialized();try{return await this.coordinator.generatePropertyTests(e)}catch(r){return this.handleError(r)}}async generateTestData(e){this.ensureInitialized();try{return await this.coordinator.generateTestData(e)}catch(r){return this.handleError(r)}}async learnPatterns(e){this.ensureInitialized();try{return await this.coordinator.learnPatterns(e)}catch(r){return this.handleError(r)}}async handleCoverageGap(e){if(!He(e.payload))return;let r=e.payload;r.riskScore>=.7&&await this.memory.set(`test-generation:pending-gaps:${r.gapId}`,r,{namespace:"test-generation",ttl:86400})}async handleImpactAnalysis(e){let r=e.payload;await this.memory.set(`test-generation:impact:${r.analysisId}`,r,{namespace:"test-generation",ttl:3600})}async handlePatternConsolidation(e){e.payload.domains.includes("test-generation")}ensureInitialized(){if(!this._initialized)throw new Error("TestGenerationPlugin is not initialized");if(!this.coordinator||!this.testGenerator||!this.patternMatcher)throw new Error("TestGenerationPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulGeneration(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedGeneration(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function Kl(c,t,e,r,i){return new pa(c,t,e,r,i)}_();_();import{spawn as zw}from"node:child_process";import{existsSync as Jp,mkdtempSync as Bw,readFileSync as qw,rmSync as Xl}from"node:fs";import{tmpdir as Gw}from"node:os";import{join as Zl}from"node:path";import{isDeepStrictEqual as ba}from"node:util";Pe();var Rt={DEFAULT_TEST_TIMEOUT_MS:6e4,DEFAULT_FILE_TIMEOUT_MS:3e4,DEFAULT_VIEWPORT_WIDTH:1280,DEFAULT_VIEWPORT_HEIGHT:720,MAX_RESULTS:1e3,RESULT_RETENTION_MS:864e5,MAX_TESTS_TRACKED:1e4,MAX_EXECUTION_HISTORY:100,ANALYSIS_CACHE_TTL_MS:36e5,MAX_RETRY_HISTORY:50,MAX_ACTIONS_PER_RECORDING:1e3,MAX_RECORDING_DURATION_MS:1800*1e3,MAX_WORKERS:32},ga={DEFAULT_STEP_TIMEOUT_MS:3e4,RETRY_DELAY_MS:1e3,DEFAULT_MAX_RETRIES:3,POLLING_INTERVAL_MS:100,ELEMENT_DETECTION_TIMEOUT_MS:1e3,POST_INTERACTION_DELAY_MS:500,DEFAULT_WAIT_MS:1e3,ACCESSIBILITY_TIMEOUT_MS:6e4,SCREENSHOT_QUALITY:80,TYPE_DEBOUNCE_MS:300},ci={BASE_DELAY_MS:1e3,MAX_DELAY_MS:3e4,DEFAULT_FLAKY_RATE:.3,DEFAULT_FLAKY_PASS_RATE:.7,RETRY_PASS_RATE_VARIATION:.1,SIGKILL_GRACE_PERIOD_MS:1e3},ha={DEFAULT_TIMEOUT_MS:6e4,QUICK_TIMEOUT_MS:1e4,MAX_CACHED_VALIDATIONS:1e3,CACHE_TTL_MS:36e5,CONTRACT_TTL_SECONDS:86400,MIGRATION_TTL_SECONDS:86400*90,MAX_RECURSION_DEPTH:10,MAX_SCHEMA_DEPTH:20,MAX_MIGRATION_STEPS:50,DEFAULT_SEARCH_LIMIT:100,HIGH_IMPACT_THRESHOLD:5,BREAKING_CHANGE_THRESHOLD:10,DEFAULT_PROVIDER_LOAD:50,HIGH_PROVIDER_LOAD_THRESHOLD:80},xO={PASSING_RATE_WARNING_THRESHOLD:95,PASSING_RATE_CRITICAL_THRESHOLD:80,MIN_COVERAGE_FOR_DEPLOY:80,PERFECT_PASSING_RATE:100,METRIC_TTL_SECONDS:86400*7,STANDARD_METRIC_TTL_SECONDS:86400,MAX_HIGH_VULN_IMPACT:.3,MEDIUM_VULN_IMPACT:.1,MAX_DUPLICATION_PERCENT:20};var PO={CHUNK_SIZE_BYTES:1024*1024,SPIKE_INTERVAL_MS:3e4,SPIKE_DURATION_MS:5e3};var kO={MAX_DURATION_MS:6e4,MAX_AGE_MS:10080*60*1e3,DAYS_IN_YEAR:365,MAX_DEPENDENCY_COUNT:10},fa={MAX_TOKENS:2048,ERROR_TRUNCATION_LENGTH:200,OUTPUT_TRUNCATION_LENGTH:500,DETAILED_OUTPUT_TRUNCATION_LENGTH:1e3,MODEL_TIERS:Cs};k();X();ge();mr();import*as li from"path";function Wt(c,t){return li.isAbsolute(c)?li.normalize(c):li.resolve(t??Ce(),c)}function ya(c,t){let e=`coverage:file:${Wt(c,t)}`,r=`coverage:file:${c}`;return e===r?[e]:[e,r]}function Wp(c){return{branch:c.some(t=>t.branches.total>0),function:c.some(t=>t.functions.total>0),statement:c.some(t=>t.statements.total>0)}}function Up(c,t){return{line:c.line,branch:t.branch?c.branch:null,function:t.function?c.function:null,statement:t.statement?c.statement:null,files:c.files}}Fc();var Nw=new Set(["skipped","pending","todo"]),Qp=4e3;function _w(c){if(!Array.isArray(c.failureMessages))return;let t=c.failureMessages.filter(r=>typeof r=="string").join(`
2272
+ `+i.slice(0,6e3)+"\n```"}],a=m=>{let p=/\b(test|it|describe)\s*\(/.test(m),h=/\b(expect|assert)\s*\(/.test(m);return p&&h?{passed:!0}:{passed:!1,feedback:"output must contain a test (test/it/describe) with an assertion (expect/assert)"}},o=await this.freeTierExecutor.execute({agentId:`test-gen:${r}`,messages:s,verify:a,escalate:!0,bestOfK:this.config.freeTierBestOfK??2,repairAttempts:this.config.freeTierRepairAttempts??1});if(!o.ok)return null;let l=$w(o.content),u=(l.match(/\b(?:expect|assert)\s*\(/g)??[]).length;return u===0?null:{tests:[{id:w(),name:`free-tier:${r.split("/").pop()??r}`,sourceFile:r,testFile:Ow(r),testCode:l,type:e.testType??"unit",assertions:u,framework:n,llmEnhanced:!0}],coverageEstimate:null,patternsUsed:["free-tier-local",`tier:${o.tierUsed}`]}}async generateTDDTests(e){let r=w();try{this.startWorkflow(r,"tdd");let i=await this.spawnTDDAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),g(i.error);this.addAgentToWorkflow(r,i.value);let n=await this.testGenerator.generateTDDTests(e);return n.success?(this.completeWorkflow(r),this.updateWorkflowProgress(r,this.getTDDProgress(e.phase))):this.failWorkflow(r,n.error.message),await this.agentCoordinator.stop(i.value),n}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async generatePropertyTests(e){let r=w();try{this.startWorkflow(r,"property");let i=await this.spawnPropertyTestAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),g(i.error);this.addAgentToWorkflow(r,i.value);let n=await this.testGenerator.generatePropertyTests(e);return n.success?this.completeWorkflow(r):this.failWorkflow(r,n.error.message),await this.agentCoordinator.stop(i.value),n}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async generateTestData(e){let r=w();try{this.startWorkflow(r,"data");let i=await this.testGenerator.generateTestData(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async learnPatterns(e){let r=w();try{this.startWorkflow(r,"learn");let i=await this.patternMatcher.learnPatterns(e);return i.success?(this.completeWorkflow(r),this.config.publishEvents&&await this.publishPatternLearned(i.value)):this.failWorkflow(r,i.error.message),i}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async spawnTestGeneratorAgent(e,r){let i={name:`test-generator-${e.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["test-generation",r.testType,r.framework??"vitest"],config:{workflowId:e,sourceFiles:r.sourceFiles,coverageTarget:r.coverageTarget}};return this.agentCoordinator.spawn(i)}async spawnTDDAgent(e,r){let i={name:`tdd-agent-${e.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["tdd",r.framework,r.phase],config:{workflowId:e,feature:r.feature,behavior:r.behavior}};return this.agentCoordinator.spawn(i)}async spawnPropertyTestAgent(e,r){let i={name:`property-test-agent-${e.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["property-testing","fast-check"],config:{workflowId:e,function:r.function,properties:r.properties}};return this.agentCoordinator.spawn(i)}async publishTestGenerated(e,r,i){let n={testId:e.id,testFile:e.testFile,framework:r,sourceFile:e.sourceFile,testType:e.type,patternsUsed:i},s=N(Ki.TestGenerated,"test-generation",n);await this.eventBus.publish(s)}async publishTestSuiteCreated(e,r){let i={suiteId:w(),testCount:e.tests.length,sourceFiles:r.sourceFiles,coverageEstimate:e.coverageEstimate},n=N(Ki.TestSuiteCreated,"test-generation",i);await this.eventBus.publish(n)}async publishPatternLearned(e){let r=N(Ki.PatternLearned,"test-generation",{patternCount:e.patterns.length,confidence:e.confidence,patternIds:e.patterns.map(i=>i.id)});await this.eventBus.publish(r)}async publishGenerationFailed(e,r){let i=N(Ki.GenerationFailed,"test-generation",{error:e.message,context:r,timestamp:new Date().toISOString()});await this.eventBus.publish(i)}getTDDProgress(e){switch(e){case"red":return 33;case"green":return 66;case"refactor":return 100;default:return 0}}subscribeToEvents(){this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGapDetected.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.subscribeToDreamEvents()}subscribeToDreamEvents(){this.eventBus.subscribe(bt.DreamCycleCompleted,this.handleDreamCycleCompleted.bind(this))}async handleDreamCycleCompleted(e){let{insights:r,cycleId:i}=e.payload;if(!r||r.length===0)return;let n=r.filter(s=>{let a=s.suggestedAction?.toLowerCase().includes(this.domainName)||s.suggestedAction?.toLowerCase().includes("test")||s.suggestedAction?.toLowerCase().includes("coverage"),o=s.sourceConcepts.some(u=>u.toLowerCase().includes("test")||u.toLowerCase().includes(this.domainName)||u.toLowerCase().includes("coverage")||u.toLowerCase().includes("edge-case")),l=s.type==="optimization"||s.type==="gap_detection"||s.type==="novel_association";return a||o||l&&s.actionable});if(n.length!==0){Z.info(`[${this.domainName}] Received ${n.length} relevant dream insights from cycle ${i}`);for(let s of n)s.confidenceScore>.7&&s.actionable&&await this.applyDreamInsight(s,i),this.recentDreamInsights.push({...s,receivedAt:new Date});this.recentDreamInsights.length>50&&(this.recentDreamInsights=this.recentDreamInsights.slice(-50))}}async applyDreamInsight(e,r){if(Z.info(`[${this.domainName}] Applying dream insight: ${e.description.slice(0,100)}...`),this.qesona)try{let i={id:`dream-insight-${e.id}`,features:this.encodeInsightAsFeatures(e),metadata:{insightType:e.type,cycleId:r,sourceConcepts:e.sourceConcepts}},n={type:"dream-insight",value:e.suggestedAction||e.description},s=this.qesona.createPattern(i,n,{reward:e.confidenceScore,success:!0,quality:e.noveltyScore},"dream-derived",this.domainName,{insightId:e.id,cycleId:r,description:e.description,suggestedAction:e.suggestedAction});Z.info(`[${this.domainName}] Created SONA pattern ${s.id} from dream insight`)}catch(i){Z.error(`[${this.domainName}] Failed to store dream insight pattern`,i instanceof Error?i:void 0)}await this.memory.set(`${this.domainName}:dream-insight:${e.id}`,{insight:e,cycleId:r,appliedAt:new Date().toISOString()},{namespace:this.domainName,ttl:86400*7})}getRecentDreamInsights(e){let r=Date.now()-864e5;return this.recentDreamInsights.filter(i=>{let n=i.receivedAt.getTime()>r,s=!e||i.type===e;return n&&s})}async enhanceWithDreamInsights(e){let r=[],n=this.getRecentDreamInsights().filter(s=>(s.type==="novel_association"||s.type==="gap_detection")&&s.actionable&&s.confidenceScore>.6);for(let s of n)s.suggestedAction&&(e.sourceFiles.some(o=>s.sourceConcepts.some(l=>o.toLowerCase().includes(l.toLowerCase())))||s.suggestedAction.toLowerCase().includes(e.testType))&&r.push(s.suggestedAction);return r.slice(0,5)}encodeInsightAsFeatures(e){let r=[],i={pattern_merge:.2,novel_association:.4,optimization:.6,gap_detection:.8};for(r.push(i[e.type]||.5),r.push(e.confidenceScore),r.push(e.noveltyScore),r.push(e.actionable?1:0),r.push(Math.min(1,e.sourceConcepts.length/10));r.length<384;)r.push(0);return r.slice(0,384)}async handleCoverageGapDetected(e){if(!He(e.payload))return;let r=e.payload,i=await this.testGenerator.generateForCoverageGap(r.file,r.uncoveredLines,"jest");if(i.success&&i.value.length>0)for(let n of i.value)await this.publishTestGenerated(n,"jest")}async handleTestRunCompleted(e){}async learnFromGeneration(e){let r=e.patternIds??[];if(r.length!==0)try{let{getUnifiedMemory:i}=await import("./unified-memory-FL26RTV3.js"),{recordPatternUsage:n}=await import("./pattern-usage-recorder-LOPNCULT.js"),s=i().getDatabase();for(let a of r)n(s,{patternId:a,success:!0})}catch(i){Z.warn("Pattern usage recording skipped",{error:i instanceof Error?i.message:String(i)})}}async adaptTestGenerationPatterns(e){if(!this.qesona)return[];try{let r={id:`test-gen-${Date.now()}`,features:this.encodeRequestAsFeatures(e),metadata:{testType:e.testType,framework:e.framework,sourceFileCount:e.sourceFiles.length}},i=await this.qesona.adaptPattern(r,this.config.sonaPatternType,"test-generation");return i.success&&i.pattern?(Z.info(`QESONA adapted pattern with ${i.similarity.toFixed(3)} similarity in ${i.adaptationTimeMs.toFixed(2)}ms`),[i.pattern.id]):[]}catch(r){return Z.error("QESONA pattern adaptation failed:",r instanceof Error?r:void 0),[]}}async storeTestGenerationPattern(e,r){if(!(!this.qesona||e.coverageEstimate===null))try{let i={id:`test-gen-${Date.now()}`,features:this.encodeRequestAsFeatures(r),metadata:{testCount:e.tests.length,coverageEstimate:e.coverageEstimate,success:!0}},n={type:"generate-tests",value:{testType:r.testType,framework:r.framework,patternsUsed:e.patternsUsed}},s=this.qesona.createPattern(i,n,{reward:e.coverageEstimate/100,success:!0,quality:e.coverageEstimate/100},this.config.sonaPatternType,"test-generation",{testCount:e.tests.length,framework:r.framework,testType:r.testType});Z.info(`Stored test generation pattern ${s.id} in QESONA`)}catch(i){Z.error("Failed to store pattern in QESONA:",i instanceof Error?i:void 0)}}async findSimilarTests(e){if(!this.flashAttention)return[];let r=[];try{for(let n of e){let s=this.generateTestEmbedding(n);this.testEmbeddings.set(n.id,s)}let i=await this.loadExistingTestEmbeddings();if(i.length===0)return[];for(let n of e){let s=this.testEmbeddings.get(n.id);if(!s)continue;let o=(await this.flashAttention.computeTestSimilarity(s,i.map(l=>l.embedding),5)).filter(l=>l.similarity>.7).map(l=>({testId:i[l.index].testId,similarity:l.similarity}));o.length>0&&r.push({test:n,similarTests:o})}return r}catch(i){return Z.error("Flash Attention similarity detection failed:",i instanceof Error?i:void 0),[]}}async prioritizeTestCases(e,r){if(!this.decisionTransformer)return e;try{let i={id:`prioritize-${Date.now()}`,features:[e.length/100,(r.coverageTarget||80)/100,r.testType==="unit"?.2:r.testType==="integration"?.5:.8,r.framework==="jest"?.3:r.framework==="vitest"?.4:.5],metadata:{testCount:e.length,framework:r.framework,testType:r.testType}},n=await this.decisionTransformer.predict(i);return Z.info(`DecisionTransformer prediction: ${n.reasoning}`),n.confidence>.7?e.sort((s,a)=>a.assertions-s.assertions):e}catch(i){return Z.error("DecisionTransformer prioritization failed:",i instanceof Error?i:void 0),e}}getQESONAStats(){return this.qesona?this.qesona.getStats():null}getFlashAttentionMetrics(){return this.flashAttention?this.flashAttention.getMetrics():null}async checkRequirementCoherence(e){return this.coherenceGate?this.coherenceGate.checkRequirementCoherence(e):{isCoherent:!0,energy:0,lane:"reflex",contradictions:[],recommendations:[],durationMs:0,usedFallback:!0}}isCoherenceGateAvailable(){return this.coherenceGate?.isAvailable()??!1}async verifyAndEnrichSpec(e){if(!this.coherenceGate||!this.config.enableCoherenceGate)return e;let r=await this.coherenceGate.validateAndEnrich(e);if(r.success)return r.value;throw r.error}async verifyTestPatternSelection(e,r){let i=U({id:w(),type:"test-pattern-selection",confidence:r,description:`Verify test pattern: ${e.name} (${e.type})`,payload:e,detectedBy:"test-generation-coordinator",severity:r>.9?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Z.info(`Test pattern '${e.name}' verified by consensus`),!0):(Z.warn(`Test pattern '${e.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyMockStrategy(e,r){let i=U({id:w(),type:"mock-strategy",confidence:r,description:`Verify mock strategy for ${e.target}: ${e.mockType}`,payload:e,detectedBy:"test-generation-coordinator",severity:r>.85?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Z.info(`Mock strategy for '${e.target}' verified by consensus`),!0):(Z.warn(`Mock strategy for '${e.target}' NOT verified`),!1)}return!0}async verifyEdgeCaseGeneration(e,r){let i=U({id:w(),type:"edge-case-generation",confidence:r,description:`Verify edge case: ${e.description}`,payload:e,detectedBy:"test-generation-coordinator",severity:"high"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Z.info(`Edge case '${e.description.slice(0,50)}...' verified by consensus`),!0):(Z.warn(`Edge case NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}encodeRequestAsFeatures(e){let r=[];for(r.push(e.testType==="unit"?.2:e.testType==="integration"?.5:.8),r.push(e.framework==="jest"?.25:e.framework==="vitest"?.5:e.framework==="mocha"?.75:.9),r.push(Math.min(1,e.sourceFiles.length/50)),r.push((e.coverageTarget||80)/100);r.length<384;)r.push(0);return r.slice(0,384)}generateTestEmbedding(e){let r=[],i=this.simpleHash(e.name);for(let n=0;n<64;n++)r.push((i>>n%32&1)*2-1);for(r.push(e.type==="unit"?.2:e.type==="integration"?.5:.8),r.push(Math.min(1,e.assertions/20));r.length<384;)r.push(0);return new Float32Array(r.slice(0,384))}async loadExistingTestEmbeddings(){try{let e=await this.memory.search("test-embedding:*",1e3),r=[];for(let i of e){let n=await this.memory.get(i);n&&r.push({testId:n.testId,embedding:new Float32Array(n.embedding)})}return r}catch{return[]}}simpleHash(e){let r=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);r=(r<<5)-r+n,r=r|0}return Math.abs(r)}async loadWorkflowState(){let e=await this.memory.get("test-generation:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("test-generation:coordinator:workflows",e,{namespace:"test-generation",persist:!0})}};k();var pa=class extends te{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;testGenerator=null;patternMatcher=null;pluginConfig;get name(){return"test-generation"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{generateTests:this.generateTests.bind(this),generateTDDTests:this.generateTDDTests.bind(this),generatePropertyTests:this.generatePropertyTests.bind(this),generateTestData:this.generateTestData.bind(this),learnPatterns:this.learnPatterns.bind(this),getCoordinator:()=>this.coordinator,getTestGenerator:()=>this.testGenerator,getPatternMatcher:()=>this.patternMatcher}}getTaskHandlers(){return new Map([["generate-tests",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.testType,i=e.framework;if(!Array.isArray(e.sourceFiles)||e.sourceFiles.length===0)return g(new Error("Invalid generate-tests payload: missing sourceFiles"));let n=await Ft("generate-tests","sourceFiles",e.sourceFiles,{maxBytes:Ur});if(!n.success)return n;let a={sourceFiles:n.value,testType:r??"unit",framework:i??"vitest",coverageTarget:e.coverageTarget,patterns:e.patterns};return this.coordinator.generateTests(a)}],["generate-tdd-tests",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.feature,i=e.behavior,n=e.framework,s=e.phase;return!r||!i?g(new Error("Invalid generate-tdd-tests payload: missing feature or behavior")):this.coordinator.generateTDDTests({feature:r,behavior:i,framework:n??"vitest",phase:s??"red"})}],["generate-property-tests",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.function,i=e.properties;return!r||!i||i.length===0?g(new Error("Invalid generate-property-tests payload: missing function or properties")):this.coordinator.generatePropertyTests({function:r,properties:i,constraints:e.constraints})}],["generate-test-data",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.schema,i=e.count;return r?this.coordinator.generateTestData({schema:r,count:i??10,locale:e.locale,preserveRelationships:e.preserveRelationships}):g(new Error("Invalid generate-test-data payload: missing schema"))}]])}async onInitialize(){this.testGenerator=Sr({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.testGenerator),this.patternMatcher=new Rr(this.memory,this.pluginConfig.patternMatcher);let e;if(this.pluginConfig.coordinator?.enableFreeTier===!0||process.env.AQE_FREE_TIER==="1"){e=new Is(1e4,{enableEMACalibration:!0,enableAutoEscalation:!0});try{await e.initialize()}catch{}}this.coordinator=new Ln(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter,void 0,void 0,e),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.testGenerator=null,this.patternMatcher=null}subscribeToEvents(){this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this)),this.eventBus.subscribe("learning-optimization.PatternConsolidated",this.handlePatternConsolidation.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;case"code-intelligence.ImpactAnalysisCompleted":await this.handleImpactAnalysis(e);break;default:break}}async generateTests(e){this.ensureInitialized();try{let r=await this.coordinator.generateTests(e);return r.success?this.trackSuccessfulGeneration(r.value):this.trackFailedGeneration(r.error),r}catch(r){return this.handleError(r)}}async generateTDDTests(e){this.ensureInitialized();try{return await this.coordinator.generateTDDTests(e)}catch(r){return this.handleError(r)}}async generatePropertyTests(e){this.ensureInitialized();try{return await this.coordinator.generatePropertyTests(e)}catch(r){return this.handleError(r)}}async generateTestData(e){this.ensureInitialized();try{return await this.coordinator.generateTestData(e)}catch(r){return this.handleError(r)}}async learnPatterns(e){this.ensureInitialized();try{return await this.coordinator.learnPatterns(e)}catch(r){return this.handleError(r)}}async handleCoverageGap(e){if(!He(e.payload))return;let r=e.payload;r.riskScore>=.7&&await this.memory.set(`test-generation:pending-gaps:${r.gapId}`,r,{namespace:"test-generation",ttl:86400})}async handleImpactAnalysis(e){let r=e.payload;await this.memory.set(`test-generation:impact:${r.analysisId}`,r,{namespace:"test-generation",ttl:3600})}async handlePatternConsolidation(e){e.payload.domains.includes("test-generation")}ensureInitialized(){if(!this._initialized)throw new Error("TestGenerationPlugin is not initialized");if(!this.coordinator||!this.testGenerator||!this.patternMatcher)throw new Error("TestGenerationPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulGeneration(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedGeneration(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function Kl(c,t,e,r,i){return new pa(c,t,e,r,i)}_();_();import{spawn as zw}from"node:child_process";import{existsSync as Jp,mkdtempSync as Bw,readFileSync as qw,rmSync as Xl}from"node:fs";import{tmpdir as Gw}from"node:os";import{join as Zl}from"node:path";import{isDeepStrictEqual as ba}from"node:util";Pe();var Rt={DEFAULT_TEST_TIMEOUT_MS:6e4,DEFAULT_FILE_TIMEOUT_MS:3e4,DEFAULT_VIEWPORT_WIDTH:1280,DEFAULT_VIEWPORT_HEIGHT:720,MAX_RESULTS:1e3,RESULT_RETENTION_MS:864e5,MAX_TESTS_TRACKED:1e4,MAX_EXECUTION_HISTORY:100,ANALYSIS_CACHE_TTL_MS:36e5,MAX_RETRY_HISTORY:50,MAX_ACTIONS_PER_RECORDING:1e3,MAX_RECORDING_DURATION_MS:1800*1e3,MAX_WORKERS:32},ga={DEFAULT_STEP_TIMEOUT_MS:3e4,RETRY_DELAY_MS:1e3,DEFAULT_MAX_RETRIES:3,POLLING_INTERVAL_MS:100,ELEMENT_DETECTION_TIMEOUT_MS:1e3,POST_INTERACTION_DELAY_MS:500,DEFAULT_WAIT_MS:1e3,ACCESSIBILITY_TIMEOUT_MS:6e4,SCREENSHOT_QUALITY:80,TYPE_DEBOUNCE_MS:300},ci={BASE_DELAY_MS:1e3,MAX_DELAY_MS:3e4,DEFAULT_FLAKY_RATE:.3,DEFAULT_FLAKY_PASS_RATE:.7,RETRY_PASS_RATE_VARIATION:.1,SIGKILL_GRACE_PERIOD_MS:1e3},ha={DEFAULT_TIMEOUT_MS:6e4,QUICK_TIMEOUT_MS:1e4,MAX_CACHED_VALIDATIONS:1e3,CACHE_TTL_MS:36e5,CONTRACT_TTL_SECONDS:86400,MIGRATION_TTL_SECONDS:86400*90,MAX_RECURSION_DEPTH:10,MAX_SCHEMA_DEPTH:20,MAX_MIGRATION_STEPS:50,DEFAULT_SEARCH_LIMIT:100,HIGH_IMPACT_THRESHOLD:5,BREAKING_CHANGE_THRESHOLD:10,DEFAULT_PROVIDER_LOAD:50,HIGH_PROVIDER_LOAD_THRESHOLD:80},PO={PASSING_RATE_WARNING_THRESHOLD:95,PASSING_RATE_CRITICAL_THRESHOLD:80,MIN_COVERAGE_FOR_DEPLOY:80,PERFECT_PASSING_RATE:100,METRIC_TTL_SECONDS:86400*7,STANDARD_METRIC_TTL_SECONDS:86400,MAX_HIGH_VULN_IMPACT:.3,MEDIUM_VULN_IMPACT:.1,MAX_DUPLICATION_PERCENT:20};var kO={CHUNK_SIZE_BYTES:1024*1024,SPIKE_INTERVAL_MS:3e4,SPIKE_DURATION_MS:5e3};var DO={MAX_DURATION_MS:6e4,MAX_AGE_MS:10080*60*1e3,DAYS_IN_YEAR:365,MAX_DEPENDENCY_COUNT:10},fa={MAX_TOKENS:2048,ERROR_TRUNCATION_LENGTH:200,OUTPUT_TRUNCATION_LENGTH:500,DETAILED_OUTPUT_TRUNCATION_LENGTH:1e3,MODEL_TIERS:Cs};k();X();ge();mr();import*as li from"path";function Wt(c,t){return li.isAbsolute(c)?li.normalize(c):li.resolve(t??Ce(),c)}function ya(c,t){let e=`coverage:file:${Wt(c,t)}`,r=`coverage:file:${c}`;return e===r?[e]:[e,r]}function Wp(c){return{branch:c.some(t=>t.branches.total>0),function:c.some(t=>t.functions.total>0),statement:c.some(t=>t.statements.total>0)}}function Up(c,t){return{line:c.line,branch:t.branch?c.branch:null,function:t.function?c.function:null,statement:t.statement?c.statement:null,files:c.files}}Fc();var Nw=new Set(["skipped","pending","todo"]),Qp=4e3;function _w(c){if(!Array.isArray(c.failureMessages))return;let t=c.failureMessages.filter(r=>typeof r=="string").join(`
2273
2273
  `).trim();if(!t)return;let e=Me(t);return e.length>Qp?`${e.slice(0,Qp)}\u2026 [truncated]`:e}function Me(c){return ji(c,Number.POSITIVE_INFINITY)}function Jl(c){return c.map(t=>({...t,error:Me(t.error),...typeof t.stack=="string"?{stack:Me(t.stack)}:{}}))}function Vw(c){return c==="passed"||c==="failed"?c:typeof c=="string"&&Nw.has(c)?"skipped":void 0}function Kp(c,t){if(!Array.isArray(c.testResults))return;let e=[];for(let r of c.testResults){let i=typeof r?.name=="string"?r.name:t,n=Array.isArray(r?.assertionResults)?r.assertionResults:[];for(let s of n){if(!s||typeof s!="object")continue;let a=Vw(s.status);if(!a)continue;let o=typeof s.fullName=="string"&&s.fullName?s.fullName:typeof s.title=="string"?s.title:"";if(!o)continue;let l=typeof s.duration=="number"&&Number.isFinite(s.duration)?s.duration:void 0,u=a==="failed"?_w(s):void 0;e.push({name:o,file:i,status:a,...l!==void 0?{duration:l}:{},...u?{failureMessage:u}:{}})}}return e.length>0?e:void 0}function Yl(c){if(c.length===0||c.some(e=>e.total>0&&!e.testCases))return;let t=c.flatMap(e=>e.testCases??[]);return t.length>0?t:void 0}Pe();Yr();var jw={simulateForTesting:!1,simulatedTestsPerFile:5,simulatedFailureRate:.2,simulatedSkipRate:.1,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:fa.MAX_TOKENS},Yp=x.create("test-execution/test-executor"),wa=class{runResults=new Map;runStats=new Map;config;memory;llmRouter;MAX_RESULTS=Rt.MAX_RESULTS;RESULT_RETENTION_MS=Rt.RESULT_RETENTION_MS;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...jw,...e}}async execute(t){let e=w(),r=new Date;try{let i=this.validateRequest(t);if(i.success===!1)return g(i.error);let n=await this.runTests(t),s=new Date,a=s.getTime()-r.getTime(),o={runId:e,status:n.failed>0?"failed":"passed",total:n.total,passed:n.passed,failed:n.failed,skipped:n.skipped,duration:a,failedTests:Jl(n.failedTests),...n.testCases?{testCases:n.testCases}:{},coverage:n.coverage,fileCoverages:n.fileCoverages};this.runResults.set(e,o),await this.storeResults(e,o,t.testFiles);let l={runId:e,startTime:r,endTime:s,duration:a,testsPerSecond:n.total/(a/1e3),workers:1,memoryUsage:process.memoryUsage?.().heapUsed??0};return this.runStats.set(e,l),f(o)}catch(i){return g(y(i))}}async executeParallel(t){let e=w(),r=new Date;try{let i=this.validateParallelRequest(t);if(i.success===!1)return g(i.error);let{workers:n,sharding:s="file",isolation:a="process"}=t,l=["vitest","jest"].includes(t.framework.toLowerCase())?1:n,u=this.shardTests(t.testFiles,l,s),d=await Promise.all(u.map((C,S)=>this.executeWorker(C,S,a,t))),m=this.aggregateResults(d),p=new Date,h=p.getTime()-r.getTime(),v={runId:e,status:m.failed>0?"failed":"passed",total:m.total,passed:m.passed,failed:m.failed,skipped:m.skipped,duration:h,failedTests:Jl(m.failedTests),...m.testCases?{testCases:m.testCases}:{},coverage:m.coverage,fileCoverages:m.fileCoverages};this.runResults.set(e,v),await this.storeResults(e,v,t.testFiles);let b={runId:e,startTime:r,endTime:p,duration:h,testsPerSecond:m.total/(h/1e3),workers:l,memoryUsage:process.memoryUsage?.().heapUsed??0};return this.runStats.set(e,b),f(v)}catch(i){return g(y(i))}}async getResults(t){let e=this.runResults.get(t);if(e)return f(e);try{let r=await this.memory.get(`test-run:${t}`);if(r)return this.runResults.set(t,r),f(r)}catch{}return g(new Error(`Test run not found: ${t}`))}async getStats(t){let e=this.runStats.get(t);if(e)return f(e);try{let r=await this.memory.get(`test-stats:${t}`);if(r)return this.runStats.set(t,r),f(r)}catch{}return g(new Error(`Test stats not found: ${t}`))}cleanupOldResults(){let t=Date.now(),e=0;for(let[r,i]of this.runResults){let n=i.duration?t-i.duration:t;t-n>this.RESULT_RETENTION_MS&&(this.runResults.delete(r),this.runStats.delete(r),e++)}if(this.runResults.size>this.MAX_RESULTS){let r=this.runResults.size-this.MAX_RESULTS,i=Array.from(this.runResults.entries());for(let n=0;n<r&&n<i.length;n++)this.runResults.delete(i[n][0]),this.runStats.delete(i[n][0]),e++}return e}destroy(){this.runResults.clear(),this.runStats.clear()}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(t){return ae(t)}async analyzeFailuresWithLLM(t){if(!this.isLLMAnalysisAvailable()||t.length===0)return null;try{let e=t.slice(0,5).map(i=>`- ${i.testName}: ${i.error?Me(i.error).substring(0,200):"Unknown error"}`).join(`
2274
2274
  `);return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze these test failures and provide insights:
2275
2275
  ${e}
@@ -2307,7 +2307,7 @@ expect(result).toBeDefined();`,effort:"medium"}),e.push({action:"Add error bound
2307
2307
  `)||r||(t===0?i&&!d?`Retry runner did not report a passing test in ${i}.`:"Retry runner did not report any passing tests.":`Test failed with exit code ${t}`)}}let a=e.match(/\{[\s\S]*"numFailedTests"[\s\S]*\}/);if(a){let l=D(a[0]);return l.numPassedTests===0&&l.numFailedTests===0&&l.numFailedTestSuites===0?ru:t===0&&l.success!==!1&&l.numFailedTests===0&&l.numFailedTestSuites===0&&Number.isFinite(l.numPassedTests)&&l.numPassedTests>0?{passed:!0}:{passed:!1,error:l.testResults?.[0]?.assertionResults?.find(d=>d.status==="failed")?.failureMessages?.join(`
2308
2308
  `)||r||(t===0?"Retry runner did not report any passing tests.":`Test failed with exit code ${t}`)}}let o=e.match(/\{[\s\S]*"stats"[\s\S]*"failures"[\s\S]*\}/);if(o){let l=D(o[0]);return l.stats?.passes===0&&l.stats?.failures===0?ru:t===0&&l.stats?.failures===0&&Number.isFinite(l.stats?.passes)&&l.stats.passes>0?{passed:!0}:{passed:!1,error:l.failures?.[0]?.err?.message||r||(t===0?"Retry runner did not report any passing tests.":`Test failed with exit code ${t}`)}}}catch{}if(t===0)return{passed:!1,error:"Retry runner did not report any passing tests."};let n=r||e||`Test failed with exit code ${t}`;return{passed:!1,error:Me(n).substring(0,1e3)}}calculateDelay(t,e,r,i){let n;switch(e){case"constant":n=r;break;case"linear":n=r*(t+1);break;case"exponential":n=r*Math.pow(2,t);break;default:n=r}if(this.config.enableJitter){let s=n*this.config.maxJitterPercent*z();n+=s}return Math.min(n,i)}sleep(t){return new Promise(e=>setTimeout(e,t))}async recordRetry(t,e){let r=this.retryHistory.get(t)??[];r.push({testId:e.testId,attempts:e.attempts,passed:e.passed,error:e.finalError,...e.unmatched?{unmatched:!0}:{},timestamp:new Date}),r.length>50&&r.shift(),this.retryHistory.set(t,r),await this.memory.set(`retry-history:${t}`,r,{namespace:"test-execution",persist:!0})}convertToRetryStatistics(t){let e=new Map,r=0,i=0,n=0,s=0,a=0;for(let d of t)r+=d.totalRetries,i+=d.successful,n+=d.failed,s+=d.totalRetries,d.successful>0&&(a+=d.successful);let o=i+n,l=o>0?r/o:0,u=a>0?s/a:0;return{totalRetries:r,successfulRetries:i,failedRetries:n,averageAttemptsToPass:u,retryRate:l,testStats:e}}},ru={passed:!1,unmatched:!0,error:"The retry filter matched no test, so nothing was rerun."};k();var Pr={NAVIGATE:"navigate",CLICK:"click",TYPE:"type",WAIT:"wait",ASSERT:"assert",SCREENSHOT:"screenshot",A11Y_CHECK:"a11y-check"};function Ta(c){return c.type===Pr.NAVIGATE}function Ea(c){return c.type===Pr.CLICK}function Aa(c){return c.type===Pr.TYPE}function xa(c){return c.type===Pr.WAIT}function Pa(c){return c.type===Pr.ASSERT}function ka(c){return c.type===Pr.SCREENSHOT}function Da(c){return c.type===Pr.A11Y_CHECK}function Ia(c){let t=Math.min(1,c.failureRate??0),e=Math.min(1,c.flakinessScore??0),r=c.complexity??.5,i=1-(c.coverage??0)/100,n=c.businessCriticality??.5,a=Math.max(0,1-(c.estimatedDuration??0)/6e4),o=10080*60*1e3,l=Math.max(0,1-(c.timeSinceModification??0)/o),u=Math.min(1,(c.dependencyCount??0)/10);return{failureProbability:t,flakiness:e,complexity:r,coverageGap:i,criticality:n,speed:a,age:l,dependencyComplexity:u}}function eg(c){return[c.failureProbability,c.flakiness,c.complexity,c.coverageGap,c.criticality,c.speed,c.age,c.dependencyComplexity]}function iu(c){return{critical:100,high:75,standard:50,low:25,defer:0}[c]}function nu(c){return{critical:"p0",high:"p1",standard:"p2",low:"p3",defer:"p3"}[c]}function su(c,t){let e=t.failedEarly?.5:0,r=c.availableTime>0?Math.max(0,1-t.executionTime/c.availableTime)*.3:0,i=t.coverageImproved?.2:0,n=t.flakyDetected?.1:0,s=e+r+i+n;return{earlyDetection:e,timeEfficiency:r,coverageGain:i,flakinessReduction:n,total:s}}function Ma(c,t){let e=Ia(t);return{id:c,features:eg(e),testId:c,testType:t.testType??"unit",priority:t.priority??t.assignedPriority??"p2",complexity:t.complexity??.5,domain:t.domain??"test-execution",dependencies:t.dependencies??[],estimatedDuration:t.estimatedDuration??5e3,coverage:t.coverage??0,failureHistory:t.failureHistory??[],filePath:t.filePath,testName:t.testName,failureRate:t.failureRate??0,flakinessScore:t.flakinessScore??0,executionCount:t.executionCount??0,timeSinceModification:t.timeSinceModification??0,businessCriticality:t.businessCriticality??.5,dependencyCount:t.dependencyCount??0,assignedPriority:t.assignedPriority??t.priority??"p2",timestamp:new Date,metadata:{...t,features:e}}}var vC={enableDT:!0,minTrajectoriesForDT:5,enableHeuristicFallback:!0,minConfidence:.4,enableAutoTraining:!0,trainingInterval:10,contextLength:10,embeddingDim:384},Fa=class{constructor(t,e={}){this.memory=t;this.config={...vC,...e},this.decisionTransformer=new oi({contextLength:this.config.contextLength,embeddingDim:this.config.embeddingDim})}memory;decisionTransformer;config;executionHistory=new Map;executionsSinceLastTraining=0;async initialize(){await this.loadHistory(),await this.loadModel()}async prioritize(t,e){try{let r=t.map(d=>Ma(d.testId,d)),i=await Promise.all(r.map(d=>this.getPrediction(d))),n=t.map((d,m)=>{let p=i[m],h=p.action.value??"standard";return{testId:d.testId,filePath:d.filePath,testName:d.testName,priority:h,score:iu(h),confidence:p.confidence,reasoning:p.reasoning??"No reasoning provided"}});n.sort((d,m)=>m.score-d.score);let s=this.decisionTransformer.getInfo(),a={trained:s.stats.episode>0,trajectoryCount:this.countTrajectories(),averageReturn:s.stats.averageReward},o=a.trained&&a.trajectoryCount>=this.config.minTrajectoriesForDT?"dt-prediction":this.config.enableHeuristicFallback?"heuristic":"dt-prediction",l=n.reduce((d,m)=>d+m.score,0),u=n.reduce((d,m)=>d+m.confidence,0)/n.length;return f({tests:n,totalScore:l,averageConfidence:u,method:o,learningStatus:a})}catch(r){return g(y(r))}}async recordExecution(t,e,r){let i={testId:t,timestamp:new Date,passed:e.passed,duration:e.duration,priority:nu(e.priority),failureReason:e.passed?void 0:"Test failed"},n=this.executionHistory.get(t)??[];n.push(i),n.length>100&&n.shift(),this.executionHistory.set(t,n),await this.persistHistory();let s=this.createExperience(t,e,r);await this.decisionTransformer.train(s),this.executionsSinceLastTraining++,this.config.enableAutoTraining&&this.executionsSinceLastTraining>=this.config.trainingInterval&&(await this.trainBatch(),this.executionsSinceLastTraining=0)}getStats(){let t=this.executionHistory.size,e=Array.from(this.executionHistory.values()).reduce((r,i)=>r+i.length,0);return{totalTests:t,totalExecutions:e,trajectoryCount:this.countTrajectories(),dtStats:this.decisionTransformer.getStats()}}async exportModel(){return this.decisionTransformer.exportModel()}async importModel(t){await this.decisionTransformer.importModel(t)}async getPrediction(t){try{let e=await this.decisionTransformer.predict(t);return this.config.enableHeuristicFallback&&e.confidence<this.config.minConfidence?this.getHeuristicPrediction(t):{action:e.action,confidence:e.confidence,reasoning:e.reasoning}}catch{return this.getHeuristicPrediction(t)}}getHeuristicPrediction(t){let e=Ia(t),r=0;r+=e.failureProbability*30,r+=e.flakiness*15,r+=e.complexity*10,r+=e.coverageGap*20,r+=e.criticality*15,r+=e.speed*5,r+=e.age*5;let i;return r>60?i="critical":r>45?i="high":r>30?i="standard":r>15?i="low":i="defer",{action:{type:"prioritize",value:i},confidence:.6,reasoning:`Heuristic: score ${r.toFixed(1)} (failure: ${e.failureProbability.toFixed(2)}, flaky: ${e.flakiness.toFixed(2)}, coverage gap: ${e.coverageGap.toFixed(2)})`}}createExperience(t,e,r){let i=this.executionHistory.get(t)??[],n=i[i.length-1],s=Ma(t,{filePath:"",testName:t,failureHistory:i.map(u=>u.passed?1:0),executionCount:i.length,flakinessScore:this.calculateFlakinessScore(i),estimatedDuration:e.duration}),a={type:"prioritize",value:e.priority},o=su(r,{failedEarly:e.failedEarly??!e.passed,executionTime:e.duration,coverageImproved:e.coverageImproved??!1,flakyDetected:e.flakyDetected??!1}),l={...s};return{state:s,action:a,reward:o.total,nextState:l,done:!0,timestamp:new Date}}calculateFlakinessScore(t){if(t.length<3)return 0;let e=t.slice(-10),r=e.filter(a=>!a.passed).length,i=0;for(let a=1;a<e.length;a++)e[a].passed!==e[a-1].passed&&i++;let n=r/e.length,s=i/Math.max(1,e.length-1);return n*.5+s*.5}async trainBatch(){let t=[];for(let[e,r]of this.executionHistory.entries())for(let i of r){let n={runId:`historical-${e}-${i.timestamp.getTime()}`,totalTests:1,availableTime:6e4,workers:1,mode:"sequential",phase:"regression"},s=this.createExperience(e,{passed:i.passed,duration:i.duration,priority:this.priorityFromEnum(i.priority),failedEarly:!i.passed},n);t.push(s)}t.length>0&&(await this.decisionTransformer.trainBatch(t),await this.saveModel())}priorityFromEnum(t){return{p0:"critical",p1:"high",p2:"standard",p3:"low",p4:"defer"}[t]??"standard"}countTrajectories(){return this.decisionTransformer.getStats().episode}async loadHistory(){try{let t=await this.memory.get("test-prioritizer:history");t&&(this.executionHistory=new Map(Object.entries(t)))}catch{}}async persistHistory(){let t=Object.fromEntries(this.executionHistory);await this.memory.set("test-prioritizer:history",t,{namespace:"test-execution",persist:!0})}async loadModel(){try{let t=await this.memory.get("test-prioritizer:model");t&&await this.decisionTransformer.importModel(t)}catch{}}async saveModel(){let t=await this.decisionTransformer.exportModel();await this.memory.set("test-prioritizer:model",t,{namespace:"test-execution",persist:!0})}};var au={defaultStepTimeout:ga.DEFAULT_STEP_TIMEOUT_MS,defaultRetries:2,retryDelay:ga.RETRY_DELAY_MS,screenshotOnFailure:!0,stopOnFirstFailure:!1,pollingInterval:ga.POLLING_INTERVAL_MS,maxParallelWorkers:4,verbose:!1,preferAgentBrowser:!0,browserClientType:"auto"},Ue=class extends Error{constructor(e,r,i,n){super(e);this.code=r;this.stepId=i;this.cause=n;this.name="E2ERunnerError"}code;stepId;cause},kr=class extends Ue{constructor(t,e,r){super(`Step "${t}" timed out after ${e}ms`,"STEP_TIMEOUT",t,r),this.name="StepTimeoutError"}},Tt=class extends Ue{constructor(e,r,i,n,s){super(e,"ASSERTION_FAILED",r,s);this.expected=i;this.actual=n;this.name="AssertionError"}expected;actual};_();var V=class c extends Error{constructor(e,r,i,n){super(e);this.code=r;this.tool=i;this.cause=n;this.name="BrowserError",Object.setPrototypeOf(this,c.prototype)}code;tool;cause},ue=class c extends V{constructor(t,e,r){super(e||"Browser tool is unavailable","BROWSER_UNAVAILABLE",t,r),this.name="BrowserUnavailableError",Object.setPrototypeOf(this,c.prototype)}},Qt=class c extends V{constructor(t,e,r){super(`${e} timed out`,"BROWSER_TIMEOUT",t,r),this.name="BrowserTimeoutError",Object.setPrototypeOf(this,c.prototype)}},Dr=class c extends V{constructor(t,e,r){let i=typeof e=="string"?e:JSON.stringify(e);super(`Element not found: ${i}`,"ELEMENT_NOT_FOUND",t,r),this.name="BrowserElementNotFoundError",Object.setPrototypeOf(this,c.prototype)}};X();Xc();Yr();k();import{spawn as bC}from"child_process";function La(c,t,e){let r=Xr("npx");if(!r){let i=Object.assign(new Error("npx CLI not found next to node"),{code:"ENOENT"});return Promise.resolve({status:null,signal:null,stdout:"",stderr:"",error:i})}return Nt(r[0],[...r[1],"agent-browser",...c],{cwd:process.cwd(),timeout:t,maxBuffer:e})}var Kt=class{config;browserLaunched=!1;constructor(t={}){let e=t.sessionName??"default";if(!/^[a-zA-Z0-9_-]+$/.test(e))throw new Error(`Invalid sessionName "${e}": must match /^[a-zA-Z0-9_-]+$/`);this.config={sessionName:e,timeout:t.timeout??3e4,headed:t.headed??!1,debug:t.debug??!1}}async execute(t,e=[]){let r=this.buildArgs(t,e);this.config.debug&&console.log(`[agent-browser] Executing: npx agent-browser ${r.join(" ")}`);try{let i=await La(r,this.config.timeout,10485760);if(i.error)return{success:!1,error:i.error.message};if(i.status!==0)return{success:!1,error:i.stderr?.trim()||`Exit code: ${i.status}`};let n=i.stdout?.trim()??"";try{return{success:!0,data:D(n)}}catch{return{success:!0,data:n}}}catch(i){return{success:!1,error:P(i)}}}async executeAsync(t,e=[]){return new Promise(r=>{let i=this.buildArgs(t,e);this.config.debug&&console.log(`[agent-browser] Executing async: npx agent-browser ${i.join(" ")}`);let n=bC("npx",["agent-browser",...i],{timeout:this.config.timeout}),s="",a="";n.stdout?.on("data",o=>{s+=o.toString()}),n.stderr?.on("data",o=>{a+=o.toString()}),n.on("close",o=>{if(o===0)try{let l=D(s.trim());r({success:!0,data:l})}catch{r({success:!0,data:s.trim()})}else r({success:!1,error:a||`Exit code: ${o}`})}),n.on("error",o=>{r({success:!1,error:o.message})})})}async open(t){let e=[t];this.config.headed&&e.push("--headed");let r=await this.execute("open",e);return r.success&&(this.browserLaunched=!0),r}async close(){let t=await this.execute("close");return t.success&&(this.browserLaunched=!1),t}async terminateDaemon(){try{await this.close();let t=this.config.sessionName;try{await Yc("pkill",["-f",`agent-browser.*--session[= ]${t}`],{cwd:process.cwd(),timeout:5e3})}catch{}return this.browserLaunched=!1,{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Failed to terminate daemon"}}}async snapshot(t){let e=["--json"];return t?.interactive&&e.push("-i"),t?.compact&&e.push("-c"),t?.depth&&e.push("-d",String(t.depth)),this.execute("snapshot",e)}async click(t){return this.execute("click",[t])}async fill(t,e){return this.execute("fill",[t,e])}async type(t,e){return this.execute("type",[t,e])}async getText(t){return this.execute("get",["text",t,"--json"])}async isVisible(t){let e=await this.execute("is",["visible",t,"--json"]);return e.success&&e.data?{success:!0,data:e.data.success}:{success:!1,error:e.error}}async screenshot(t,e){let r=[];return t&&r.push(t),e&&r.push("--full"),t||r.push("--json"),this.execute("screenshot",r)}async waitForElement(t,e){let r=[t];return e?this.execute("wait",r):this.execute("wait",r)}async waitForText(t){return this.execute("wait",["--text",t])}async waitForUrl(t){let e=t.includes("*")?t:`**${t}**`;return this.execute("wait",["--url",e])}async waitForNetworkIdle(){return this.execute("wait",["--load","networkidle"])}async setDevice(t){return this.execute("set",["device",t])}async setViewport(t,e){return this.execute("set",["viewport",String(t),String(e)])}async mockRoute(t,e){let r=JSON.stringify(e);return this.execute("network",["route",t,"--body",r])}async abortRoute(t){return this.execute("network",["route",t,"--abort"])}async clearRoutes(){return this.execute("network",["unroute"])}async saveState(t){return this.execute("state",["save",t])}async loadState(t){return this.execute("state",["load",t])}async startTrace(){return this.execute("trace",["start"])}async stopTrace(t){let e=await this.execute("trace",["stop",t]);return e.success?{success:!0,data:t}:{success:!1,error:e.error}}async eval(t){return this.execute("eval",[t,"--json"])}getSessionName(){return this.config.sessionName}isBrowserLaunched(){return this.browserLaunched}buildArgs(t,e){let r=[];return this.config.sessionName!=="default"&&r.push("--session",this.config.sessionName),r.push(t,...e),r}};async function tg(){try{let c=await La([],1e4),t=(c.stdout??"")+(c.stderr??"");return t.includes("agent-browser")&&t.includes("Usage:")}catch{return!1}}X();var rg=new Set(["button","link","textbox","checkbox","radio","combobox","listbox","menuitem","menuitemcheckbox","menuitemradio","option","searchbox","slider","spinbutton","switch","tab","treeitem"]);var cu=class{parse(t){let e=t.split(`
2309
2309
  `),r=[],i=new Map,n=0;for(let a of e){let o=this.parseLine(a);o&&(r.push(o),i.set(o.ref,o),o.depth>n&&(n=o.depth))}this.buildRelationships(r);let s=r.filter(a=>rg.has(a.role.toLowerCase()));return{rawTree:t,elements:r,interactiveElements:s,refMap:i,stats:{totalElements:r.length,interactiveCount:s.length,maxDepth:n},parsedAt:new Date}}parseJson(t){let e=typeof t=="string"?D(t):t;if(e.success&&e.data){let r=e.data.snapshot||e.data,i=e.data.refs||{};return this.parseWithRefs(r,i)}if(typeof e=="string")return this.parse(e);throw new Error("Invalid snapshot JSON format")}parseWithRefs(t,e){let r=[],i=new Map,n=0;for(let[o,l]of Object.entries(e)){let u={ref:o,refWithAt:`@${o}`,role:l.role,name:l.name,attributes:{},depth:0,children:[]};r.push(u),i.set(o,u)}let s=this.parse(t);for(let o of s.elements){let l=i.get(o.ref);l&&(l.text=o.text,l.depth=o.depth,l.level=o.level,o.depth>n&&(n=o.depth))}let a=r.filter(o=>rg.has(o.role.toLowerCase()));return{rawTree:t,elements:r,interactiveElements:a,refMap:i,stats:{totalElements:r.length,interactiveCount:a.length,maxDepth:n},parsedAt:new Date}}parseLine(t){if(!t.trim())return null;let e=this.getIndentLevel(t),r=t.match(/^(\s*-\s*)(\w+)(?:\s+"([^"]*)")?(.*)$/);if(!r)return null;let[,,i,n,s]=r,a=s?.match(/\[ref=(\w+)\]/);if(!a)return null;let o=a[1],l=s?.match(/\[level=(\d+)\]/),u=l?parseInt(l[1],10):void 0,d=s?.match(/\[nth=(\d+)\]/),m=d?parseInt(d[1],10):void 0,p=t.match(/:\s*(.+)$/),h=p?p[1].trim():void 0,v={};return u&&(v.level=String(u)),m!==void 0&&(v.nth=String(m)),{ref:o,refWithAt:`@${o}`,role:i.toLowerCase(),name:n,text:h,level:u,attributes:v,depth:e,children:[]}}getIndentLevel(t){let e=t.match(/^(\s*)/);return e?Math.floor(e[1].length/2):0}buildRelationships(t){let e=[];for(let r of t){for(;e.length>0&&e[e.length-1].depth>=r.depth;)e.pop();if(e.length>0){let i=e[e.length-1];r.parent=i.ref,i.children.push(r.ref)}e.push(r)}}findByRef(t,e){let r=e.startsWith("@")?e.slice(1):e;return t.refMap.get(r)||null}findByRole(t,e){return t.elements.filter(r=>r.role.toLowerCase()===e.toLowerCase())}findByName(t,e,r=!1){return t.elements.filter(i=>i.name?r?i.name===e:i.name.toLowerCase().includes(e.toLowerCase()):!1)}findByText(t,e,r=!1){return t.elements.filter(i=>{let n=i.text||i.name||"";return r?n===e:n.toLowerCase().includes(e.toLowerCase())})}findInteractive(t,e){for(let r of t.interactiveElements)if(!(e.role&&r.role.toLowerCase()!==e.role.toLowerCase())&&!(e.name&&r.name!==e.name)&&!(e.text&&!(r.text||r.name||"").toLowerCase().includes(e.text.toLowerCase())))return r;return null}refToCssSelector(t,e){let r=this.findByRef(t,e);if(!r)return null;let i=r.role,n=r.name;return{button:n?`button:has-text("${n}")`:"button",link:n?`a:has-text("${n}")`:"a",textbox:n?`input[placeholder="${n}"], input[aria-label="${n}"]`:'input[type="text"]',heading:n?`h1:has-text("${n}"), h2:has-text("${n}"), h3:has-text("${n}")`:"h1, h2, h3",checkbox:n?`input[type="checkbox"][aria-label="${n}"]`:'input[type="checkbox"]'}[i]||`[role="${i}"]`}},ou=null;function ig(){return ou||(ou=new cu),ou}k();var $a=class{constructor(t){this.defaultConfig=t}defaultConfig;sessions=new Map;activeSession=null;sessionCounter=0;async createSession(t){let e=t?.name??this.generateSessionName();if(this.sessions.has(e))throw new Error(`Session "${e}" already exists`);let r=new Kt({sessionName:e,headed:t?.headed??this.defaultConfig?.headed??!1,timeout:t?.timeout??this.defaultConfig?.timeout??3e4}),i={name:e,createdAt:new Date,lastActivity:new Date,status:"idle",executor:r};return this.sessions.set(e,i),t?.initialUrl&&(await r.open(t.initialUrl)).success&&(i.currentUrl=t.initialUrl,i.status="active"),this.activeSession||(this.activeSession=e),i}async getOrCreateSession(t,e){let r=this.sessions.get(t);return r||this.createSession({...e,name:t})}getSession(t){return this.sessions.get(t)}getActiveSession(){if(this.activeSession)return this.sessions.get(this.activeSession)}switchSession(t){if(!this.sessions.has(t))throw new Error(`Session "${t}" not found`);this.activeSession=t}listSessions(){return Array.from(this.sessions.values())}async listCliSessions(){try{let t=await La(["session","list"],5e3);if(t.error||t.status!==0)return[];let r=t.stdout.split(`
2310
- `),i=[];for(let n of r){let s=n.match(/^\s*(?:->)?\s*(\w+)\s*$/);s&&i.push(s[1])}return i}catch{return[]}}async closeSession(t){let e=this.sessions.get(t);if(!e)return{success:!1,error:`Session "${t}" not found`};let r=await e.executor.terminateDaemon();if(r.success&&(e.status="closed",this.sessions.delete(t),this.activeSession===t)){let i=Array.from(this.sessions.keys());this.activeSession=i.length>0?i[0]:null}return r}async closeAllSessions(){let t=Array.from(this.sessions.keys());for(let e of t)await this.closeSession(e);this.sessions.clear(),this.activeSession=null}async cleanupIdleSessions(t=300*1e3){let e=Date.now(),r=0;for(let[i,n]of this.sessions)n.status==="idle"&&e-n.lastActivity.getTime()>t&&(await this.closeSession(i),r++);return r}getExecutor(){let t=this.getActiveSession();if(!t)throw new Error("No active session. Create one first.");return t.executor}getSessionExecutor(t){let e=this.sessions.get(t);if(!e)throw new Error(`Session "${t}" not found`);return e.executor}touchSession(t){let e=this.sessions.get(t);e&&(e.lastActivity=new Date)}updateSessionUrl(t,e){let r=this.sessions.get(t);r&&(r.currentUrl=e,r.lastActivity=new Date,r.status="active")}generateSessionName(){return`session-${++this.sessionCounter}-${Date.now().toString(36)}`}getStats(){let t=0,e=0,r=0;for(let i of this.sessions.values())switch(i.status){case"active":t++;break;case"idle":e++;break;case"closed":r++;break}return{totalSessions:this.sessions.size,activeSessions:t,idleSessions:e,closedSessions:r,activeSessionName:this.activeSession}}};X();function $n(c){if(typeof c=="string")return/^@?e\d+$/.test(c)?c.startsWith("@")?c:`@${c}`:c;switch(c.type){case"ref":return c.value.startsWith("@")?c.value:`@${c.value}`;case"css":return c.value;case"xpath":return`xpath=${c.value}`;case"text":return`text=${c.value}`;default:return c.value}}function re(c){return{success:!0,value:c}}function B(c){return{success:!1,error:c}}function Oa(c){return{id:c.name,tool:"agent-browser",status:c.status,currentUrl:c.currentUrl,createdAt:c.createdAt}}function wC(c){let t=c.elements.map(i=>({ref:i.refWithAt,role:i.role,name:i.name,text:i.text,depth:i.depth})),e=c.interactiveElements.map(i=>({ref:i.refWithAt,role:i.role,name:i.name,text:i.text,depth:i.depth})),r=new Map;for(let i of t)r.set(i.ref,i);return{url:c.url??"",title:c.title??"",elements:t,interactiveElements:e,refMap:r,timestamp:c.parsedAt}}var ui=class{tool="agent-browser";executor;sessionManager;snapshotParser;config;isLaunched=!1;currentSessionId=null;constructor(t={}){this.config={headed:t.headed??!1,timeout:t.timeout??3e4,debug:t.debug??!1,sessionName:t.sessionName??"default"};let e={sessionName:this.config.sessionName,timeout:this.config.timeout,headed:this.config.headed,debug:this.config.debug};this.executor=new Kt(e),this.sessionManager=new $a({headed:this.config.headed,timeout:this.config.timeout}),this.snapshotParser=ig()}async launch(t){try{if(this.isLaunched&&this.currentSessionId){let n=this.sessionManager.getSession(this.currentSessionId);if(n)return t?.viewport&&await this.setViewport(t.viewport.width,t.viewport.height),re(Oa(n))}if(!await this.isAvailable())return B(new ue("agent-browser","agent-browser CLI is not available"));let r=t?.sessionName??this.config.sessionName,i=await this.sessionManager.createSession({name:r,headed:t?.headless===!1||this.config.headed,timeout:this.config.timeout});return this.currentSessionId=i.name,this.isLaunched=!0,this.executor=new Kt({sessionName:i.name,timeout:this.config.timeout,headed:t?.headless===!1||this.config.headed,debug:this.config.debug}),t?.viewport&&await this.setViewport(t.viewport.width,t.viewport.height),t?.deviceName&&await this.setDevice(t.deviceName),re(Oa(i))}catch(e){let r=new V(P(e),"LAUNCH_FAILED","agent-browser",e instanceof Error?e:void 0);return B(r)}}async quit(){try{if(this.currentSessionId){let t=await this.sessionManager.closeSession(this.currentSessionId);t.success||this.config.debug&&console.warn(`[agent-browser] Session close warning: ${t.error}`)}if(this.executor)try{await this.executor.terminateDaemon()}catch(t){console.debug("[AgentBrowserClient] Daemon termination error:",t instanceof Error?t.message:t)}return this.isLaunched=!1,this.currentSessionId=null,re(void 0)}catch(t){return this.isLaunched=!1,this.currentSessionId=null,B(new V(P(t),"QUIT_FAILED","agent-browser",t instanceof Error?t:void 0))}}async isAvailable(){return tg()}async dispose(){await this.sessionManager.closeAllSessions(),this.isLaunched=!1,this.currentSessionId=null}async navigate(t){let e=Date.now();try{let r=await this.executor.open(t);if(!r.success)return B(new V(r.error??"Navigation failed","NAVIGATION_FAILED","agent-browser"));this.currentSessionId&&this.sessionManager.updateSessionUrl(this.currentSessionId,t);let i=await this.executor.eval("JSON.stringify({ title: document.title, url: window.location.href })"),n=i.success&&i.data?typeof i.data=="string"?D(i.data):i.data:{title:"",url:t};return re({url:n.url||t,title:n.title||"",success:!0,durationMs:Date.now()-e})}catch(r){return B(new V(P(r),"NAVIGATION_FAILED","agent-browser",r instanceof Error?r:void 0))}}async reload(){try{let t=await this.executor.eval("window.location.reload()");return t.success?re(void 0):B(new V(t.error??"Reload failed","RELOAD_FAILED","agent-browser"))}catch(t){return B(new V(P(t),"RELOAD_FAILED","agent-browser",t instanceof Error?t:void 0))}}async goBack(){try{let t=await this.executor.eval("window.history.back()");return t.success?re(void 0):B(new V(t.error??"Go back failed","HISTORY_FAILED","agent-browser"))}catch(t){return B(new V(P(t),"HISTORY_FAILED","agent-browser",t instanceof Error?t:void 0))}}async goForward(){try{let t=await this.executor.eval("window.history.forward()");return t.success?re(void 0):B(new V(t.error??"Go forward failed","HISTORY_FAILED","agent-browser"))}catch(t){return B(new V(P(t),"HISTORY_FAILED","agent-browser",t instanceof Error?t:void 0))}}async click(t){try{let e=$n(t),r=await this.executor.click(e);return r.success?re(void 0):B(new Dr("agent-browser",t,new Error(r.error)))}catch(e){return B(new V(P(e),"CLICK_FAILED","agent-browser",e instanceof Error?e:void 0))}}async fill(t,e){try{let r=$n(t),i=await this.executor.fill(r,e);return i.success?re(void 0):B(new Dr("agent-browser",t,new Error(i.error)))}catch(r){return B(new V(P(r),"FILL_FAILED","agent-browser",r instanceof Error?r:void 0))}}async getText(t){try{let e=$n(t),r=await this.executor.getText(e);if(!r.success)return B(new Dr("agent-browser",t,new Error(r.error)));let i=r.data;if(i&&typeof i=="object"){let n=i;if("text"in n)i=n.text;else if("data"in n&&typeof n.data=="object"){let s=n.data;"text"in s?i=s.text:"result"in s&&(i=s.result)}else"result"in n&&(i=n.result)}return re(String(i??""))}catch(e){return B(new V(P(e),"GET_TEXT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async isVisible(t){try{let e=$n(t),r=await this.executor.isVisible(e);return r.success?re(!!r.data):re(!1)}catch(e){return B(new V(P(e),"VISIBILITY_CHECK_FAILED","agent-browser",e instanceof Error?e:void 0))}}async screenshot(t){try{let e=await this.executor.screenshot(t?.path,t?.fullPage);if(!e.success)return B(new V(e.error??"Screenshot failed","SCREENSHOT_FAILED","agent-browser"));let r=await this.executor.eval("JSON.stringify({ width: window.innerWidth, height: window.innerHeight })"),i={width:1280,height:720};if(r.success&&r.data){let n=typeof r.data=="string"?D(r.data):r.data;i={width:n.width||1280,height:n.height||720}}return re({base64:t?.path?void 0:String(e.data??""),path:t?.path,format:"png",dimensions:i})}catch(e){return B(new V(P(e),"SCREENSHOT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async evaluate(t){try{let e=await this.executor.eval(t);if(!e.success)return B(new V(e.error??"Evaluation failed","EVAL_FAILED","agent-browser"));let r=e.data;if(r&&typeof r=="object"){let i=r;if("data"in i&&i.data&&typeof i.data=="object"){let n=i.data;"result"in n&&(r=n.result)}else"result"in i&&(r=i.result)}return re(r)}catch(e){return B(new V(P(e),"EVAL_FAILED","agent-browser",e instanceof Error?e:void 0))}}async getSnapshot(t){try{let e=await this.executor.snapshot({interactive:t?.interactive,depth:t?.depth});if(!e.success)return B(new V(e.error??"Snapshot failed","SNAPSHOT_FAILED","agent-browser"));let r;try{r=this.snapshotParser.parseJson(e.data)}catch{r=this.snapshotParser.parse(String(e.data))}let i=await this.executor.eval("window.location.href"),n=await this.executor.eval("document.title");return i.success&&(r.url=String(i.data)),n.success&&(r.title=String(n.data)),re(wC(r))}catch(e){return B(new V(P(e),"SNAPSHOT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async createSession(t){try{let e=await this.sessionManager.createSession({name:t});return re(Oa(e))}catch(e){return B(new V(P(e),"SESSION_CREATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async switchSession(t){try{return this.sessionManager.switchSession(t),this.currentSessionId=t,this.executor=new Kt({sessionName:t,timeout:this.config.timeout,headed:this.config.headed,debug:this.config.debug}),re(void 0)}catch(e){return B(new V(P(e),"SESSION_SWITCH_FAILED","agent-browser",e instanceof Error?e:void 0))}}async listSessions(){try{let t=this.sessionManager.listSessions();return re(t.map(Oa))}catch(t){return B(new V(P(t),"SESSION_LIST_FAILED","agent-browser",t instanceof Error?t:void 0))}}async mockRoute(t,e){try{let r={status:e.status??200,body:e.body,headers:e.headers},i=await this.executor.mockRoute(t,r);return i.success?re(void 0):B(new V(i.error??"Mock route failed","MOCK_ROUTE_FAILED","agent-browser"))}catch(r){return B(new V(P(r),"MOCK_ROUTE_FAILED","agent-browser",r instanceof Error?r:void 0))}}async abortRoute(t){try{let e=await this.executor.abortRoute(t);return e.success?re(void 0):B(new V(e.error??"Abort route failed","ABORT_ROUTE_FAILED","agent-browser"))}catch(e){return B(new V(P(e),"ABORT_ROUTE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async clearRoutes(){try{let t=await this.executor.clearRoutes();return t.success?re(void 0):B(new V(t.error??"Clear routes failed","CLEAR_ROUTES_FAILED","agent-browser"))}catch(t){return B(new V(P(t),"CLEAR_ROUTES_FAILED","agent-browser",t instanceof Error?t:void 0))}}async setDevice(t){try{let e=await this.executor.setDevice(t);return e.success?re(void 0):B(new V(e.error??"Set device failed","SET_DEVICE_FAILED","agent-browser"))}catch(e){return B(new V(P(e),"SET_DEVICE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async setViewport(t,e){try{let r=await this.executor.setViewport(t,e);return r.success?re(void 0):B(new V(r.error??"Set viewport failed","SET_VIEWPORT_FAILED","agent-browser"))}catch(r){return B(new V(P(r),"SET_VIEWPORT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async saveState(t){try{let e=await this.executor.saveState(t);return e.success?re(void 0):B(new V(e.error??"Save state failed","SAVE_STATE_FAILED","agent-browser"))}catch(e){return B(new V(P(e),"SAVE_STATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async loadState(t){try{let e=await this.executor.loadState(t);return e.success?re(void 0):B(new V(e.error??"Load state failed","LOAD_STATE_FAILED","agent-browser"))}catch(e){return B(new V(P(e),"LOAD_STATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async waitForElement(t,e){try{let r=$n(t),i=await this.executor.waitForElement(r,e);return i.success?re(void 0):B(new Qt("agent-browser",`waitForElement(${r})`,new Error(i.error)))}catch(r){return B(new V(P(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForText(t,e){try{let r=await this.executor.waitForText(t);return r.success?re(void 0):B(new Qt("agent-browser",`waitForText("${t}")`,new Error(r.error)))}catch(r){return B(new V(P(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForUrl(t,e){try{let r=await this.executor.waitForUrl(t);return r.success?re(void 0):B(new Qt("agent-browser",`waitForUrl("${t}")`,new Error(r.error)))}catch(r){return B(new V(P(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForNetworkIdle(t){try{let e=await this.executor.waitForNetworkIdle();return e.success?re(void 0):B(new Qt("agent-browser","waitForNetworkIdle",new Error(e.error)))}catch(e){return B(new V(P(e),"WAIT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async startTrace(){try{let t=await this.executor.startTrace();return t.success?re(void 0):B(new V(t.error??"Start trace failed","START_TRACE_FAILED","agent-browser"))}catch(t){return B(new V(P(t),"START_TRACE_FAILED","agent-browser",t instanceof Error?t:void 0))}}async stopTrace(t){try{let e=await this.executor.stopTrace(t);return e.success?re(e.data??t):B(new V(e.error??"Stop trace failed","STOP_TRACE_FAILED","agent-browser"))}catch(e){return B(new V(P(e),"STOP_TRACE_FAILED","agent-browser",e instanceof Error?e:void 0))}}};import{randomUUID as cg}from"crypto";var Na={persistentContext:!0,cloudflareWaitSeconds:0,resourceBlocking:"functional"};var CC=new Set(["google-analytics.com","googletagmanager.com","analytics.google.com","hotjar.com","fullstory.com","segment.io","segment.com","mixpanel.com","heap.io","heapanalytics.com","amplitude.com","mouseflow.com","crazyegg.com","optimizely.com","newrelic.com","nr-data.net","sentry.io","bugsnag.com","logrocket.com","clarity.ms","facebook.net","connect.facebook.net"]),SC=new Set(["doubleclick.net","googlesyndication.com","googleadservices.com","google-analytics.com","adservice.google.com","pagead2.googlesyndication.com","ads.twitter.com","ads-api.twitter.com","adsserver.com","adnxs.com","amazon-adsystem.com","criteo.com","moatads.com","outbrain.com","taboola.com","bidswitch.net","rubiconproject.com"]),RC={image:"image",font:"font",media:"media",stylesheet:"stylesheet",websocket:"websocket"},ng={functional:{enabled:!0,blockedCategories:["image","font","media","stylesheet","tracking","advertising"]},visual:{enabled:!1,blockedCategories:[]},performance:{enabled:!0,blockedCategories:["image","font","media","tracking","advertising"]}};function lu(c,t,e){if(!e.enabled)return!1;if(e.allowPatterns?.length){for(let i of e.allowPatterns)if(ag(c,i))return!1}if(e.blockPatterns?.length){for(let i of e.blockPatterns)if(ag(c,i))return!0}let r=RC[t];return!!(r&&e.blockedCategories.includes(r)||e.blockedCategories.includes("tracking")&&og(c,CC)||e.blockedCategories.includes("advertising")&&og(c,SC))}function On(c){if(typeof c=="object")return c;let t=ng[c];return t?{...t,blockedCategories:[...t.blockedCategories]}:ng.visual}var sg=new Map;function ag(c,t){let e=sg.get(t);if(!e){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");e=new RegExp(r,"i"),sg.set(t,e)}return e.test(c)}function og(c,t){try{let e=new URL(c).hostname;for(let r of t)if(e===r||e.endsWith(`.${r}`))return!0}catch{}return!1}var _a=null,lg=!1;function ug(){if(lg)return _a;lg=!0;try{_a=mm("patchright")}catch{_a=null}return _a}var Jt=class{tool="stealth";stealthConfig;page=null;context=null;browser=null;sessionId=null;constructor(t){this.stealthConfig={...Na,...t}}async isAvailable(){return ug()!==null}async launch(t){let e=ug();if(!e)return{success:!1,error:new ue("stealth","Patchright is not installed. Install with: npm install patchright")};try{let r={headless:t?.headless??!0};if(t?.viewport&&(r.viewport=t.viewport),t?.args&&(r.args=t.args),this.stealthConfig.userAgent&&(r.userAgent=this.stealthConfig.userAgent),this.stealthConfig.proxy&&(r.proxy=this.stealthConfig.proxy),this.stealthConfig.persistentContext){let i=this.stealthConfig.userDataDir||`/tmp/stealth-browser-${cg()}`;this.context=await e.chromium.launchPersistentContext(i,r);let n=this.context.pages();this.page=n.length>0?n[0]:await this.context.newPage()}else this.browser=await e.chromium.launch(r),this.page=await this.browser.newPage();return await this.applyResourceBlocking(),this.sessionId=cg(),{success:!0,value:{id:this.sessionId,tool:"stealth",status:"active",createdAt:new Date}}}catch(r){return{success:!1,error:new V(`Failed to launch stealth browser: ${r instanceof Error?r.message:String(r)}`,"LAUNCH_FAILED","stealth",r instanceof Error?r:void 0)}}}async quit(){try{return this.context&&(await this.context.close(),this.context=null),this.browser&&(await this.browser.close(),this.browser=null),this.page=null,this.sessionId=null,{success:!0,value:void 0}}catch(t){return{success:!1,error:new V("Failed to quit stealth browser","QUIT_FAILED","stealth",t instanceof Error?t:void 0)}}}async navigate(t){if(!this.page)return this.notLaunched();try{let e=Date.now(),i=(await this.page.goto(t,{waitUntil:"domcontentloaded"}))?.status()??void 0;this.stealthConfig.cloudflareWaitSeconds>0&&await this.waitForCloudflare();let n=await this.page.title();return{success:!0,value:{url:this.page.url(),title:n,success:!0,durationMs:Date.now()-e,statusCode:i??void 0}}}catch(e){return this.wrapError("navigate",e)}}async reload(){if(!this.page)return this.notLaunched();try{return await this.page.reload(),{success:!0,value:void 0}}catch(t){return this.wrapError("reload",t)}}async goBack(){if(!this.page)return this.notLaunched();try{return await this.page.goBack(),{success:!0,value:void 0}}catch(t){return this.wrapError("goBack",t)}}async goForward(){if(!this.page)return this.notLaunched();try{return await this.page.goForward(),{success:!0,value:void 0}}catch(t){return this.wrapError("goForward",t)}}async click(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return await this.page.click(e),{success:!0,value:void 0}}catch(e){return this.wrapError("click",e)}}async fill(t,e){if(!this.page)return this.notLaunched();try{let r=this.resolveSelector(t);return await this.page.fill(r,e),{success:!0,value:void 0}}catch(r){return this.wrapError("fill",r)}}async getText(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return{success:!0,value:await this.page.textContent(e)??""}}catch(e){return this.wrapError("getText",e)}}async isVisible(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return{success:!0,value:await this.page.isVisible(e)}}catch(e){return this.wrapError("isVisible",e)}}async screenshot(t){if(!this.page)return this.notLaunched();try{return{success:!0,value:{base64:(await this.page.screenshot({path:t?.path,fullPage:t?.fullPage,type:"png"})).toString("base64"),path:t?.path,format:"png",dimensions:{width:0,height:0}}}}catch(e){return this.wrapError("screenshot",e)}}async evaluate(t){if(!this.page)return this.notLaunched();try{return{success:!0,value:await this.page.evaluate(t)}}catch(e){return this.wrapError("evaluate",e)}}async dispose(){await this.quit()}resolveSelector(t){if(typeof t=="string")return t;switch(t.type){case"css":return t.value;case"xpath":return`xpath=${t.value}`;case"text":return`text=${t.value}`;case"ref":return t.value;default:return t.value}}async applyResourceBlocking(){if(!this.page||!this.stealthConfig.resourceBlocking)return;let t=typeof this.stealthConfig.resourceBlocking=="string"?On(this.stealthConfig.resourceBlocking):this.stealthConfig.resourceBlocking;t.enabled&&await this.page.route("**/*",e=>{let r=e.request().url(),i=e.request().resourceType();lu(r,i,t)?e.abort().catch(()=>{}):e.continue().catch(()=>{})})}async waitForCloudflare(){if(!this.page||this.stealthConfig.cloudflareWaitSeconds<=0)return;let t=this.stealthConfig.cloudflareWaitSeconds*1e3,e=Date.now();for(;Date.now()-e<t;){try{let r=await this.page.title();if(!r.includes("Just a moment")&&!r.includes("Checking your browser"))return}catch{}await new Promise(r=>setTimeout(r,500))}}notLaunched(){return{success:!1,error:new V("Stealth browser not launched. Call launch() first.","NOT_LAUNCHED","stealth")}}wrapError(t,e){return{success:!1,error:new V(`Stealth ${t} failed: ${e instanceof Error?e.message:String(e)}`,"OPERATION_FAILED","stealth",e instanceof Error?e:void 0)}}};async function uu(){return!1}async function mu(){try{return await new ui().isAvailable()}catch{return!1}}var TC=["e2e-testing","api-mocking","responsive-testing","auth-testing"],EC=["stealth-testing"];function AC(c){return TC.includes(c)}var Va=class{tool="vibium";async isAvailable(){return!1}async launch(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async quit(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async navigate(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async reload(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async goBack(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async goForward(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async click(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async fill(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async getText(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async isVisible(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async screenshot(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async evaluate(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async dispose(){}};async function pu(c={}){let{preference:t="auto",useCase:e}=c;if(e&&EC.includes(e)&&await du())return new Jt;if(e&&AC(e)||t==="agent-browser")return Nn();if(t==="stealth"){if(await du())return new Jt;throw new ue("stealth","Patchright is not installed")}if(t==="vibium"){if(await uu())return new Va;throw new ue("vibium","Vibium is not available")}return await uu()?new Va:(await mu(),Nn())}async function Nn(){return new ui}async function za(c){return pu({useCase:c})}async function du(){try{return await new Jt().isAvailable()}catch{return!1}}import{exec as PC}from"child_process";import{promisify as kC}from"util";k();X();Xc();Yr();var B1=kC(PC);k();var dg={enabled:!0,similarityThreshold:.6,maxFingerprintsPerPage:200,namespace:"aqe/adaptive-locators",fallbackChain:["text","aria","fingerprint"]};function DC(c){return`
2310
+ `),i=[];for(let n of r){let s=n.match(/^\s*(?:->)?\s*(\w+)\s*$/);s&&i.push(s[1])}return i}catch{return[]}}async closeSession(t){let e=this.sessions.get(t);if(!e)return{success:!1,error:`Session "${t}" not found`};let r=await e.executor.terminateDaemon();if(r.success&&(e.status="closed",this.sessions.delete(t),this.activeSession===t)){let i=Array.from(this.sessions.keys());this.activeSession=i.length>0?i[0]:null}return r}async closeAllSessions(){let t=Array.from(this.sessions.keys());for(let e of t)await this.closeSession(e);this.sessions.clear(),this.activeSession=null}async cleanupIdleSessions(t=300*1e3){let e=Date.now(),r=0;for(let[i,n]of this.sessions)n.status==="idle"&&e-n.lastActivity.getTime()>t&&(await this.closeSession(i),r++);return r}getExecutor(){let t=this.getActiveSession();if(!t)throw new Error("No active session. Create one first.");return t.executor}getSessionExecutor(t){let e=this.sessions.get(t);if(!e)throw new Error(`Session "${t}" not found`);return e.executor}touchSession(t){let e=this.sessions.get(t);e&&(e.lastActivity=new Date)}updateSessionUrl(t,e){let r=this.sessions.get(t);r&&(r.currentUrl=e,r.lastActivity=new Date,r.status="active")}generateSessionName(){return`session-${++this.sessionCounter}-${Date.now().toString(36)}`}getStats(){let t=0,e=0,r=0;for(let i of this.sessions.values())switch(i.status){case"active":t++;break;case"idle":e++;break;case"closed":r++;break}return{totalSessions:this.sessions.size,activeSessions:t,idleSessions:e,closedSessions:r,activeSessionName:this.activeSession}}};X();function $n(c){if(typeof c=="string")return/^@?e\d+$/.test(c)?c.startsWith("@")?c:`@${c}`:c;switch(c.type){case"ref":return c.value.startsWith("@")?c.value:`@${c.value}`;case"css":return c.value;case"xpath":return`xpath=${c.value}`;case"text":return`text=${c.value}`;default:return c.value}}function re(c){return{success:!0,value:c}}function B(c){return{success:!1,error:c}}function Oa(c){return{id:c.name,tool:"agent-browser",status:c.status,currentUrl:c.currentUrl,createdAt:c.createdAt}}function wC(c){let t=c.elements.map(i=>({ref:i.refWithAt,role:i.role,name:i.name,text:i.text,depth:i.depth})),e=c.interactiveElements.map(i=>({ref:i.refWithAt,role:i.role,name:i.name,text:i.text,depth:i.depth})),r=new Map;for(let i of t)r.set(i.ref,i);return{url:c.url??"",title:c.title??"",elements:t,interactiveElements:e,refMap:r,timestamp:c.parsedAt}}var ui=class{tool="agent-browser";executor;sessionManager;snapshotParser;config;isLaunched=!1;currentSessionId=null;constructor(t={}){this.config={headed:t.headed??!1,timeout:t.timeout??3e4,debug:t.debug??!1,sessionName:t.sessionName??"default"};let e={sessionName:this.config.sessionName,timeout:this.config.timeout,headed:this.config.headed,debug:this.config.debug};this.executor=new Kt(e),this.sessionManager=new $a({headed:this.config.headed,timeout:this.config.timeout}),this.snapshotParser=ig()}async launch(t){try{if(this.isLaunched&&this.currentSessionId){let n=this.sessionManager.getSession(this.currentSessionId);if(n)return t?.viewport&&await this.setViewport(t.viewport.width,t.viewport.height),re(Oa(n))}if(!await this.isAvailable())return B(new ue("agent-browser","agent-browser CLI is not available"));let r=t?.sessionName??this.config.sessionName,i=await this.sessionManager.createSession({name:r,headed:t?.headless===!1||this.config.headed,timeout:this.config.timeout});return this.currentSessionId=i.name,this.isLaunched=!0,this.executor=new Kt({sessionName:i.name,timeout:this.config.timeout,headed:t?.headless===!1||this.config.headed,debug:this.config.debug}),t?.viewport&&await this.setViewport(t.viewport.width,t.viewport.height),t?.deviceName&&await this.setDevice(t.deviceName),re(Oa(i))}catch(e){let r=new V(P(e),"LAUNCH_FAILED","agent-browser",e instanceof Error?e:void 0);return B(r)}}async quit(){try{if(this.currentSessionId){let t=await this.sessionManager.closeSession(this.currentSessionId);t.success||this.config.debug&&console.warn(`[agent-browser] Session close warning: ${t.error}`)}if(this.executor)try{await this.executor.terminateDaemon()}catch(t){console.debug("[AgentBrowserClient] Daemon termination error:",t instanceof Error?t.message:t)}return this.isLaunched=!1,this.currentSessionId=null,re(void 0)}catch(t){return this.isLaunched=!1,this.currentSessionId=null,B(new V(P(t),"QUIT_FAILED","agent-browser",t instanceof Error?t:void 0))}}async isAvailable(){return tg()}async dispose(){await this.sessionManager.closeAllSessions(),this.isLaunched=!1,this.currentSessionId=null}async navigate(t){let e=Date.now();try{let r=await this.executor.open(t);if(!r.success)return B(new V(r.error??"Navigation failed","NAVIGATION_FAILED","agent-browser"));this.currentSessionId&&this.sessionManager.updateSessionUrl(this.currentSessionId,t);let i=await this.executor.eval("JSON.stringify({ title: document.title, url: window.location.href })"),n=i.success&&i.data?typeof i.data=="string"?D(i.data):i.data:{title:"",url:t};return re({url:n.url||t,title:n.title||"",success:!0,durationMs:Date.now()-e})}catch(r){return B(new V(P(r),"NAVIGATION_FAILED","agent-browser",r instanceof Error?r:void 0))}}async reload(){try{let t=await this.executor.eval("window.location.reload()");return t.success?re(void 0):B(new V(t.error??"Reload failed","RELOAD_FAILED","agent-browser"))}catch(t){return B(new V(P(t),"RELOAD_FAILED","agent-browser",t instanceof Error?t:void 0))}}async goBack(){try{let t=await this.executor.eval("window.history.back()");return t.success?re(void 0):B(new V(t.error??"Go back failed","HISTORY_FAILED","agent-browser"))}catch(t){return B(new V(P(t),"HISTORY_FAILED","agent-browser",t instanceof Error?t:void 0))}}async goForward(){try{let t=await this.executor.eval("window.history.forward()");return t.success?re(void 0):B(new V(t.error??"Go forward failed","HISTORY_FAILED","agent-browser"))}catch(t){return B(new V(P(t),"HISTORY_FAILED","agent-browser",t instanceof Error?t:void 0))}}async click(t){try{let e=$n(t),r=await this.executor.click(e);return r.success?re(void 0):B(new Dr("agent-browser",t,new Error(r.error)))}catch(e){return B(new V(P(e),"CLICK_FAILED","agent-browser",e instanceof Error?e:void 0))}}async fill(t,e){try{let r=$n(t),i=await this.executor.fill(r,e);return i.success?re(void 0):B(new Dr("agent-browser",t,new Error(i.error)))}catch(r){return B(new V(P(r),"FILL_FAILED","agent-browser",r instanceof Error?r:void 0))}}async getText(t){try{let e=$n(t),r=await this.executor.getText(e);if(!r.success)return B(new Dr("agent-browser",t,new Error(r.error)));let i=r.data;if(i&&typeof i=="object"){let n=i;if("text"in n)i=n.text;else if("data"in n&&typeof n.data=="object"){let s=n.data;"text"in s?i=s.text:"result"in s&&(i=s.result)}else"result"in n&&(i=n.result)}return re(String(i??""))}catch(e){return B(new V(P(e),"GET_TEXT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async isVisible(t){try{let e=$n(t),r=await this.executor.isVisible(e);return r.success?re(!!r.data):re(!1)}catch(e){return B(new V(P(e),"VISIBILITY_CHECK_FAILED","agent-browser",e instanceof Error?e:void 0))}}async screenshot(t){try{let e=await this.executor.screenshot(t?.path,t?.fullPage);if(!e.success)return B(new V(e.error??"Screenshot failed","SCREENSHOT_FAILED","agent-browser"));let r=await this.executor.eval("JSON.stringify({ width: window.innerWidth, height: window.innerHeight })"),i={width:1280,height:720};if(r.success&&r.data){let n=typeof r.data=="string"?D(r.data):r.data;i={width:n.width||1280,height:n.height||720}}return re({base64:t?.path?void 0:String(e.data??""),path:t?.path,format:"png",dimensions:i})}catch(e){return B(new V(P(e),"SCREENSHOT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async evaluate(t){try{let e=await this.executor.eval(t);if(!e.success)return B(new V(e.error??"Evaluation failed","EVAL_FAILED","agent-browser"));let r=e.data;if(r&&typeof r=="object"){let i=r;if("data"in i&&i.data&&typeof i.data=="object"){let n=i.data;"result"in n&&(r=n.result)}else"result"in i&&(r=i.result)}return re(r)}catch(e){return B(new V(P(e),"EVAL_FAILED","agent-browser",e instanceof Error?e:void 0))}}async getSnapshot(t){try{let e=await this.executor.snapshot({interactive:t?.interactive,depth:t?.depth});if(!e.success)return B(new V(e.error??"Snapshot failed","SNAPSHOT_FAILED","agent-browser"));let r;try{r=this.snapshotParser.parseJson(e.data)}catch{r=this.snapshotParser.parse(String(e.data))}let i=await this.executor.eval("window.location.href"),n=await this.executor.eval("document.title");return i.success&&(r.url=String(i.data)),n.success&&(r.title=String(n.data)),re(wC(r))}catch(e){return B(new V(P(e),"SNAPSHOT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async createSession(t){try{let e=await this.sessionManager.createSession({name:t});return re(Oa(e))}catch(e){return B(new V(P(e),"SESSION_CREATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async switchSession(t){try{return this.sessionManager.switchSession(t),this.currentSessionId=t,this.executor=new Kt({sessionName:t,timeout:this.config.timeout,headed:this.config.headed,debug:this.config.debug}),re(void 0)}catch(e){return B(new V(P(e),"SESSION_SWITCH_FAILED","agent-browser",e instanceof Error?e:void 0))}}async listSessions(){try{let t=this.sessionManager.listSessions();return re(t.map(Oa))}catch(t){return B(new V(P(t),"SESSION_LIST_FAILED","agent-browser",t instanceof Error?t:void 0))}}async mockRoute(t,e){try{let r={status:e.status??200,body:e.body,headers:e.headers},i=await this.executor.mockRoute(t,r);return i.success?re(void 0):B(new V(i.error??"Mock route failed","MOCK_ROUTE_FAILED","agent-browser"))}catch(r){return B(new V(P(r),"MOCK_ROUTE_FAILED","agent-browser",r instanceof Error?r:void 0))}}async abortRoute(t){try{let e=await this.executor.abortRoute(t);return e.success?re(void 0):B(new V(e.error??"Abort route failed","ABORT_ROUTE_FAILED","agent-browser"))}catch(e){return B(new V(P(e),"ABORT_ROUTE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async clearRoutes(){try{let t=await this.executor.clearRoutes();return t.success?re(void 0):B(new V(t.error??"Clear routes failed","CLEAR_ROUTES_FAILED","agent-browser"))}catch(t){return B(new V(P(t),"CLEAR_ROUTES_FAILED","agent-browser",t instanceof Error?t:void 0))}}async setDevice(t){try{let e=await this.executor.setDevice(t);return e.success?re(void 0):B(new V(e.error??"Set device failed","SET_DEVICE_FAILED","agent-browser"))}catch(e){return B(new V(P(e),"SET_DEVICE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async setViewport(t,e){try{let r=await this.executor.setViewport(t,e);return r.success?re(void 0):B(new V(r.error??"Set viewport failed","SET_VIEWPORT_FAILED","agent-browser"))}catch(r){return B(new V(P(r),"SET_VIEWPORT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async saveState(t){try{let e=await this.executor.saveState(t);return e.success?re(void 0):B(new V(e.error??"Save state failed","SAVE_STATE_FAILED","agent-browser"))}catch(e){return B(new V(P(e),"SAVE_STATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async loadState(t){try{let e=await this.executor.loadState(t);return e.success?re(void 0):B(new V(e.error??"Load state failed","LOAD_STATE_FAILED","agent-browser"))}catch(e){return B(new V(P(e),"LOAD_STATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async waitForElement(t,e){try{let r=$n(t),i=await this.executor.waitForElement(r,e);return i.success?re(void 0):B(new Qt("agent-browser",`waitForElement(${r})`,new Error(i.error)))}catch(r){return B(new V(P(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForText(t,e){try{let r=await this.executor.waitForText(t);return r.success?re(void 0):B(new Qt("agent-browser",`waitForText("${t}")`,new Error(r.error)))}catch(r){return B(new V(P(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForUrl(t,e){try{let r=await this.executor.waitForUrl(t);return r.success?re(void 0):B(new Qt("agent-browser",`waitForUrl("${t}")`,new Error(r.error)))}catch(r){return B(new V(P(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForNetworkIdle(t){try{let e=await this.executor.waitForNetworkIdle();return e.success?re(void 0):B(new Qt("agent-browser","waitForNetworkIdle",new Error(e.error)))}catch(e){return B(new V(P(e),"WAIT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async startTrace(){try{let t=await this.executor.startTrace();return t.success?re(void 0):B(new V(t.error??"Start trace failed","START_TRACE_FAILED","agent-browser"))}catch(t){return B(new V(P(t),"START_TRACE_FAILED","agent-browser",t instanceof Error?t:void 0))}}async stopTrace(t){try{let e=await this.executor.stopTrace(t);return e.success?re(e.data??t):B(new V(e.error??"Stop trace failed","STOP_TRACE_FAILED","agent-browser"))}catch(e){return B(new V(P(e),"STOP_TRACE_FAILED","agent-browser",e instanceof Error?e:void 0))}}};import{randomUUID as cg}from"crypto";var Na={persistentContext:!0,cloudflareWaitSeconds:0,resourceBlocking:"functional"};var CC=new Set(["google-analytics.com","googletagmanager.com","analytics.google.com","hotjar.com","fullstory.com","segment.io","segment.com","mixpanel.com","heap.io","heapanalytics.com","amplitude.com","mouseflow.com","crazyegg.com","optimizely.com","newrelic.com","nr-data.net","sentry.io","bugsnag.com","logrocket.com","clarity.ms","facebook.net","connect.facebook.net"]),SC=new Set(["doubleclick.net","googlesyndication.com","googleadservices.com","google-analytics.com","adservice.google.com","pagead2.googlesyndication.com","ads.twitter.com","ads-api.twitter.com","adsserver.com","adnxs.com","amazon-adsystem.com","criteo.com","moatads.com","outbrain.com","taboola.com","bidswitch.net","rubiconproject.com"]),RC={image:"image",font:"font",media:"media",stylesheet:"stylesheet",websocket:"websocket"},ng={functional:{enabled:!0,blockedCategories:["image","font","media","stylesheet","tracking","advertising"]},visual:{enabled:!1,blockedCategories:[]},performance:{enabled:!0,blockedCategories:["image","font","media","tracking","advertising"]}};function lu(c,t,e){if(!e.enabled)return!1;if(e.allowPatterns?.length){for(let i of e.allowPatterns)if(ag(c,i))return!1}if(e.blockPatterns?.length){for(let i of e.blockPatterns)if(ag(c,i))return!0}let r=RC[t];return!!(r&&e.blockedCategories.includes(r)||e.blockedCategories.includes("tracking")&&og(c,CC)||e.blockedCategories.includes("advertising")&&og(c,SC))}function On(c){if(typeof c=="object")return c;let t=ng[c];return t?{...t,blockedCategories:[...t.blockedCategories]}:ng.visual}var sg=new Map;function ag(c,t){let e=sg.get(t);if(!e){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");e=new RegExp(r,"i"),sg.set(t,e)}return e.test(c)}function og(c,t){try{let e=new URL(c).hostname;for(let r of t)if(e===r||e.endsWith(`.${r}`))return!0}catch{}return!1}var _a=null,lg=!1;function ug(){if(lg)return _a;lg=!0;try{_a=mm("patchright")}catch{_a=null}return _a}var Jt=class{tool="stealth";stealthConfig;page=null;context=null;browser=null;sessionId=null;constructor(t){this.stealthConfig={...Na,...t}}async isAvailable(){return ug()!==null}async launch(t){let e=ug();if(!e)return{success:!1,error:new ue("stealth","Patchright is not installed. Install with: npm install patchright")};try{let r={headless:t?.headless??!0};if(t?.viewport&&(r.viewport=t.viewport),t?.args&&(r.args=t.args),this.stealthConfig.userAgent&&(r.userAgent=this.stealthConfig.userAgent),this.stealthConfig.proxy&&(r.proxy=this.stealthConfig.proxy),this.stealthConfig.persistentContext){let i=this.stealthConfig.userDataDir||`/tmp/stealth-browser-${cg()}`;this.context=await e.chromium.launchPersistentContext(i,r);let n=this.context.pages();this.page=n.length>0?n[0]:await this.context.newPage()}else this.browser=await e.chromium.launch(r),this.page=await this.browser.newPage();return await this.applyResourceBlocking(),this.sessionId=cg(),{success:!0,value:{id:this.sessionId,tool:"stealth",status:"active",createdAt:new Date}}}catch(r){return{success:!1,error:new V(`Failed to launch stealth browser: ${r instanceof Error?r.message:String(r)}`,"LAUNCH_FAILED","stealth",r instanceof Error?r:void 0)}}}async quit(){try{return this.context&&(await this.context.close(),this.context=null),this.browser&&(await this.browser.close(),this.browser=null),this.page=null,this.sessionId=null,{success:!0,value:void 0}}catch(t){return{success:!1,error:new V("Failed to quit stealth browser","QUIT_FAILED","stealth",t instanceof Error?t:void 0)}}}async navigate(t){if(!this.page)return this.notLaunched();try{let e=Date.now(),i=(await this.page.goto(t,{waitUntil:"domcontentloaded"}))?.status()??void 0;this.stealthConfig.cloudflareWaitSeconds>0&&await this.waitForCloudflare();let n=await this.page.title();return{success:!0,value:{url:this.page.url(),title:n,success:!0,durationMs:Date.now()-e,statusCode:i??void 0}}}catch(e){return this.wrapError("navigate",e)}}async reload(){if(!this.page)return this.notLaunched();try{return await this.page.reload(),{success:!0,value:void 0}}catch(t){return this.wrapError("reload",t)}}async goBack(){if(!this.page)return this.notLaunched();try{return await this.page.goBack(),{success:!0,value:void 0}}catch(t){return this.wrapError("goBack",t)}}async goForward(){if(!this.page)return this.notLaunched();try{return await this.page.goForward(),{success:!0,value:void 0}}catch(t){return this.wrapError("goForward",t)}}async click(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return await this.page.click(e),{success:!0,value:void 0}}catch(e){return this.wrapError("click",e)}}async fill(t,e){if(!this.page)return this.notLaunched();try{let r=this.resolveSelector(t);return await this.page.fill(r,e),{success:!0,value:void 0}}catch(r){return this.wrapError("fill",r)}}async getText(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return{success:!0,value:await this.page.textContent(e)??""}}catch(e){return this.wrapError("getText",e)}}async isVisible(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return{success:!0,value:await this.page.isVisible(e)}}catch(e){return this.wrapError("isVisible",e)}}async screenshot(t){if(!this.page)return this.notLaunched();try{return{success:!0,value:{base64:(await this.page.screenshot({path:t?.path,fullPage:t?.fullPage,type:"png"})).toString("base64"),path:t?.path,format:"png",dimensions:{width:0,height:0}}}}catch(e){return this.wrapError("screenshot",e)}}async evaluate(t){if(!this.page)return this.notLaunched();try{return{success:!0,value:await this.page.evaluate(t)}}catch(e){return this.wrapError("evaluate",e)}}async dispose(){await this.quit()}resolveSelector(t){if(typeof t=="string")return t;switch(t.type){case"css":return t.value;case"xpath":return`xpath=${t.value}`;case"text":return`text=${t.value}`;case"ref":return t.value;default:return t.value}}async applyResourceBlocking(){if(!this.page||!this.stealthConfig.resourceBlocking)return;let t=typeof this.stealthConfig.resourceBlocking=="string"?On(this.stealthConfig.resourceBlocking):this.stealthConfig.resourceBlocking;t.enabled&&await this.page.route("**/*",e=>{let r=e.request().url(),i=e.request().resourceType();lu(r,i,t)?e.abort().catch(()=>{}):e.continue().catch(()=>{})})}async waitForCloudflare(){if(!this.page||this.stealthConfig.cloudflareWaitSeconds<=0)return;let t=this.stealthConfig.cloudflareWaitSeconds*1e3,e=Date.now();for(;Date.now()-e<t;){try{let r=await this.page.title();if(!r.includes("Just a moment")&&!r.includes("Checking your browser"))return}catch{}await new Promise(r=>setTimeout(r,500))}}notLaunched(){return{success:!1,error:new V("Stealth browser not launched. Call launch() first.","NOT_LAUNCHED","stealth")}}wrapError(t,e){return{success:!1,error:new V(`Stealth ${t} failed: ${e instanceof Error?e.message:String(e)}`,"OPERATION_FAILED","stealth",e instanceof Error?e:void 0)}}};async function uu(){return!1}async function mu(){try{return await new ui().isAvailable()}catch{return!1}}var TC=["e2e-testing","api-mocking","responsive-testing","auth-testing"],EC=["stealth-testing"];function AC(c){return TC.includes(c)}var Va=class{tool="vibium";async isAvailable(){return!1}async launch(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async quit(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async navigate(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async reload(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async goBack(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async goForward(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async click(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async fill(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async getText(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async isVisible(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async screenshot(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async evaluate(){return{success:!1,error:new ue("vibium","Vibium client not yet implemented")}}async dispose(){}};async function pu(c={}){let{preference:t="auto",useCase:e}=c;if(e&&EC.includes(e)&&await du())return new Jt;if(e&&AC(e)||t==="agent-browser")return Nn();if(t==="stealth"){if(await du())return new Jt;throw new ue("stealth","Patchright is not installed")}if(t==="vibium"){if(await uu())return new Va;throw new ue("vibium","Vibium is not available")}return await uu()?new Va:(await mu(),Nn())}async function Nn(){return new ui}async function za(c){return pu({useCase:c})}async function du(){try{return await new Jt().isAvailable()}catch{return!1}}import{exec as PC}from"child_process";import{promisify as kC}from"util";k();X();Xc();Yr();var q1=kC(PC);k();var dg={enabled:!0,similarityThreshold:.6,maxFingerprintsPerPage:200,namespace:"aqe/adaptive-locators",fallbackChain:["text","aria","fingerprint"]};function DC(c){return`
2311
2311
  (() => {
2312
2312
  const el = document.querySelector(${JSON.stringify(c)});
2313
2313
  if (!el) return null;
@@ -2613,7 +2613,7 @@ describe('${e} Integration', () => {
2613
2613
  .rejects.toThrow('Unrecoverable');
2614
2614
  });
2615
2615
  });
2616
- });`}};k();var GC=[{name:"uncovered-lines",weight:.25},{name:"complexity",weight:.2},{name:"defect-history",weight:.2},{name:"change-frequency",weight:.15},{name:"code-age",weight:.1},{name:"dependency-count",weight:.1}],mi=class c{constructor(t){this.memory=t}memory;static HISTORY_KEY_PREFIX="risk-history";static MAX_TREND_POINTS=30;async calculateRisk(t){try{let{file:e,uncoveredLines:r,factors:i=GC}=t,n=this.normalizeFactorWeights(i),s=await this.calculateFactorScores(e,r,n),a=s.reduce((u,d)=>u+d.score*d.contribution,0),o=this.riskScoreToSeverity(a),l=this.generateRiskRecommendations(e,a,o,s);return await this.storeRiskSnapshot(e,a,s),f({file:e,overallRisk:a,riskLevel:o,factors:s,recommendations:l})}catch(e){return g(y(e))}}async factorInHistory(t,e){try{let r=await this.getDefectHistory(t),i=Math.min(1,r.count/10)*.3,n=await this.getChangeFrequency(t),s=Math.min(1,n/20)*.2,a=await this.getRiskTrend(t),o=0;if(a.success){let u=a.value;u.trend==="increasing"?o=.15:u.trend==="decreasing"&&(o=-.1)}let l=e+i+s+o;return Math.min(1,Math.max(0,l))}catch{return e}}async getRiskTrend(t){try{let e=`${c.HISTORY_KEY_PREFIX}:${t}`,r=await this.memory.get(e);if(!r||r.length===0)return f({file:t,dataPoints:[],trend:"stable",forecast:.5});let i=r.slice(-c.MAX_TREND_POINTS).map(a=>({date:new Date(a.timestamp),riskScore:a.riskScore,factors:a.topFactors})),n=this.analyzeTrend(i),s=this.forecastRisk(i);return f({file:t,dataPoints:i,trend:n,forecast:s})}catch(e){return g(y(e))}}normalizeFactorWeights(t){let e=t.reduce((r,i)=>r+i.weight,0);return e===0?t:t.map(r=>({...r,weight:r.weight/e}))}async calculateFactorScores(t,e,r){let i=[];for(let n of r){let s=await this.calculateSingleFactorScore(n.name,t,e);i.push({name:n.name,score:s,contribution:n.weight})}return i}async calculateSingleFactorScore(t,e,r){switch(t){case"uncovered-lines":return this.calculateUncoveredLinesScore(r);case"complexity":return await this.calculateComplexityScore(e);case"defect-history":return await this.calculateDefectHistoryScore(e);case"change-frequency":return await this.calculateChangeFrequencyScore(e);case"code-age":return await this.calculateCodeAgeScore(e);case"dependency-count":return await this.calculateDependencyScore(e);default:return .5}}calculateUncoveredLinesScore(t){let e=t.length;return e===0?0:e<=5?.2:e<=15?.4:e<=30?.6:e<=50?.8:1}async calculateComplexityScore(t){try{let e=await this.memory.get(`complexity:${t}`);if(!e)return .5;let r=e.cyclomatic;return r<=5?.2:r<=10?.4:r<=20?.6:r<=30?.8:1}catch{return .5}}async calculateDefectHistoryScore(t){let r=(await this.getDefectHistory(t)).count;return r===0?.1:r<=2?.3:r<=5?.5:r<=10?.7:.9}async calculateChangeFrequencyScore(t){let e=await this.getChangeFrequency(t);return e<=2?.2:e<=5?.4:e<=10?.6:e<=20?.8:1}async calculateCodeAgeScore(t){try{let e=await this.memory.get(`file-metadata:${t}`);if(!e)return .5;let r=(Date.now()-new Date(e.createdAt).getTime())/(1e3*60*60*24);return r<=7?.8:r<=30?.5:r<=90?.3:r<=365?.4:.6}catch{return .5}}async calculateDependencyScore(t){try{let e=await this.memory.get(`dependencies:${t}`);if(!e)return .5;let r=e.count;return r<=3?.2:r<=7?.4:r<=15?.6:r<=25?.8:1}catch{return .5}}async getDefectHistory(t){try{return{count:(await this.memory.get(`defect-history:${t}`))?.defectCount??0}}catch{return{count:0}}}async getChangeFrequency(t){try{return(await this.memory.get(`change-frequency:${t}`))?.changesLast90Days??5}catch{return 5}}riskScoreToSeverity(t){return t>=.8?"critical":t>=.6?"high":t>=.3?"medium":t>=.1?"low":"info"}generateRiskRecommendations(t,e,r,i){let n=[],a=[...i].sort((o,l)=>l.score*l.contribution-o.score*o.contribution).slice(0,3);r==="critical"?n.push(`CRITICAL: ${t} has a risk score of ${(e*100).toFixed(1)}%. Immediate action required.`):r==="high"&&n.push(`HIGH RISK: ${t} should be prioritized for test coverage improvement.`);for(let o of a)o.score>=.6&&n.push(this.getFactorRecommendation(o.name,o.score));return e>=.5&&n.push("Consider breaking this file into smaller, more testable modules."),i.find(o=>o.name==="defect-history"&&o.score>=.5)&&n.push("This file has a history of defects. Add regression tests for known issues."),n}getFactorRecommendation(t,e){let r=e>=.8?"Critical":"High";switch(t){case"uncovered-lines":return`${r}: Many uncovered lines. Focus on adding unit tests for core logic.`;case"complexity":return`${r}: High complexity detected. Consider refactoring before adding tests.`;case"defect-history":return`${r}: Past defects in this area. Add regression tests to prevent recurrence.`;case"change-frequency":return`${r}: Frequently changed code. Ensure comprehensive test coverage.`;case"code-age":return`${r}: Code age indicates risk. Review and update tests accordingly.`;case"dependency-count":return`${r}: Many dependencies. Add integration tests to verify interactions.`;default:return`${r}: Factor "${t}" indicates elevated risk.`}}async storeRiskSnapshot(t,e,r){try{let i=`${c.HISTORY_KEY_PREFIX}:${t}`,n=await this.memory.get(i)??[],s={timestamp:Date.now(),riskScore:e,topFactors:r.filter(o=>o.score>=.5).map(o=>o.name)},a=[...n,s].slice(-c.MAX_TREND_POINTS);await this.memory.set(i,a,{persist:!0})}catch{}}analyzeTrend(t){if(t.length<3)return"stable";let e=t.length,r=0,i=0,n=0,s=0;for(let o=0;o<e;o++){let l=o,u=t[o].riskScore;r+=l,i+=u,n+=l*u,s+=l*l}let a=(e*n-r*i)/(e*s-r*r);return a>.01?"increasing":a<-.01?"decreasing":"stable"}forecastRisk(t){if(t.length===0)return .5;if(t.length===1)return t[0].riskScore;let e=.3,r=t[0].riskScore;for(let n=1;n<t.length;n++)r=e*t[n].riskScore+(1-e)*r;let i=this.analyzeTrend(t);return i==="increasing"?r=Math.min(1,r+.05):i==="decreasing"&&(r=Math.max(0,r-.05)),r}};var Au={dimensions:384,includePathFeatures:!0,includeTemporalFeatures:!0,normalization:"l2"},_n=class{config;constructor(t={}){this.config={...Au,...t}}embedFileCoverage(t){let e=new Array(this.config.dimensions).fill(0),r=0;return r=this.encodeCoverageMetrics(e,t,r),r=this.encodeGapCharacteristics(e,t,r),r=this.encodeRiskFactors(e,t,r),r=this.encodeFileCharacteristics(e,t,r),this.encodeDerivedFeatures(e,t,r),{vector:this.normalize(e),metadata:this.createMetadata(t),confidence:this.calculateConfidence(t)}}embedCoverageGap(t){let e=new Array(this.config.dimensions).fill(0);e[0]=t.riskScore,e[1]=Math.min(1,t.lines.length/100),e[2]=Math.min(1,t.branches.length/20),e[3]=this.severityToNumber(t.severity)/4;let r=this.extractPathFeatures(t.file);if(e[4]=r.depth/10,e[5]=r.hashNormalized,t.lines.length>1){let n=t.lines[t.lines.length-1]-t.lines[0];e[6]=Math.min(1,n/500),e[7]=t.lines.length/(n+1)}for(let n=8;n<this.config.dimensions;n++){let s=t.riskScore*n+t.lines.length*.01;e[n]=Math.sin(s)*.5+.5}return{vector:this.normalize(e),metadata:{filePath:t.file,lineCoverage:0,branchCoverage:0,functionCoverage:0,statementCoverage:0,uncoveredLineCount:t.lines.length,uncoveredBranchCount:t.branches.length,riskScore:t.riskScore,lastUpdated:Date.now(),totalLines:t.lines.length>0?t.lines[t.lines.length-1]:0},confidence:.8}}embedQuery(t){let e=new Array(this.config.dimensions).fill(0);if(t.minLineCoverage!==void 0&&(e[0]=t.minLineCoverage/100),t.maxLineCoverage!==void 0&&(e[1]=t.maxLineCoverage/100),t.minBranchCoverage!==void 0&&(e[2]=t.minBranchCoverage/100),t.maxBranchCoverage!==void 0&&(e[3]=t.maxBranchCoverage/100),t.minRiskScore!==void 0&&(e[4]=t.minRiskScore),t.maxRiskScore!==void 0&&(e[5]=t.maxRiskScore),t.filePattern){let r=this.extractPathFeatures(t.filePattern);e[6]=r.depth/10,e[7]=r.hashNormalized}t.maxUncoveredLines!==void 0&&(e[8]=Math.min(1,t.maxUncoveredLines/100));for(let r=9;r<this.config.dimensions;r++)e[r]===0&&(e[r]=.5);return{vector:this.normalize(e),metadata:{filePath:t.filePattern||"",lineCoverage:t.minLineCoverage||0,branchCoverage:t.minBranchCoverage||0,functionCoverage:0,statementCoverage:0,uncoveredLineCount:t.maxUncoveredLines||0,uncoveredBranchCount:0,riskScore:t.minRiskScore||0,lastUpdated:Date.now(),totalLines:0},confidence:.7}}batchEmbed(t){return t.map(e=>this.embedFileCoverage(e))}encodeCoverageMetrics(t,e,r){return t[r++]=e.lines.total>0?e.lines.covered/e.lines.total:0,t[r++]=Math.min(1,e.lines.total/1e3),t[r++]=Math.min(1,e.lines.covered/500),t[r++]=e.lines.total>0?e.uncoveredLines.length/e.lines.total:0,t[r++]=e.branches.total>0?e.branches.covered/e.branches.total:1,t[r++]=Math.min(1,e.branches.total/200),t[r++]=Math.min(1,e.branches.covered/100),t[r++]=e.branches.total>0?e.uncoveredBranches.length/e.branches.total:0,t[r++]=e.functions.total>0?e.functions.covered/e.functions.total:1,t[r++]=Math.min(1,e.functions.total/50),t[r++]=Math.min(1,e.functions.covered/25),t[r++]=e.functions.total>0?1-e.functions.covered/e.functions.total:0,t[r++]=e.statements.total>0?e.statements.covered/e.statements.total:1,t[r++]=Math.min(1,e.statements.total/1e3),t[r++]=Math.min(1,e.statements.covered/500),t[r++]=e.statements.total>0?1-e.statements.covered/e.statements.total:0,r}encodeGapCharacteristics(t,e,r){let i=e.uncoveredLines,n=e.uncoveredBranches;if(t[r++]=Math.min(1,i.length/100),t[r++]=Math.min(1,n.length/50),t[r++]=Math.min(1,(i.length+n.length)/150),t[r++]=i.length>0?1:0,i.length>1){let s=[...i].sort((u,d)=>u-d),a=s[s.length-1]-s[0],o=i.length/(a+1);t[r++]=Math.min(1,a/500),t[r++]=Math.min(1,o);let l=this.countContiguousRegions(s);t[r++]=Math.min(1,l/10),t[r++]=l>0?i.length/l:0}else t[r++]=0,t[r++]=i.length>0?1:0,t[r++]=i.length>0?.1:0,t[r++]=i.length;if(i.length>0&&e.lines.total>0){let s=Math.min(...i),a=Math.max(...i);t[r++]=s/e.lines.total,t[r++]=a/e.lines.total,t[r++]=(a-s)/e.lines.total,t[r++]=i.filter(o=>o<=e.lines.total*.2).length/i.length}else r+=4;return r+=4,r}encodeRiskFactors(t,e,r){let i=this.calculateOverallCoverage(e);t[r++]=1-i,t[r++]=e.branches.total>0?1-e.branches.covered/e.branches.total:0,t[r++]=e.functions.total>0?1-e.functions.covered/e.functions.total:0,t[r++]=Math.min(1,e.uncoveredLines.length/50),t[r++]=Math.min(1,e.lines.total/500),t[r++]=Math.min(1,e.functions.total/30),t[r++]=Math.min(1,e.branches.total/100),t[r++]=e.lines.total>300?.8:e.lines.total/375;let n=this.calculateLargeGapRatio(e.uncoveredLines);return t[r++]=n,t[r++]=e.uncoveredBranches.length>10?1:e.uncoveredBranches.length/10,t[r++]=e.uncoveredLines.length>30?1:e.uncoveredLines.length/30,t[r++]=this.calculateGapConcentration(e),r+=4,r}encodeFileCharacteristics(t,e,r){let i=this.extractPathFeatures(e.path);return t[r++]=i.depth/10,t[r++]=i.hashNormalized,t[r++]=i.isTest?.1:.9,t[r++]=i.isConfig?.2:.8,t[r++]=i.extension==="ts"?1:0,t[r++]=i.extension==="js"?1:0,t[r++]=i.extension==="tsx"||i.extension==="jsx"?1:0,t[r++]=i.isIndex?.5:0,t[r++]=i.inSrc?1:0,t[r++]=i.inLib?.8:0,t[r++]=i.inDomains?1:0,t[r++]=i.inServices?.9:0,r+=4,r}encodeDerivedFeatures(t,e,r){let i=[e.lines.covered/(e.lines.total||1),e.branches.covered/(e.branches.total||1),e.functions.covered/(e.functions.total||1),e.statements.covered/(e.statements.total||1),e.uncoveredLines.length/(e.lines.total||1),e.uncoveredBranches.length/(e.branches.total||1)];for(let n=0;n<6;n++)for(let s=n+1;s<6&&r<this.config.dimensions;s++)t[r++]=(i[n]+i[s])/2,r<this.config.dimensions&&(t[r++]=Math.abs(i[n]-i[s]));for(;r<this.config.dimensions-6;){let n=(r-64)%i.length;t[r++]=i[n]*i[n],r<this.config.dimensions&&(t[r++]=Math.sqrt(i[n]))}for(;r<this.config.dimensions;){let n=(r-64)*.1,s=i[(r-64)%i.length];t[r++]=Math.sin(s*Math.PI+n)*.5+.5}}normalize(t){switch(this.config.normalization){case"l2":return this.l2Normalize(t);case"minmax":return this.minMaxNormalize(t);default:return t}}l2Normalize(t){let e=Math.sqrt(t.reduce((r,i)=>r+i*i,0));return e===0?t:t.map(r=>r/e)}minMaxNormalize(t){let e=Math.min(...t),i=Math.max(...t)-e;return i===0?t.map(()=>.5):t.map(n=>(n-e)/i)}createMetadata(t){return{filePath:t.path,lineCoverage:t.lines.total>0?t.lines.covered/t.lines.total*100:0,branchCoverage:t.branches.total>0?t.branches.covered/t.branches.total*100:0,functionCoverage:t.functions.total>0?t.functions.covered/t.functions.total*100:0,statementCoverage:t.statements.total>0?t.statements.covered/t.statements.total*100:0,uncoveredLineCount:t.uncoveredLines.length,uncoveredBranchCount:t.uncoveredBranches.length,riskScore:this.calculateRiskScore(t),lastUpdated:Date.now(),totalLines:t.lines.total}}calculateConfidence(t){let e=t.lines.total>0,r=t.branches.total>0,i=t.functions.total>0,n=t.statements.total>0,s=.5;return e&&(s+=.2),r&&(s+=.1),i&&(s+=.1),n&&(s+=.1),Math.min(1,s)}calculateOverallCoverage(t){let e=t.lines.total>0?t.lines.covered/t.lines.total:1,r=t.branches.total>0?t.branches.covered/t.branches.total:1,i=t.functions.total>0?t.functions.covered/t.functions.total:1,n=t.statements.total>0?t.statements.covered/t.statements.total:1;return(e+r+i+n)/4}calculateRiskScore(t){let e=t.lines.total>0?1-t.lines.covered/t.lines.total:0,r=t.branches.total>0?1-t.branches.covered/t.branches.total:0,i=t.functions.total>0?1-t.functions.covered/t.functions.total:0;return Math.min(1,e*.3+r*.4+i*.3)}countContiguousRegions(t){if(t.length===0)return 0;let e=1;for(let r=1;r<t.length;r++)t[r]-t[r-1]>3&&e++;return e}calculateLargeGapRatio(t){if(t.length===0)return 0;let e=[...t].sort((s,a)=>s-a),r=0,i=1;for(let s=1;s<e.length;s++)e[s]-e[s-1]<=3?i++:(i>10&&r++,i=1);i>10&&r++;let n=this.countContiguousRegions(e);return n>0?r/n:0}calculateGapConcentration(t){if(t.uncoveredLines.length===0||t.lines.total===0)return 0;let e=this.countContiguousRegions([...t.uncoveredLines].sort((i,n)=>i-n)),r=Math.ceil(t.uncoveredLines.length/5);return e>0?Math.min(1,r/e):0}extractPathFeatures(t){let e=t.split("/").filter(Boolean),r=t.split(".").pop()||"",i=e[e.length-1]||"";return{depth:e.length,extension:r,hashNormalized:this.hashString(t)/1e6,isTest:/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(t)||e.includes("tests")||e.includes("__tests__"),isConfig:/\.(config|rc)\.(ts|js|json|yaml|yml)$/.test(t),isIndex:i.startsWith("index."),inSrc:e.includes("src"),inLib:e.includes("lib"),inDomains:e.includes("domains"),inServices:e.includes("services")}}hashString(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i|0}return Math.abs(e)}severityToNumber(t){switch(t){case"critical":return 4;case"high":return 3;case"medium":return 2;case"low":return 1;default:return 0}}};function Vn(c){return new _n(c)}_();k();var Iz=x.create("coverage-analysis/sublinear-analyzer");bs();k();var zn=["missing-error-handler","absent-boundary-validation","unprotected-state-transition","missing-integration-contract","absent-edge-case","missing-security-check"],jC={dimensions:384,minConfidence:.3,maxGaps:50,riskWeight:.6,distanceWeight:.4,namespace:"ghost-surface",idealSurfaceDecay:.95},Bn=class c{config;hnswIndex;embedder;idealSurfacePatterns=[];cachedIdealSurface=null;cachedPhantomRatio=1;initialized=!1;constructor(t,e={}){this.config={...jC,...e},this.hnswIndex=t.hnswIndex,this.embedder=t.embedder}async initialize(){try{return this.idealSurfacePatterns=this.buildBaselinePatterns(),this.cachedIdealSurface=this.aggregateIdealSurface(),this.initialized=!0,f(void 0)}catch(t){return g(y(t))}}async computePhantomSurface(t,e){try{this.ensureInitialized();let r=this.buildIdealSurface(e),i=new Map,n=[];for(let o of t.files){let l=this.embedder.embedFileCoverage(o).vector;n.push(l),i.set(o.path,this.computeGhostVector(l,r)),await this.hnswIndex.insert(`${this.config.namespace}:${o.path}`,i.get(o.path),{filePath:o.path,lineCoverage:this.ratio(o.lines.covered,o.lines.total)*100,branchCoverage:this.ratio(o.branches.covered,o.branches.total)*100,functionCoverage:this.ratio(o.functions.covered,o.functions.total)*100,statementCoverage:this.ratio(o.statements.covered,o.statements.total)*100,uncoveredLineCount:o.uncoveredLines.length,uncoveredBranchCount:o.uncoveredBranches.length,riskScore:this.fileRiskScore(o),lastUpdated:Date.now(),totalLines:o.lines.total})}let s=this.aggregateSurface(n),a=this.phantomRatioFromVectors(r,s);return this.cachedIdealSurface=r,this.cachedPhantomRatio=a,f({ghostVectors:i,idealSurface:r,actualSurface:s,phantomRatio:a,computedAt:Date.now(),filesAnalyzed:t.files.length})}catch(r){return g(y(r))}}async detectPhantomGaps(t,e){try{this.ensureInitialized();let r=e??this.config.minConfidence,i=[];for(let[n,s]of t.ghostVectors){if(vs(s)<.01)continue;let a=await this.hnswIndex.search(s,5),o=this.getApplicableCategories(n);for(let l of this.classifyGhost(s,a)){if(l.confidence<r||!o.has(l.category))continue;let u=this.gapRiskScore(s,l.category),d=Math.min(1,vs(s));i.push({id:this.gapId(n,l.category),file:n,category:l.category,ghostDistance:d,riskScore:u,severity:this.toSeverity(d,u),confidence:l.confidence,description:this.gapDescription(n,l.category,d),suggestedLines:l.suggestedLines})}}return i.sort((n,s)=>s.ghostDistance*s.riskScore-n.ghostDistance*n.riskScore),f(i.slice(0,this.config.maxGaps))}catch(r){return g(y(r))}}rankPhantomGaps(t){let{riskWeight:e,distanceWeight:r}=this.config;return[...t].sort((i,n)=>e*n.riskScore+r*n.ghostDistance-(e*i.riskScore+r*i.ghostDistance))}async updateIdealSurface(t){try{this.ensureInitialized();for(let e of this.idealSurfacePatterns)e.weight*=this.config.idealSurfaceDecay;for(let e of t){if(e.vector.length!==this.config.dimensions)continue;let r=this.idealSurfacePatterns.findIndex(i=>i.id===e.id);r>=0?this.idealSurfacePatterns[r]=e:this.idealSurfacePatterns.push(e)}return this.idealSurfacePatterns=this.idealSurfacePatterns.filter(e=>e.weight>.01),this.cachedIdealSurface=this.aggregateIdealSurface(),f(this.idealSurfacePatterns.length)}catch(e){return g(y(e))}}getPhantomRatio(){return this.cachedPhantomRatio}computeGhostVector(t,e){let r=Math.min(t.length,e.length),i=new Array(r);for(let n=0;n<r;n++)i[n]=Math.max(0,e[n]-t[n]);return pr(i)}buildBaselinePatterns(){let t=this.config.dimensions,e=Math.floor(t/zn.length);return zn.map((r,i)=>{let n=new Array(t).fill(0),s=i*e,a=Math.min(s+e,t);for(let o=s;o<a;o++)n[o]=Math.sin((o-s)/e*Math.PI)*.8+.2;return n[0]=.9,n[1]=.85,n[2]=.9,n[3]=.85,{id:`baseline-${r}`,category:r,vector:pr(n),weight:1,source:"baseline"}})}buildIdealSurface(t){let e=this.aggregateIdealSurface();if(t.riskAreas?.length)for(let r=32;r<48&&r<e.length;r++)e[r]*=1.2;if(t.defectHistory?.length){let r=Math.min(1.5,1+t.defectHistory.length*.05);for(let i=0;i<16&&i<e.length;i++)e[i]*=r}return pr(e)}aggregateIdealSurface(){let t=this.config.dimensions;if(this.idealSurfacePatterns.length===0)return pr(new Array(t).fill(1));let e=new Array(t).fill(0),r=0;for(let i of this.idealSurfacePatterns){for(let n=0;n<t;n++)e[n]+=i.vector[n]*i.weight;r+=i.weight}if(r>0)for(let i=0;i<t;i++)e[i]/=r;return pr(e)}aggregateSurface(t){let e=this.config.dimensions;if(t.length===0)return new Array(e).fill(0);let r=new Array(e).fill(0);for(let i of t)for(let n=0;n<e&&n<i.length;n++)r[n]+=i[n];for(let i=0;i<e;i++)r[i]/=t.length;return pr(r)}classifyGhost(t,e){let r=this.config.dimensions,i=Math.floor(r/zn.length),n=[],s=0;for(let a of e)a.score>.7&&(s+=a.score*.1);for(let a=0;a<zn.length;a++){let o=a*i,l=Math.min(o+i,r),u=0;for(let m=o;m<l&&m<t.length;m++)u+=t[m]**2;u=Math.sqrt(u/(l-o));let d=Math.min(1,u+s);d>.05&&n.push({category:zn[a],confidence:d,suggestedLines:this.suggestLines(a,t)})}return n.sort((a,o)=>o.confidence-a.confidence)}suggestLines(t,e){let r=e[0]||0,i=e[2]||0;if(r<.1&&i<.1)return[];let n=t*20+1,s=Math.ceil(r*10),a=[];for(let o=0;o<s&&a.length<10;o++)a.push(n+o*5);return a}getApplicableCategories(t){let e=t.toLowerCase(),r=e.split("/").pop()||e,i=new Set(["missing-error-handler","absent-edge-case"]);return/\b(math|calc|util|helper|format|parse|convert|transform)\b/.test(r)?(i.add("absent-boundary-validation"),i):(i.add("absent-boundary-validation"),/\b(auth|security|token|credential|password|session|permission|rbac|acl|encrypt|crypto)\b/.test(e)&&i.add("missing-security-check"),/\b(service|controller|handler|router|middleware|api|endpoint|gateway|adapter)\b/.test(e)&&(i.add("missing-integration-contract"),i.add("unprotected-state-transition")),/\b(state|store|reducer|saga|machine|workflow|queue|scheduler)\b/.test(e)&&i.add("unprotected-state-transition"),i)}static CATEGORY_RISK={"missing-security-check":1.5,"missing-error-handler":1.3,"unprotected-state-transition":1.2,"missing-integration-contract":1.1,"absent-boundary-validation":1,"absent-edge-case":.8};gapRiskScore(t,e){return Math.min(1,vs(t)*(c.CATEGORY_RISK[e]??1))}fileRiskScore(t){return Math.min(1,(1-this.ratio(t.lines.covered,t.lines.total))*.3+(1-this.ratio(t.branches.covered,t.branches.total))*.4+(1-this.ratio(t.functions.covered,t.functions.total))*.3)}phantomRatioFromVectors(t,e){return!t.length||!e.length?1:Math.max(0,Math.min(1,1-Mt(t,e)))}toSeverity(t,e){let r=(t+e)/2;return r>=.8?"critical":r>=.6?"high":r>=.3?"medium":"low"}ensureInitialized(){if(!this.initialized)throw new Error("GhostCoverageAnalyzerService not initialized. Call initialize() first.")}ratio(t,e){return e>0?t/e:0}gapId(t,e){let r=`${t}:${e}`.split("").reduce((i,n)=>(i<<5)-i+n.charCodeAt(0)|0,0);return`phantom-${Math.abs(r).toString(16)}`}gapDescription(t,e,r){let i=t.split("/").pop()||t,n=r>.7?"significant":r>.4?"moderate":"minor";return{"missing-error-handler":`${i}: ${n} missing error handler tests. Cover error paths and failure recovery.`,"absent-boundary-validation":`${i}: ${n} missing boundary validation tests. Cover input bounds and null checks.`,"unprotected-state-transition":`${i}: ${n} missing state transition tests. Cover state changes and race conditions.`,"missing-integration-contract":`${i}: ${n} missing integration contract tests. Cover external API boundaries.`,"absent-edge-case":`${i}: ${n} missing edge case tests. Cover empty inputs, max values, and timeouts.`,"missing-security-check":`${i}: ${n} missing security check tests. Cover auth bypass and injection attacks.`}[e]}};ge();var Q=class{forward(t){return Math.max(0,t)}backward(t){return t>0?1:0}};var K=class{forward(t){return t}backward(t){return 1}},Ie=class c{static forward(t){let e=Math.max(...t),r=t.map(n=>Math.exp(n-e)),i=r.reduce((n,s)=>n+s,0);return new Float32Array(r.map(n=>n/i))}static backward(t,e){let r=c.forward(t),i=new Float32Array(t.length);for(let n=0;n<t.length;n++)i[n]=r[n]-e[n];return i}},Fe=class{forward(t,e){let r=e instanceof Float32Array?e:new Float32Array(e),i=0;for(let n=0;n<t.length;n++){let s=t[n]-r[n];i+=s*s}return i/t.length}backward(t,e){let r=e instanceof Float32Array?e:new Float32Array(e),i=new Float32Array(t.length),n=t.length;for(let s=0;s<n;s++)i[s]=2*(t[s]-r[s])/n;return i}};var Ka=class{weights;biases;weightGradients;biasGradients;activation;inputSize;outputSize;lastInput=null;lastPreActivation=null;lastOutput=null;constructor(t){this.inputSize=t.inputSize,this.outputSize=t.outputSize,this.activation=t.activation;let e=Math.sqrt(2/(this.inputSize+this.outputSize));this.weights=new Float32Array(this.inputSize*this.outputSize),this.biases=new Float32Array(this.outputSize),this.weightGradients=new Float32Array(this.inputSize*this.outputSize),this.biasGradients=new Float32Array(this.outputSize);for(let r=0;r<this.weights.length;r++)this.weights[r]=(z()*2-1)*e;for(let r=0;r<this.biases.length;r++)this.biases[r]=0}forward(t){this.lastInput=t;let e=new Float32Array(this.outputSize),r=new Float32Array(this.outputSize);for(let i=0;i<this.outputSize;i++){let n=this.biases[i];for(let s=0;s<this.inputSize;s++)n+=t[s]*this.weights[i*this.inputSize+s];r[i]=n,e[i]=this.activation.forward(n)}return this.lastPreActivation=r,this.lastOutput=e,e}backward(t){if(!this.lastInput||!this.lastPreActivation)throw new Error("Must call forward before backward");let e=new Float32Array(this.outputSize);for(let i=0;i<this.outputSize;i++)e[i]=this.activation.backward(this.lastPreActivation[i])*t[i];for(let i=0;i<this.outputSize;i++){for(let n=0;n<this.inputSize;n++)this.weightGradients[i*this.inputSize+n]+=e[i]*this.lastInput[n];this.biasGradients[i]+=e[i]}let r=new Float32Array(this.inputSize);for(let i=0;i<this.inputSize;i++)for(let n=0;n<this.outputSize;n++)r[i]+=e[n]*this.weights[n*this.inputSize+i];return r}update(t){for(let e=0;e<this.weights.length;e++)this.weights[e]-=t*this.weightGradients[e],this.weightGradients[e]=0;for(let e=0;e<this.biases.length;e++)this.biases[e]-=t*this.biasGradients[e],this.biasGradients[e]=0}getParameters(){return{weights:Array.from(this.weights),biases:Array.from(this.biases)}}setParameters(t){this.weights=new Float32Array(t.weights),this.biases=new Float32Array(t.biases),this.weightGradients=new Float32Array(this.weights.length),this.biasGradients=new Float32Array(this.biases.length)}},J=class c{layers=[];learningRate;constructor(t){this.learningRate=t.learningRate||.001;for(let e=0;e<t.layerSizes.length-1;e++){let r=new Ka({inputSize:t.layerSizes[e],outputSize:t.layerSizes[e+1],activation:t.activations[e]||new Q});this.layers.push(r)}}forward(t){let e=t instanceof Float32Array?t:new Float32Array(t);for(let r of this.layers)e=r.forward(e);return e}backward(t){let e=t;for(let r=this.layers.length-1;r>=0;r--)e=this.layers[r].backward(e)}train(t,e,r){let i=this.forward(t),n=e instanceof Float32Array?e:new Float32Array(e),s=r.forward(i,n),a=r.backward(i,n);this.backward(a);for(let o of this.layers)o.update(this.learningRate);return s}trainBatch(t,e,r){let i=0;for(let n of this.layers)n.weightGradients.fill(0),n.biasGradients.fill(0);for(let n=0;n<t.length;n++){let s=t[n]instanceof Float32Array?t[n]:new Float32Array(t[n]),a=e[n]instanceof Float32Array?e[n]:new Float32Array(e[n]),o=this.forward(s),l=r.forward(o,a);i+=l;let u=r.backward(o,a);this.backward(u)}for(let n of this.layers){for(let s=0;s<n.weightGradients.length;s++)n.weightGradients[s]/=t.length;for(let s=0;s<n.biasGradients.length;s++)n.biasGradients[s]/=t.length;n.update(this.learningRate)}return i/t.length}getParameters(){return{layers:this.layers.map(t=>t.getParameters())}}setParameters(t){for(let e=0;e<this.layers.length&&e<t.layers.length;e++)this.layers[e].setParameters(t.layers[e])}clone(){let t=new c({layerSizes:[this.layers[0].inputSize,...this.layers.map(e=>e.outputSize)],activations:this.layers.map(e=>e.activation),learningRate:this.learningRate});return t.setParameters(this.getParameters()),t}softUpdate(t,e){for(let r=0;r<this.layers.length;r++){let i=this.layers[r],n=t.layers[r];for(let s=0;s<i.weights.length;s++)i.weights[s]=e*n.weights[s]+(1-e)*i.weights[s];for(let s=0;s<i.biases.length;s++)i.biases[s]=e*n.biases[s]+(1-e)*i.biases[s]}}};ge();var At=class{buffer=[];maxSize;priorities=null;usePrioritized;alpha=.6;beta=.4;betaIncrement=.001;epsilon=1e-6;constructor(t,e=!1){this.maxSize=t,this.usePrioritized=e,e&&(this.priorities=new Float32Array(t),this.priorities.fill(1))}add(t){this.buffer.length>=this.maxSize&&(this.buffer.shift(),this.priorities&&(this.priorities.set(this.priorities.slice(1)),this.priorities[this.maxSize-1]=1)),this.buffer.push(t)}addBatch(t){for(let e of t)this.add(e)}sample(t){if(this.buffer.length===0)return[];if(this.usePrioritized&&this.priorities)return this.samplePrioritized(t);let e=[],r=new Set;for(;r.size<Math.min(t,this.buffer.length);)r.add(Se(0,this.buffer.length));for(let i of r)e.push(this.buffer[i]);return e}samplePrioritized(t){let e=this.getPriorities(),r=[],i=[];for(let n=0;n<Math.min(t,this.buffer.length);n++){let s=z()*e.reduce((o,l)=>o+l,0),a=0;for(let o=0;o<e.length;o++)if(a+=e[o],s<=a){r.push(o);break}}for(let n of r)n<this.buffer.length&&i.push(this.buffer[n]);return this.beta=Math.min(1,this.beta+this.betaIncrement),i}getPriorities(){if(!this.priorities)return[];let t=[],e=this.priorities.reduce((r,i)=>r+Math.pow(i,this.alpha),0);for(let r=0;r<this.buffer.length;r++)t.push(Math.pow(this.priorities[r],this.alpha)/e);return t}updatePriorities(t,e){if(!(!this.priorities||!this.usePrioritized))for(let r=0;r<t.length;r++){let i=t[r],n=e[r];i<this.priorities.length&&(this.priorities[i]=Math.abs(n)+this.epsilon)}}getImportanceWeights(t){if(!this.usePrioritized||!this.priorities)return new Array(t.length).fill(1);let e=[],r=this.getPriorities(),i=this.getMaxImportanceWeight();for(let n of t)if(n<r.length&&r[n]>0){let s=Math.pow(this.buffer.length*r[n],-this.beta);e.push(s/i)}else e.push(1);return e}getMaxImportanceWeight(){if(!this.usePrioritized||!this.priorities)return 1;let t=this.getPriorities(),e=0;for(let r of t)if(r>0){let i=Math.pow(this.buffer.length*r,-this.beta);e=Math.max(e,i)}return e}size(){return this.buffer.length}isReady(t){return this.buffer.length>=t}clear(){this.buffer=[],this.priorities&&this.priorities.fill(1)}getAll(){return[...this.buffer]}getStats(){return{size:this.buffer.length,maxSize:this.maxSize,utilization:this.buffer.length/this.maxSize,usePrioritized:this.usePrioritized}}};var JC={stateSize:10,actionSize:4,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0,maxGradNorm:1},Ja=class extends ve{qNetwork;targetNetwork;replayBufferClass;qConfig;updateCount=0;actions=[];constructor(t={},e=Bp){super("q-learning","value-based",{},e),this.qConfig={...JC,...t},this.qNetwork=new J({layerSizes:[this.qConfig.stateSize,...this.qConfig.hiddenLayers,this.qConfig.actionSize],activations:Array(this.qConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass=new At(this.config.replayBufferSize,!1),this.initializeActions()}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.targetNetwork.forward(e),i=this.argmax(r),n=this.actions[i],s=r[i],a=this.calculateConfidence(r);return{action:n,confidence:a,value:s,reasoning:this.generateReasoning(t,n,s,a)}}async trainCore(t){for(let i of t)this.replayBufferClass.add(i);if(!this.replayBufferClass.isReady(this.qConfig.minReplaySize))return this.getStats();let e=this.replayBufferClass.sample(this.config.batchSize);if(e.length===0)return this.getStats();let r=0;for(let i of e){let n=this.prepareState(i.state),s=this.prepareState(i.nextState),a,o=this.qNetwork.forward(n),l=this.actionToIndex(i.action);if(this.qConfig.doubleDQN&&!i.done){let m=this.qNetwork.forward(s),p=this.argmax(m),v=this.targetNetwork.forward(s)[p];a=i.reward+this.config.discountFactor*v}else{let m=this.targetNetwork.forward(s),p=Math.max(...m);a=i.reward+this.config.discountFactor*p*(i.done?0:1)}let u=new Float32Array(o.length);for(let m=0;m<u.length;m++)u[m]=m===l?a:o[m];let d=this.qNetwork.train(n,u,new Fe);r+=Math.abs(d)}return this.updateCount++,this.updateCount%this.qConfig.targetUpdateFreq===0&&this.updateTargetNetwork(),{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/e.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural Q-Learning (DQN) for Coverage Path Optimization",capabilities:["Deep Q-Network for function approximation","Experience replay for stable learning","Target network for consistent targets","Double DQN for reduced overestimation","Coverage-aware test prioritization"],hyperparameters:{stateSize:this.qConfig.stateSize,actionSize:this.qConfig.actionSize,hiddenLayers:this.qConfig.hiddenLayers.join(","),targetUpdateFreq:this.qConfig.targetUpdateFreq,doubleDQN:String(this.qConfig.doubleDQN)},stats:this.stats}}updateTargetNetwork(){this.targetNetwork=this.qNetwork.clone()}prepareState(t){let e=t.features.slice(0,this.qConfig.stateSize);for(;e.length<this.qConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]=e[i]/r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"generate-unit",value:"standard"},{type:"generate-integration",value:"standard"},{type:"prioritize",value:"high"},{type:"skip",value:0}],this.qConfig.actionSize=this.actions.length,this.qNetwork=new J({layerSizes:[this.qConfig.stateSize,...this.qConfig.hiddenLayers,this.qConfig.actionSize],activations:Array(this.qConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone()}actionToIndex(t){let e=this.actionToKey(t);for(let r=0;r<this.actions.length;r++)if(this.actionToKey(this.actions[r])===e)return r;return 0}indexToAction(t){return this.actions[Math.min(t,this.actions.length-1)]}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}actionToKey(t){return`${t.type}:${JSON.stringify(t.value)}`}calculateConfidence(t){let e=Math.max(...t),r=Math.min(...t);if(e===r)return .5;let i=e-r;return Math.min(1,.3+i*2)}generateReasoning(t,e,r,i){return this.episodeCount<10?`Neural Q-Learning exploration phase (episode ${this.episodeCount}): ${e.type} action`:i>.8?`High-confidence Neural Q-Learning decision (${i.toFixed(2)}): ${e.type} with Q-value ${r.toFixed(3)} based on ${this.updateCount} network updates`:r>.5?`Positive Q-value (${r.toFixed(3)}) suggests ${e.type} is effective for current coverage state`:`Exploratory Neural Q-Learning action: ${e.type} with confidence ${i.toFixed(2)}`}async exportCustomData(){return{qNetwork:this.qNetwork.getParameters(),targetNetwork:this.targetNetwork.getParameters(),qConfig:this.qConfig,updateCount:this.updateCount,replayBufferSize:this.replayBufferClass.size()}}async importCustomData(t){t.qNetwork&&this.qNetwork.setParameters(t.qNetwork),t.targetNetwork&&this.targetNetwork.setParameters(t.targetNetwork),t.qConfig&&(this.qConfig={...this.qConfig,...t.qConfig}),typeof t.updateCount=="number"&&(this.updateCount=t.updateCount),this.initialized=!0}async resetAlgorithm(){this.qNetwork=new J({layerSizes:[this.qConfig.stateSize,...this.qConfig.hiddenLayers,this.qConfig.actionSize],activations:Array(this.qConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass.clear(),this.updateCount=0}};var YC={maxConcurrentWorkflows:5,defaultTimeout:6e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},at=x.create("coverage-analysis"),qn=class extends ie{constructor(e,r,i={},n){let s={...YC,...i};super(e,"coverage-analysis",s,{verifyFindingTypes:["coverage-gap","risk-zone","quality-regression"],...s.consensusConfig});this.memory=r;this.coverageAnalyzer=new Xt({memory:r,llmRouter:n}),this.gapDetector=new di({memory:r,llmRouter:n}),this.riskScorer=new mi(r),this.qLearning=new Ja(this.qlConfig,qp)}memory;coverageAnalyzer;gapDetector;riskScorer;ghostAnalyzer=null;qLearning;qlConfig={stateSize:12,actionSize:4,hiddenLayers:[128,64],targetUpdateFreq:50,minReplaySize:50,doubleDQN:!0};async onInitialize(){}async onDispose(){}subscribeToEvents(){}async getQLRecommendations(e,r=10){try{let i=[];for(let a of e.slice(0,r)){let o=await this.predictQL(a),l=this.actionToTestType(o.action),u=this.estimateCoverageGain(a,o.action),d=this.estimateTestDuration(a,l);i.push({filePath:a.file,testType:l,priority:o.value,estimatedCoverageGain:u,estimatedDuration:d,action:o.action,confidence:o.confidence})}i.sort((a,o)=>o.priority-a.priority);let n=i.reduce((a,o)=>a+o.estimatedCoverageGain,0),s=i.reduce((a,o)=>a+o.estimatedDuration,0);return f({tests:i,totalEstimatedCoverageGain:n,totalEstimatedDuration:s,reasoning:`Q-Learning prioritized ${i.length} tests based on coverage optimization potential`})}catch(i){return g(y(i))}}async predictQL(e){try{let r=this.gapToQLState(e),i=await this.qLearning.predict(r),n=this.estimateCoverageGain(e,i.action),s=this.actionToTestCount(i.action);return{action:i.action,confidence:i.confidence,value:i.value||0,reasoning:i.reasoning||"",estimatedCoverageGain:n,estimatedTestCount:s}}catch(r){return{action:{type:"generate-unit",value:"standard"},confidence:.3,value:0,reasoning:`Fallback prediction due to error: ${r.message}`,estimatedCoverageGain:.1,estimatedTestCount:1}}}async trainQL(e){try{await this.qLearning.trainBatch([e]);let r=this.qLearning.getStats();r.episode%10===0&&await this.memory.set("coverage:ql:model:latest",{stats:r,exportedAt:new Date().toISOString()})}catch(r){at.error("Failed to train Q-Learning model",r instanceof Error?r:void 0)}}gapToQLState(e){let r=[e.riskScore/10,Math.min(1,e.lines.length/50),Math.min(1,e.branches.length/10),this.severityToNumber(e.severity)/4,this.complexityFromPath(e.file),this.changeFrequencyFromPath(e.file),this.businessCriticalityFromPath(e.file),e.lines.length/Math.max(1,e.branches.length),this.calculateCoveragePotential(e),this.calculateFileComplexityScore(e),this.calculateTestComplexity(e),this.calculateExecutionCost(e)];return{id:e.id,features:r,metadata:{filePath:e.file,lines:e.lines,branches:e.branches,riskScore:e.riskScore,severity:e.severity},timestamp:new Date}}estimateCoverageGain(e,r){let i=(e.lines.length+e.branches.length*2)/1e3;switch(r.type){case"generate-unit":return i*.3;case"generate-integration":return i*.5;case"prioritize":return i*.7;case"skip":return 0;default:return i*.2}}estimateTestDuration(e,r){let i=e.lines.length*.5;switch(r){case"unit":return i;case"integration":return i*2;case"e2e":return i*5;default:return i}}actionToTestType(e){switch(e.type){case"generate-unit":return"unit";case"generate-integration":return"integration";case"prioritize":return"integration";default:return"unit"}}actionToTestCount(e){switch(e.type){case"generate-unit":return 3;case"generate-integration":return 2;case"prioritize":return 5;case"skip":return 0;default:return 1}}calculateCoveragePotential(e){let r=Math.min(1,e.lines.length/50),i=Math.min(1,e.branches.length/10),n=e.riskScore/10;return(r+i+n)/3}calculateFileComplexityScore(e){let i=e.file.split("/").length,n=/service|controller|provider|manager/i.test(e.file);return Math.min(1,(i+(n?2:0))/10)}calculateTestComplexity(e){let r=e.branches.length*.6,i=e.lines.length*.1;return Math.min(1,(r+i)/20)}calculateExecutionCost(e){let r=Math.min(1,e.lines.length/100),i=e.riskScore/10;return(r+i)/2}complexityFromPath(e){return["service","controller","provider","manager","handler"].some(n=>e.toLowerCase().includes(n))?.7:.3}changeFrequencyFromPath(e){return["src","lib","services","controllers"].some(n=>e.includes(n))?.6:.2}businessCriticalityFromPath(e){return["auth","payment","user","core","api"].some(n=>e.toLowerCase().includes(n))?.8:.4}isReady(){return this.initialized}async analyze(e){try{if(this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&at.warn("Topology degraded, using conservative analysis mode"),this.minCutMixin.shouldPauseOperations())return g(new Error("Coverage analysis paused: topology is in critical state"));let r=await this.coverageAnalyzer.analyze(e);return r.success&&r.value.measured!==!1&&await this.publishCoverageReport(r.value),r}catch(r){return g(y(r))}}async detectGaps(e){try{if(this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&at.warn("Topology degraded, using conservative gap detection"),this.minCutMixin.shouldPauseOperations())return g(new Error("Gap detection paused: topology is in critical state"));let r=await this.gapDetector.detectGaps(e);if(r.success){let i=[];for(let n of r.value.gaps){if(this.config.enableConsensus&&(n.severity==="critical"||n.severity==="high")){let s=Math.min(.95,n.riskScore/10+.3);if(!await this.verifyCoverageGap(n,s)){at.info(`Coverage gap in '${n.file}' not verified, skipping publication`);continue}}i.push(n)}return Qa(e)&&await this.publishGapEvents(i),f({...r.value,gaps:i})}return r}catch(r){return g(y(r))}}async calculateRisk(e){try{if(this.minCutMixin.shouldPauseOperations())return g(new Error("Risk calculation paused: topology is in critical state"));let r=await this.riskScorer.calculateRisk(e);if(r.success){if(this.config.enableConsensus&&(r.value.riskLevel==="critical"||r.value.riskLevel==="high")&&!await this.verifyRiskZone({file:r.value.file,riskScore:r.value.overallRisk,factors:r.value.factors.map(n=>({name:n.name,weight:n.contribution}))},Math.min(.95,r.value.overallRisk/10+.5)))return at.warn(`Risk zone '${r.value.file}' not verified, downgrading severity`),f({...r.value,riskLevel:r.value.riskLevel==="critical"?"high":"medium"});r.value.riskLevel==="critical"&&await this.publishRiskZoneEvent(r.value)}return r}catch(r){return g(y(r))}}async getTrend(e){try{let{timeRange:r,granularity:i}=e,n=await this.memory.search("coverage:history:*",100);if(n.length===0)return f({dataPoints:[],trend:"stable",forecast:0});let s=[];for(let u of n){let d=parseInt(u.split(":").pop()||"0",10),m=new Date(d);if(m>=r.start&&m<=r.end){let p=await this.memory.get(u);p&&p.measured===!0&&Number.isFinite(p.line)&&s.push({date:m,coverage:p})}}s.sort((u,d)=>u.date.getTime()-d.date.getTime());let a=this.aggregateByGranularity(s,i),o=this.analyzeCoverageTrend(a),l=this.forecastCoverage(a);return f({dataPoints:a,trend:o,forecast:l})}catch(r){return g(y(r))}}async findSimilar(e){try{let{pattern:r,k:i}=e,n=Date.now(),s=this.createGapEmbedding(r),a=await this.memory.vectorSearch(s,i),o=[];for(let u of a){let d=u.metadata;d&&o.push({gap:{id:u.key,file:d.file||"unknown",lines:[],branches:[],riskScore:d.riskScore||0,severity:d.severity||"low",recommendation:"Similar pattern found in codebase"},similarity:u.score})}let l=Date.now()-n;return f({patterns:o,searchTime:l})}catch(r){return g(y(r))}}async analyzeGhostCoverage(e,r){try{if(!this.ghostAnalyzer){let d={hnswIndex:Qi(this.memory),embedder:Vn()};this.ghostAnalyzer=new Bn(d),await this.ghostAnalyzer.initialize()}let i={files:e.map(d=>({path:d,lines:{covered:0,total:100},branches:{covered:0,total:10},functions:{covered:0,total:5},statements:{covered:0,total:100},uncoveredLines:[],uncoveredBranches:[]})),summary:{line:0,branch:0,function:0,statement:0,files:e.length}},n={name:r,sourcePatterns:e},s=await this.ghostAnalyzer.computePhantomSurface(i,n);if(!s.success)return g(s.error);let a=s.value,o=await this.ghostAnalyzer.detectPhantomGaps(a),u={gaps:(o.success?o.value:[]).map(d=>({id:d.id,category:d.category,description:d.description,confidence:d.confidence,severity:d.severity,suggestedTest:d.suggestedLines.length>0?`Add test covering lines ${d.suggestedLines.join(", ")} in ${d.file}`:`Add ${d.category} test for ${d.file}`})),totalGhostScore:a.phantomRatio,coverageCompleteness:1-a.phantomRatio,computedAt:new Date(a.computedAt)};return f(u)}catch(i){return g(y(i))}}async publishCoverageReport(e){let r={reportId:crypto.randomUUID(),line:e.summary.line,branch:e.collected&&!e.collected.branch?null:e.summary.branch,function:e.collected&&!e.collected.function?null:e.summary.function,statement:e.collected&&!e.collected.statement?null:e.summary.statement,files:e.summary.files,measured:!0,...e.runStatus?{runStatus:e.runStatus}:{}},i=N(Ts.CoverageReportCreated,"coverage-analysis",r);await this.eventBus.publish(i)}async publishGapEvents(e){let r=e.filter(i=>i.severity==="critical"||i.severity==="high");for(let i of r){let n={gapId:i.id,file:i.file,uncoveredLines:i.lines,uncoveredBranches:i.branches,riskScore:i.riskScore,measured:!0,coverageMethod:"instrumented-report"},s=N(Ts.CoverageGapDetected,"coverage-analysis",n);await this.eventBus.publish(s)}}async publishRiskZoneEvent(e){let r=N(Ts.RiskZoneIdentified,"coverage-analysis",{file:e.file,overallRisk:e.overallRisk,riskLevel:e.riskLevel,topFactors:e.factors.slice(0,3).map(i=>i.name),recommendations:e.recommendations});await this.eventBus.publish(r)}aggregateByGranularity(e,r){if(e.length===0)return[];let i=new Map;for(let s of e){let a=this.getBucketKey(s.date,r),o=i.get(a)||[];o.push(s),i.set(a,o)}let n=[];for(let[,s]of i)if(s.length>0){let a={line:s.reduce((o,l)=>o+l.coverage.line,0)/s.length,branch:s.reduce((o,l)=>o+l.coverage.branch,0)/s.length,function:s.reduce((o,l)=>o+l.coverage.function,0)/s.length,statement:s.reduce((o,l)=>o+l.coverage.statement,0)/s.length,files:Math.round(s.reduce((o,l)=>o+l.coverage.files,0)/s.length)};n.push({date:s[0].date,coverage:a})}return n.sort((s,a)=>s.date.getTime()-a.date.getTime())}getBucketKey(e,r){let i=e.getFullYear(),n=e.getMonth(),s=e.getDate();switch(r){case"daily":return`${i}-${n}-${s}`;case"weekly":{let a=Math.floor(s/7);return`${i}-${n}-W${a}`}case"monthly":return`${i}-${n}`}}analyzeCoverageTrend(e){if(e.length<2)return"stable";let r=e.map(u=>{let d=u.coverage;return(d.line+d.branch+d.function+d.statement)/4}),i=r.length,n=0,s=0,a=0,o=0;for(let u=0;u<i;u++)n+=u,s+=r[u],a+=u*r[u],o+=u*u;let l=(i*a-n*s)/(i*o-n*n);return l>.5?"improving":l<-.5?"declining":"stable"}forecastCoverage(e){if(e.length===0)return 0;let r=e.map(a=>{let o=a.coverage;return(o.line+o.branch+o.function+o.statement)/4});if(r.length===1)return r[0];let i=.3,n=r[0];for(let a=1;a<r.length;a++)n=i*r[a]+(1-i)*n;let s=this.analyzeCoverageTrend(e);return s==="improving"?n=Math.min(100,n+2):s==="declining"&&(n=Math.max(0,n-2)),n}createGapEmbedding(e){let i=new Array(384).fill(0);i[0]=e.riskScore,i[1]=Math.min(1,e.lines.length/100),i[2]=Math.min(1,e.branches.length/20),i[3]=this.severityToNumber(e.severity)/4;let n=e.file.split("").reduce((s,a)=>s+a.charCodeAt(0),0);i[4]=n%1e3/1e3;for(let s=5;s<384;s++)i[s]=Math.sin(s*e.riskScore)*.5+.5;return i}severityToNumber(e){switch(e){case"critical":return 4;case"high":return 3;case"medium":return 2;case"low":return 1;default:return 0}}async verifyCoverageGap(e,r){let i=U({id:w(),type:"coverage-gap",confidence:r,description:`Verify coverage gap in ${e.file}: ${e.lines.length} uncovered lines, ${e.branches.length} uncovered branches`,payload:e,detectedBy:"coverage-analysis-coordinator",severity:e.severity});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(at.info(`Coverage gap in '${e.file}' verified by consensus`),!0):(at.warn(`Coverage gap in '${e.file}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyRiskZone(e,r){let i=U({id:w(),type:"risk-zone",confidence:r,description:`Verify risk zone: ${e.file} with risk score ${e.riskScore.toFixed(2)}`,payload:e,detectedBy:"coverage-analysis-coordinator",severity:e.riskScore>=.8?"critical":e.riskScore>=.5?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(at.info(`Risk zone '${e.file}' classification verified by consensus`),!0):(at.warn(`Risk zone '${e.file}' classification NOT verified`),!1)}return!0}async verifyQualityRegression(e,r){let i=U({id:w(),type:"quality-regression",confidence:r,description:`Verify quality regression: ${e.metric} dropped from ${e.previousValue.toFixed(1)}% to ${e.currentValue.toFixed(1)}% (threshold: ${e.threshold}%)`,payload:e,detectedBy:"coverage-analysis-coordinator",severity:"critical"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(at.info("Quality regression verified by consensus"),!0):(at.warn(`Quality regression NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}};var Ya=class c extends te{static VERSION="1.0.0";coordinator;_activeAnalyses=0;constructor(t,e,r){super(t,e),this.coordinator=new qn(t,e,{},r)}get name(){return"coverage-analysis"}get version(){return c.VERSION}get dependencies(){return["test-execution"]}getAPI(){return this.coordinator}getCoverageAPI(){return this.coordinator}getTaskHandlers(){return new Map([["analyze-coverage",async t=>{let e=t.coverageData;if(!e)return g(new Error("Invalid analyze-coverage payload: missing coverageData"));this._activeAnalyses++,this.updateAgentMetrics();try{let{instrumented:r,...i}=e;return await this.coordinator.analyze({coverageData:i,threshold:t.threshold,includeFileDetails:t.includeFileDetails,measured:!1})}finally{this._activeAnalyses--,this.updateAgentMetrics()}}],["detect-gaps",async t=>{let e=t.coverageData;if(!e)return g(new Error("Invalid detect-gaps payload: missing coverageData"));this._activeAnalyses++,this.updateAgentMetrics();try{return await this.coordinator.detectGaps({coverageData:e,minCoverage:t.minCoverage,prioritize:t.prioritize})}finally{this._activeAnalyses--,this.updateAgentMetrics()}}],["calculate-risk",async t=>{let e=t.file,r=t.uncoveredLines;if(!e||!r)return g(new Error("Invalid calculate-risk payload: missing file or uncoveredLines"));this._activeAnalyses++,this.updateAgentMetrics();try{return await this.coordinator.calculateRisk({file:e,uncoveredLines:r,factors:t.factors})}finally{this._activeAnalyses--,this.updateAgentMetrics()}}],["analyze-ghost-coverage",async t=>{let e=t.existingTests,r=t.codeContext;if(!e||!r)return g(new Error("Invalid analyze-ghost-coverage payload: missing existingTests or codeContext"));this._activeAnalyses++,this.updateAgentMetrics();try{return await this.coordinator.analyzeGhostCoverage(e,r)}finally{this._activeAnalyses--,this.updateAgentMetrics()}}]])}async onInitialize(){await this.coordinator.initialize(),this.updateHealth({status:"idle",lastActivity:new Date})}async onDispose(){await this.coordinator.dispose(),this.updateHealth({status:"unhealthy",agents:{total:0,active:0,idle:0,failed:0}})}subscribeToEvents(){this.eventBus.subscribe(je.TestRunCompleted,this.handleTestRunCompleted.bind(this))}async onEvent(t){t.type===je.TestRunCompleted&&await this.handleTestRunCompleted(t)}async handleTestRunCompleted(t){let e=t.payload;if(e.coverageData){this._activeAnalyses++,this.updateAgentMetrics();try{await this.coordinator.analyze({coverageData:e.coverageData,includeFileDetails:!0})}finally{this._activeAnalyses--,this.updateAgentMetrics()}}}updateAgentMetrics(){let t={status:(this._activeAnalyses>0,"healthy"),agents:{total:3,active:this._activeAnalyses>0?1:0,idle:this._activeAnalyses>0?2:3,failed:0},lastActivity:new Date,errors:[]};this.updateHealth(t)}getHealth(){return{...this._health,agents:{total:3,active:this._activeAnalyses>0?1:0,idle:this._activeAnalyses>0?2:3,failed:0},lastActivity:new Date}}};function xu(c,t,e){return new Ya(c,t,e)}_();k();k();var XC=["coverage","complexity","maintainability","duplication","testability","security"],ZC={coverage:"coverage",duplication:"duplications"};function iq(c,t){return c??t}function ze(c){return typeof c=="number"&&Number.isFinite(c)&&c>=0}function nq(c){let t=XC,e=`metrics must be a non-empty array of metric names (${t.join(", ")}).`;if(!Array.isArray(c)||c.length===0)throw new Error(e);let r=c.filter(i=>typeof i!="string"||!t.includes(i));if(r.length>0)throw new Error(`${e} Unknown: ${r.map(i=>JSON.stringify(i)).join(", ")}.`);return[...new Set(c)]}function sq(c,t){let e=c.length>0?[...new Set(c)]:Object.keys(t).filter(s=>ze(t[s])),r=e.filter(s=>ze(t[s])),i=e.filter(s=>!ze(t[s])),n=e.length===0?0:Math.round(r.length/e.length*100)/100;return{evidenceStatus:i.length===0&&r.length>0?"measured":Qc,measured:r,unmeasured:i,confidence:n}}function aq(c,t,e={}){let r=Om(e),i=[];for(let n of c){let s=ZC[n],a=s?r[s]:void 0,o=t[n];if(!a||!ze(o))continue;(a.direction==="min"?o<a.value:o>a.value)&&i.push({metric:n,value:o,threshold:a.value,direction:a.direction})}return i}function oq(c){let t=c.direction==="min"?"at least":"at most";return`${c.metric} measured at ${c.value} fails its threshold (${t} ${c.threshold}).`}var eS={strictMode:!1,enableWarnings:!0,defaultSeverities:{coverage:"high",testsPassing:"critical",criticalBugs:"critical",codeSmells:"medium",securityVulnerabilities:"critical",technicalDebt:"medium",duplications:"low"}},tS={strict:{coverage:{min:90},testsPassing:{min:100},criticalBugs:{max:0},codeSmells:{max:10},securityVulnerabilities:{max:0},technicalDebt:{max:2},duplications:{max:3}},standard:{coverage:{min:80},testsPassing:{min:95},criticalBugs:{max:0},codeSmells:{max:20},securityVulnerabilities:{max:0},technicalDebt:{max:5},duplications:{max:5}},relaxed:{coverage:{min:60},testsPassing:{min:90},criticalBugs:{max:2},codeSmells:{max:50},securityVulnerabilities:{max:1},technicalDebt:{max:10},duplications:{max:10}}},Zt=class{constructor(t,e={}){this.memory=t;this.config={...eS,...e};for(let[r,i]of Object.entries(tS))this.presets.set(r,i)}memory;config;presets=new Map;async evaluateGate(t){try{let{gateName:e,metrics:r,thresholds:i}=t;if(!r)return g(new Error("No metrics provided for gate evaluation"));let n=[],s=[];if(n.push(...this.evaluateMinThresholds(r,i)),n.push(...this.evaluateMaxThresholds(r,i)),n.length===0)return g(new Error("No thresholds configured for gate evaluation"));let a=n.filter(d=>!ze(d.value)).map(d=>d.name);for(let d of n)d.passed||s.push(d.name);let o=this.calculateOverallScore(n),l=a.length===0&&this.determineGateStatus(n),u={gateName:e,passed:l,checks:n,overallScore:o,failedChecks:s,evidenceStatus:a.length===0?"measured":"insufficient-evidence",unmeasured:a};return await this.storeEvaluationResult(u),f(u)}catch(e){return g(y(e))}}async createGatePreset(t,e){try{let r=`preset-${t}-${w().slice(0,8)}`;return this.presets.set(t,e),await this.memory.set(`quality-gate:preset:${t}`,{id:r,name:t,thresholds:e,createdAt:new Date().toISOString()},{namespace:"quality-assessment",persist:!0}),f(r)}catch(r){return g(y(r))}}async getGatePreset(t){if(this.presets.has(t))return this.presets.get(t);let e=await this.memory.get(`quality-gate:preset:${t}`);if(e)return this.presets.set(t,e.thresholds),e.thresholds}async listGatePresets(){let t=await this.memory.search("quality-gate:preset:*",100),e=new Set(Array.from(this.presets.keys()));for(let r of t){let i=r.replace("quality-gate:preset:","");e.add(i)}return Array.from(e)}evaluateMinThresholds(t,e){let r=[];return e.coverage?.min!==void 0&&r.push(this.createCheck("coverage",t.coverage,e.coverage.min,"min",this.config.defaultSeverities.coverage)),e.testsPassing?.min!==void 0&&r.push(this.createCheck("testsPassing",t.testsPassing,e.testsPassing.min,"min",this.config.defaultSeverities.testsPassing)),r}evaluateMaxThresholds(t,e){let r=[];return e.criticalBugs?.max!==void 0&&r.push(this.createCheck("criticalBugs",t.criticalBugs,e.criticalBugs.max,"max",this.config.defaultSeverities.criticalBugs)),e.codeSmells?.max!==void 0&&r.push(this.createCheck("codeSmells",t.codeSmells,e.codeSmells.max,"max",this.config.defaultSeverities.codeSmells)),e.securityVulnerabilities?.max!==void 0&&r.push(this.createCheck("securityVulnerabilities",t.securityVulnerabilities,e.securityVulnerabilities.max,"max",this.config.defaultSeverities.securityVulnerabilities)),e.technicalDebt?.max!==void 0&&r.push(this.createCheck("technicalDebt",t.technicalDebt,e.technicalDebt.max,"max",this.config.defaultSeverities.technicalDebt)),e.duplications?.max!==void 0&&r.push(this.createCheck("duplications",t.duplications,e.duplications.max,"max",this.config.defaultSeverities.duplications)),r}createCheck(t,e,r,i,n){let s=ze(e)&&(i==="min"?e>=r:e<=r);return{name:t,passed:s,value:e,threshold:r,severity:n}}calculateOverallScore(t){if(t.length===0)return 100;let e={critical:3,high:2,medium:1.5,low:1,info:.5},r=0,i=0;for(let n of t){let s=e[n.severity];r+=s,n.passed&&(i+=s)}return r>0?Math.round(i/r*100):100}determineGateStatus(t){return this.config.strictMode?t.every(e=>e.passed):t.filter(e=>e.severity==="critical"||e.severity==="high").every(e=>e.passed)}async storeEvaluationResult(t){let e=`quality-gate:evaluation:${t.gateName}:${Date.now()}`;await this.memory.set(e,{...t,evaluatedAt:new Date().toISOString()},{namespace:"quality-assessment",ttl:86400*30})}};_();ei();var rS=/(?:^|[(,=:[!&|?{;+\-*%~^]|\b(?:return|typeof|case|do|else|in|of|void|yield|await))$/,wg=c=>c.replace(/[^\n]/g," ");function iS(c){let t=c.length-1;for(;t>=0&&/\s/.test(c[t]);)t--;return rS.test(c.slice(Math.max(0,t-9),t+1))}function nS(c,t){let e=c[t],r=!1;for(let i=t+1;i<c.length;i++){let n=c[i];if(n==="\\"){i++;continue}if(n===`
2616
+ });`}};k();var GC=[{name:"uncovered-lines",weight:.25},{name:"complexity",weight:.2},{name:"defect-history",weight:.2},{name:"change-frequency",weight:.15},{name:"code-age",weight:.1},{name:"dependency-count",weight:.1}],mi=class c{constructor(t){this.memory=t}memory;static HISTORY_KEY_PREFIX="risk-history";static MAX_TREND_POINTS=30;async calculateRisk(t){try{let{file:e,uncoveredLines:r,factors:i=GC}=t,n=this.normalizeFactorWeights(i),s=await this.calculateFactorScores(e,r,n),a=s.reduce((u,d)=>u+d.score*d.contribution,0),o=this.riskScoreToSeverity(a),l=this.generateRiskRecommendations(e,a,o,s);return await this.storeRiskSnapshot(e,a,s),f({file:e,overallRisk:a,riskLevel:o,factors:s,recommendations:l})}catch(e){return g(y(e))}}async factorInHistory(t,e){try{let r=await this.getDefectHistory(t),i=Math.min(1,r.count/10)*.3,n=await this.getChangeFrequency(t),s=Math.min(1,n/20)*.2,a=await this.getRiskTrend(t),o=0;if(a.success){let u=a.value;u.trend==="increasing"?o=.15:u.trend==="decreasing"&&(o=-.1)}let l=e+i+s+o;return Math.min(1,Math.max(0,l))}catch{return e}}async getRiskTrend(t){try{let e=`${c.HISTORY_KEY_PREFIX}:${t}`,r=await this.memory.get(e);if(!r||r.length===0)return f({file:t,dataPoints:[],trend:"stable",forecast:.5});let i=r.slice(-c.MAX_TREND_POINTS).map(a=>({date:new Date(a.timestamp),riskScore:a.riskScore,factors:a.topFactors})),n=this.analyzeTrend(i),s=this.forecastRisk(i);return f({file:t,dataPoints:i,trend:n,forecast:s})}catch(e){return g(y(e))}}normalizeFactorWeights(t){let e=t.reduce((r,i)=>r+i.weight,0);return e===0?t:t.map(r=>({...r,weight:r.weight/e}))}async calculateFactorScores(t,e,r){let i=[];for(let n of r){let s=await this.calculateSingleFactorScore(n.name,t,e);i.push({name:n.name,score:s,contribution:n.weight})}return i}async calculateSingleFactorScore(t,e,r){switch(t){case"uncovered-lines":return this.calculateUncoveredLinesScore(r);case"complexity":return await this.calculateComplexityScore(e);case"defect-history":return await this.calculateDefectHistoryScore(e);case"change-frequency":return await this.calculateChangeFrequencyScore(e);case"code-age":return await this.calculateCodeAgeScore(e);case"dependency-count":return await this.calculateDependencyScore(e);default:return .5}}calculateUncoveredLinesScore(t){let e=t.length;return e===0?0:e<=5?.2:e<=15?.4:e<=30?.6:e<=50?.8:1}async calculateComplexityScore(t){try{let e=await this.memory.get(`complexity:${t}`);if(!e)return .5;let r=e.cyclomatic;return r<=5?.2:r<=10?.4:r<=20?.6:r<=30?.8:1}catch{return .5}}async calculateDefectHistoryScore(t){let r=(await this.getDefectHistory(t)).count;return r===0?.1:r<=2?.3:r<=5?.5:r<=10?.7:.9}async calculateChangeFrequencyScore(t){let e=await this.getChangeFrequency(t);return e<=2?.2:e<=5?.4:e<=10?.6:e<=20?.8:1}async calculateCodeAgeScore(t){try{let e=await this.memory.get(`file-metadata:${t}`);if(!e)return .5;let r=(Date.now()-new Date(e.createdAt).getTime())/(1e3*60*60*24);return r<=7?.8:r<=30?.5:r<=90?.3:r<=365?.4:.6}catch{return .5}}async calculateDependencyScore(t){try{let e=await this.memory.get(`dependencies:${t}`);if(!e)return .5;let r=e.count;return r<=3?.2:r<=7?.4:r<=15?.6:r<=25?.8:1}catch{return .5}}async getDefectHistory(t){try{return{count:(await this.memory.get(`defect-history:${t}`))?.defectCount??0}}catch{return{count:0}}}async getChangeFrequency(t){try{return(await this.memory.get(`change-frequency:${t}`))?.changesLast90Days??5}catch{return 5}}riskScoreToSeverity(t){return t>=.8?"critical":t>=.6?"high":t>=.3?"medium":t>=.1?"low":"info"}generateRiskRecommendations(t,e,r,i){let n=[],a=[...i].sort((o,l)=>l.score*l.contribution-o.score*o.contribution).slice(0,3);r==="critical"?n.push(`CRITICAL: ${t} has a risk score of ${(e*100).toFixed(1)}%. Immediate action required.`):r==="high"&&n.push(`HIGH RISK: ${t} should be prioritized for test coverage improvement.`);for(let o of a)o.score>=.6&&n.push(this.getFactorRecommendation(o.name,o.score));return e>=.5&&n.push("Consider breaking this file into smaller, more testable modules."),i.find(o=>o.name==="defect-history"&&o.score>=.5)&&n.push("This file has a history of defects. Add regression tests for known issues."),n}getFactorRecommendation(t,e){let r=e>=.8?"Critical":"High";switch(t){case"uncovered-lines":return`${r}: Many uncovered lines. Focus on adding unit tests for core logic.`;case"complexity":return`${r}: High complexity detected. Consider refactoring before adding tests.`;case"defect-history":return`${r}: Past defects in this area. Add regression tests to prevent recurrence.`;case"change-frequency":return`${r}: Frequently changed code. Ensure comprehensive test coverage.`;case"code-age":return`${r}: Code age indicates risk. Review and update tests accordingly.`;case"dependency-count":return`${r}: Many dependencies. Add integration tests to verify interactions.`;default:return`${r}: Factor "${t}" indicates elevated risk.`}}async storeRiskSnapshot(t,e,r){try{let i=`${c.HISTORY_KEY_PREFIX}:${t}`,n=await this.memory.get(i)??[],s={timestamp:Date.now(),riskScore:e,topFactors:r.filter(o=>o.score>=.5).map(o=>o.name)},a=[...n,s].slice(-c.MAX_TREND_POINTS);await this.memory.set(i,a,{persist:!0})}catch{}}analyzeTrend(t){if(t.length<3)return"stable";let e=t.length,r=0,i=0,n=0,s=0;for(let o=0;o<e;o++){let l=o,u=t[o].riskScore;r+=l,i+=u,n+=l*u,s+=l*l}let a=(e*n-r*i)/(e*s-r*r);return a>.01?"increasing":a<-.01?"decreasing":"stable"}forecastRisk(t){if(t.length===0)return .5;if(t.length===1)return t[0].riskScore;let e=.3,r=t[0].riskScore;for(let n=1;n<t.length;n++)r=e*t[n].riskScore+(1-e)*r;let i=this.analyzeTrend(t);return i==="increasing"?r=Math.min(1,r+.05):i==="decreasing"&&(r=Math.max(0,r-.05)),r}};var Au={dimensions:384,includePathFeatures:!0,includeTemporalFeatures:!0,normalization:"l2"},_n=class{config;constructor(t={}){this.config={...Au,...t}}embedFileCoverage(t){let e=new Array(this.config.dimensions).fill(0),r=0;return r=this.encodeCoverageMetrics(e,t,r),r=this.encodeGapCharacteristics(e,t,r),r=this.encodeRiskFactors(e,t,r),r=this.encodeFileCharacteristics(e,t,r),this.encodeDerivedFeatures(e,t,r),{vector:this.normalize(e),metadata:this.createMetadata(t),confidence:this.calculateConfidence(t)}}embedCoverageGap(t){let e=new Array(this.config.dimensions).fill(0);e[0]=t.riskScore,e[1]=Math.min(1,t.lines.length/100),e[2]=Math.min(1,t.branches.length/20),e[3]=this.severityToNumber(t.severity)/4;let r=this.extractPathFeatures(t.file);if(e[4]=r.depth/10,e[5]=r.hashNormalized,t.lines.length>1){let n=t.lines[t.lines.length-1]-t.lines[0];e[6]=Math.min(1,n/500),e[7]=t.lines.length/(n+1)}for(let n=8;n<this.config.dimensions;n++){let s=t.riskScore*n+t.lines.length*.01;e[n]=Math.sin(s)*.5+.5}return{vector:this.normalize(e),metadata:{filePath:t.file,lineCoverage:0,branchCoverage:0,functionCoverage:0,statementCoverage:0,uncoveredLineCount:t.lines.length,uncoveredBranchCount:t.branches.length,riskScore:t.riskScore,lastUpdated:Date.now(),totalLines:t.lines.length>0?t.lines[t.lines.length-1]:0},confidence:.8}}embedQuery(t){let e=new Array(this.config.dimensions).fill(0);if(t.minLineCoverage!==void 0&&(e[0]=t.minLineCoverage/100),t.maxLineCoverage!==void 0&&(e[1]=t.maxLineCoverage/100),t.minBranchCoverage!==void 0&&(e[2]=t.minBranchCoverage/100),t.maxBranchCoverage!==void 0&&(e[3]=t.maxBranchCoverage/100),t.minRiskScore!==void 0&&(e[4]=t.minRiskScore),t.maxRiskScore!==void 0&&(e[5]=t.maxRiskScore),t.filePattern){let r=this.extractPathFeatures(t.filePattern);e[6]=r.depth/10,e[7]=r.hashNormalized}t.maxUncoveredLines!==void 0&&(e[8]=Math.min(1,t.maxUncoveredLines/100));for(let r=9;r<this.config.dimensions;r++)e[r]===0&&(e[r]=.5);return{vector:this.normalize(e),metadata:{filePath:t.filePattern||"",lineCoverage:t.minLineCoverage||0,branchCoverage:t.minBranchCoverage||0,functionCoverage:0,statementCoverage:0,uncoveredLineCount:t.maxUncoveredLines||0,uncoveredBranchCount:0,riskScore:t.minRiskScore||0,lastUpdated:Date.now(),totalLines:0},confidence:.7}}batchEmbed(t){return t.map(e=>this.embedFileCoverage(e))}encodeCoverageMetrics(t,e,r){return t[r++]=e.lines.total>0?e.lines.covered/e.lines.total:0,t[r++]=Math.min(1,e.lines.total/1e3),t[r++]=Math.min(1,e.lines.covered/500),t[r++]=e.lines.total>0?e.uncoveredLines.length/e.lines.total:0,t[r++]=e.branches.total>0?e.branches.covered/e.branches.total:1,t[r++]=Math.min(1,e.branches.total/200),t[r++]=Math.min(1,e.branches.covered/100),t[r++]=e.branches.total>0?e.uncoveredBranches.length/e.branches.total:0,t[r++]=e.functions.total>0?e.functions.covered/e.functions.total:1,t[r++]=Math.min(1,e.functions.total/50),t[r++]=Math.min(1,e.functions.covered/25),t[r++]=e.functions.total>0?1-e.functions.covered/e.functions.total:0,t[r++]=e.statements.total>0?e.statements.covered/e.statements.total:1,t[r++]=Math.min(1,e.statements.total/1e3),t[r++]=Math.min(1,e.statements.covered/500),t[r++]=e.statements.total>0?1-e.statements.covered/e.statements.total:0,r}encodeGapCharacteristics(t,e,r){let i=e.uncoveredLines,n=e.uncoveredBranches;if(t[r++]=Math.min(1,i.length/100),t[r++]=Math.min(1,n.length/50),t[r++]=Math.min(1,(i.length+n.length)/150),t[r++]=i.length>0?1:0,i.length>1){let s=[...i].sort((u,d)=>u-d),a=s[s.length-1]-s[0],o=i.length/(a+1);t[r++]=Math.min(1,a/500),t[r++]=Math.min(1,o);let l=this.countContiguousRegions(s);t[r++]=Math.min(1,l/10),t[r++]=l>0?i.length/l:0}else t[r++]=0,t[r++]=i.length>0?1:0,t[r++]=i.length>0?.1:0,t[r++]=i.length;if(i.length>0&&e.lines.total>0){let s=Math.min(...i),a=Math.max(...i);t[r++]=s/e.lines.total,t[r++]=a/e.lines.total,t[r++]=(a-s)/e.lines.total,t[r++]=i.filter(o=>o<=e.lines.total*.2).length/i.length}else r+=4;return r+=4,r}encodeRiskFactors(t,e,r){let i=this.calculateOverallCoverage(e);t[r++]=1-i,t[r++]=e.branches.total>0?1-e.branches.covered/e.branches.total:0,t[r++]=e.functions.total>0?1-e.functions.covered/e.functions.total:0,t[r++]=Math.min(1,e.uncoveredLines.length/50),t[r++]=Math.min(1,e.lines.total/500),t[r++]=Math.min(1,e.functions.total/30),t[r++]=Math.min(1,e.branches.total/100),t[r++]=e.lines.total>300?.8:e.lines.total/375;let n=this.calculateLargeGapRatio(e.uncoveredLines);return t[r++]=n,t[r++]=e.uncoveredBranches.length>10?1:e.uncoveredBranches.length/10,t[r++]=e.uncoveredLines.length>30?1:e.uncoveredLines.length/30,t[r++]=this.calculateGapConcentration(e),r+=4,r}encodeFileCharacteristics(t,e,r){let i=this.extractPathFeatures(e.path);return t[r++]=i.depth/10,t[r++]=i.hashNormalized,t[r++]=i.isTest?.1:.9,t[r++]=i.isConfig?.2:.8,t[r++]=i.extension==="ts"?1:0,t[r++]=i.extension==="js"?1:0,t[r++]=i.extension==="tsx"||i.extension==="jsx"?1:0,t[r++]=i.isIndex?.5:0,t[r++]=i.inSrc?1:0,t[r++]=i.inLib?.8:0,t[r++]=i.inDomains?1:0,t[r++]=i.inServices?.9:0,r+=4,r}encodeDerivedFeatures(t,e,r){let i=[e.lines.covered/(e.lines.total||1),e.branches.covered/(e.branches.total||1),e.functions.covered/(e.functions.total||1),e.statements.covered/(e.statements.total||1),e.uncoveredLines.length/(e.lines.total||1),e.uncoveredBranches.length/(e.branches.total||1)];for(let n=0;n<6;n++)for(let s=n+1;s<6&&r<this.config.dimensions;s++)t[r++]=(i[n]+i[s])/2,r<this.config.dimensions&&(t[r++]=Math.abs(i[n]-i[s]));for(;r<this.config.dimensions-6;){let n=(r-64)%i.length;t[r++]=i[n]*i[n],r<this.config.dimensions&&(t[r++]=Math.sqrt(i[n]))}for(;r<this.config.dimensions;){let n=(r-64)*.1,s=i[(r-64)%i.length];t[r++]=Math.sin(s*Math.PI+n)*.5+.5}}normalize(t){switch(this.config.normalization){case"l2":return this.l2Normalize(t);case"minmax":return this.minMaxNormalize(t);default:return t}}l2Normalize(t){let e=Math.sqrt(t.reduce((r,i)=>r+i*i,0));return e===0?t:t.map(r=>r/e)}minMaxNormalize(t){let e=Math.min(...t),i=Math.max(...t)-e;return i===0?t.map(()=>.5):t.map(n=>(n-e)/i)}createMetadata(t){return{filePath:t.path,lineCoverage:t.lines.total>0?t.lines.covered/t.lines.total*100:0,branchCoverage:t.branches.total>0?t.branches.covered/t.branches.total*100:0,functionCoverage:t.functions.total>0?t.functions.covered/t.functions.total*100:0,statementCoverage:t.statements.total>0?t.statements.covered/t.statements.total*100:0,uncoveredLineCount:t.uncoveredLines.length,uncoveredBranchCount:t.uncoveredBranches.length,riskScore:this.calculateRiskScore(t),lastUpdated:Date.now(),totalLines:t.lines.total}}calculateConfidence(t){let e=t.lines.total>0,r=t.branches.total>0,i=t.functions.total>0,n=t.statements.total>0,s=.5;return e&&(s+=.2),r&&(s+=.1),i&&(s+=.1),n&&(s+=.1),Math.min(1,s)}calculateOverallCoverage(t){let e=t.lines.total>0?t.lines.covered/t.lines.total:1,r=t.branches.total>0?t.branches.covered/t.branches.total:1,i=t.functions.total>0?t.functions.covered/t.functions.total:1,n=t.statements.total>0?t.statements.covered/t.statements.total:1;return(e+r+i+n)/4}calculateRiskScore(t){let e=t.lines.total>0?1-t.lines.covered/t.lines.total:0,r=t.branches.total>0?1-t.branches.covered/t.branches.total:0,i=t.functions.total>0?1-t.functions.covered/t.functions.total:0;return Math.min(1,e*.3+r*.4+i*.3)}countContiguousRegions(t){if(t.length===0)return 0;let e=1;for(let r=1;r<t.length;r++)t[r]-t[r-1]>3&&e++;return e}calculateLargeGapRatio(t){if(t.length===0)return 0;let e=[...t].sort((s,a)=>s-a),r=0,i=1;for(let s=1;s<e.length;s++)e[s]-e[s-1]<=3?i++:(i>10&&r++,i=1);i>10&&r++;let n=this.countContiguousRegions(e);return n>0?r/n:0}calculateGapConcentration(t){if(t.uncoveredLines.length===0||t.lines.total===0)return 0;let e=this.countContiguousRegions([...t.uncoveredLines].sort((i,n)=>i-n)),r=Math.ceil(t.uncoveredLines.length/5);return e>0?Math.min(1,r/e):0}extractPathFeatures(t){let e=t.split("/").filter(Boolean),r=t.split(".").pop()||"",i=e[e.length-1]||"";return{depth:e.length,extension:r,hashNormalized:this.hashString(t)/1e6,isTest:/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(t)||e.includes("tests")||e.includes("__tests__"),isConfig:/\.(config|rc)\.(ts|js|json|yaml|yml)$/.test(t),isIndex:i.startsWith("index."),inSrc:e.includes("src"),inLib:e.includes("lib"),inDomains:e.includes("domains"),inServices:e.includes("services")}}hashString(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i|0}return Math.abs(e)}severityToNumber(t){switch(t){case"critical":return 4;case"high":return 3;case"medium":return 2;case"low":return 1;default:return 0}}};function Vn(c){return new _n(c)}_();k();var Mz=x.create("coverage-analysis/sublinear-analyzer");bs();k();var zn=["missing-error-handler","absent-boundary-validation","unprotected-state-transition","missing-integration-contract","absent-edge-case","missing-security-check"],jC={dimensions:384,minConfidence:.3,maxGaps:50,riskWeight:.6,distanceWeight:.4,namespace:"ghost-surface",idealSurfaceDecay:.95},Bn=class c{config;hnswIndex;embedder;idealSurfacePatterns=[];cachedIdealSurface=null;cachedPhantomRatio=1;initialized=!1;constructor(t,e={}){this.config={...jC,...e},this.hnswIndex=t.hnswIndex,this.embedder=t.embedder}async initialize(){try{return this.idealSurfacePatterns=this.buildBaselinePatterns(),this.cachedIdealSurface=this.aggregateIdealSurface(),this.initialized=!0,f(void 0)}catch(t){return g(y(t))}}async computePhantomSurface(t,e){try{this.ensureInitialized();let r=this.buildIdealSurface(e),i=new Map,n=[];for(let o of t.files){let l=this.embedder.embedFileCoverage(o).vector;n.push(l),i.set(o.path,this.computeGhostVector(l,r)),await this.hnswIndex.insert(`${this.config.namespace}:${o.path}`,i.get(o.path),{filePath:o.path,lineCoverage:this.ratio(o.lines.covered,o.lines.total)*100,branchCoverage:this.ratio(o.branches.covered,o.branches.total)*100,functionCoverage:this.ratio(o.functions.covered,o.functions.total)*100,statementCoverage:this.ratio(o.statements.covered,o.statements.total)*100,uncoveredLineCount:o.uncoveredLines.length,uncoveredBranchCount:o.uncoveredBranches.length,riskScore:this.fileRiskScore(o),lastUpdated:Date.now(),totalLines:o.lines.total})}let s=this.aggregateSurface(n),a=this.phantomRatioFromVectors(r,s);return this.cachedIdealSurface=r,this.cachedPhantomRatio=a,f({ghostVectors:i,idealSurface:r,actualSurface:s,phantomRatio:a,computedAt:Date.now(),filesAnalyzed:t.files.length})}catch(r){return g(y(r))}}async detectPhantomGaps(t,e){try{this.ensureInitialized();let r=e??this.config.minConfidence,i=[];for(let[n,s]of t.ghostVectors){if(vs(s)<.01)continue;let a=await this.hnswIndex.search(s,5),o=this.getApplicableCategories(n);for(let l of this.classifyGhost(s,a)){if(l.confidence<r||!o.has(l.category))continue;let u=this.gapRiskScore(s,l.category),d=Math.min(1,vs(s));i.push({id:this.gapId(n,l.category),file:n,category:l.category,ghostDistance:d,riskScore:u,severity:this.toSeverity(d,u),confidence:l.confidence,description:this.gapDescription(n,l.category,d),suggestedLines:l.suggestedLines})}}return i.sort((n,s)=>s.ghostDistance*s.riskScore-n.ghostDistance*n.riskScore),f(i.slice(0,this.config.maxGaps))}catch(r){return g(y(r))}}rankPhantomGaps(t){let{riskWeight:e,distanceWeight:r}=this.config;return[...t].sort((i,n)=>e*n.riskScore+r*n.ghostDistance-(e*i.riskScore+r*i.ghostDistance))}async updateIdealSurface(t){try{this.ensureInitialized();for(let e of this.idealSurfacePatterns)e.weight*=this.config.idealSurfaceDecay;for(let e of t){if(e.vector.length!==this.config.dimensions)continue;let r=this.idealSurfacePatterns.findIndex(i=>i.id===e.id);r>=0?this.idealSurfacePatterns[r]=e:this.idealSurfacePatterns.push(e)}return this.idealSurfacePatterns=this.idealSurfacePatterns.filter(e=>e.weight>.01),this.cachedIdealSurface=this.aggregateIdealSurface(),f(this.idealSurfacePatterns.length)}catch(e){return g(y(e))}}getPhantomRatio(){return this.cachedPhantomRatio}computeGhostVector(t,e){let r=Math.min(t.length,e.length),i=new Array(r);for(let n=0;n<r;n++)i[n]=Math.max(0,e[n]-t[n]);return pr(i)}buildBaselinePatterns(){let t=this.config.dimensions,e=Math.floor(t/zn.length);return zn.map((r,i)=>{let n=new Array(t).fill(0),s=i*e,a=Math.min(s+e,t);for(let o=s;o<a;o++)n[o]=Math.sin((o-s)/e*Math.PI)*.8+.2;return n[0]=.9,n[1]=.85,n[2]=.9,n[3]=.85,{id:`baseline-${r}`,category:r,vector:pr(n),weight:1,source:"baseline"}})}buildIdealSurface(t){let e=this.aggregateIdealSurface();if(t.riskAreas?.length)for(let r=32;r<48&&r<e.length;r++)e[r]*=1.2;if(t.defectHistory?.length){let r=Math.min(1.5,1+t.defectHistory.length*.05);for(let i=0;i<16&&i<e.length;i++)e[i]*=r}return pr(e)}aggregateIdealSurface(){let t=this.config.dimensions;if(this.idealSurfacePatterns.length===0)return pr(new Array(t).fill(1));let e=new Array(t).fill(0),r=0;for(let i of this.idealSurfacePatterns){for(let n=0;n<t;n++)e[n]+=i.vector[n]*i.weight;r+=i.weight}if(r>0)for(let i=0;i<t;i++)e[i]/=r;return pr(e)}aggregateSurface(t){let e=this.config.dimensions;if(t.length===0)return new Array(e).fill(0);let r=new Array(e).fill(0);for(let i of t)for(let n=0;n<e&&n<i.length;n++)r[n]+=i[n];for(let i=0;i<e;i++)r[i]/=t.length;return pr(r)}classifyGhost(t,e){let r=this.config.dimensions,i=Math.floor(r/zn.length),n=[],s=0;for(let a of e)a.score>.7&&(s+=a.score*.1);for(let a=0;a<zn.length;a++){let o=a*i,l=Math.min(o+i,r),u=0;for(let m=o;m<l&&m<t.length;m++)u+=t[m]**2;u=Math.sqrt(u/(l-o));let d=Math.min(1,u+s);d>.05&&n.push({category:zn[a],confidence:d,suggestedLines:this.suggestLines(a,t)})}return n.sort((a,o)=>o.confidence-a.confidence)}suggestLines(t,e){let r=e[0]||0,i=e[2]||0;if(r<.1&&i<.1)return[];let n=t*20+1,s=Math.ceil(r*10),a=[];for(let o=0;o<s&&a.length<10;o++)a.push(n+o*5);return a}getApplicableCategories(t){let e=t.toLowerCase(),r=e.split("/").pop()||e,i=new Set(["missing-error-handler","absent-edge-case"]);return/\b(math|calc|util|helper|format|parse|convert|transform)\b/.test(r)?(i.add("absent-boundary-validation"),i):(i.add("absent-boundary-validation"),/\b(auth|security|token|credential|password|session|permission|rbac|acl|encrypt|crypto)\b/.test(e)&&i.add("missing-security-check"),/\b(service|controller|handler|router|middleware|api|endpoint|gateway|adapter)\b/.test(e)&&(i.add("missing-integration-contract"),i.add("unprotected-state-transition")),/\b(state|store|reducer|saga|machine|workflow|queue|scheduler)\b/.test(e)&&i.add("unprotected-state-transition"),i)}static CATEGORY_RISK={"missing-security-check":1.5,"missing-error-handler":1.3,"unprotected-state-transition":1.2,"missing-integration-contract":1.1,"absent-boundary-validation":1,"absent-edge-case":.8};gapRiskScore(t,e){return Math.min(1,vs(t)*(c.CATEGORY_RISK[e]??1))}fileRiskScore(t){return Math.min(1,(1-this.ratio(t.lines.covered,t.lines.total))*.3+(1-this.ratio(t.branches.covered,t.branches.total))*.4+(1-this.ratio(t.functions.covered,t.functions.total))*.3)}phantomRatioFromVectors(t,e){return!t.length||!e.length?1:Math.max(0,Math.min(1,1-Mt(t,e)))}toSeverity(t,e){let r=(t+e)/2;return r>=.8?"critical":r>=.6?"high":r>=.3?"medium":"low"}ensureInitialized(){if(!this.initialized)throw new Error("GhostCoverageAnalyzerService not initialized. Call initialize() first.")}ratio(t,e){return e>0?t/e:0}gapId(t,e){let r=`${t}:${e}`.split("").reduce((i,n)=>(i<<5)-i+n.charCodeAt(0)|0,0);return`phantom-${Math.abs(r).toString(16)}`}gapDescription(t,e,r){let i=t.split("/").pop()||t,n=r>.7?"significant":r>.4?"moderate":"minor";return{"missing-error-handler":`${i}: ${n} missing error handler tests. Cover error paths and failure recovery.`,"absent-boundary-validation":`${i}: ${n} missing boundary validation tests. Cover input bounds and null checks.`,"unprotected-state-transition":`${i}: ${n} missing state transition tests. Cover state changes and race conditions.`,"missing-integration-contract":`${i}: ${n} missing integration contract tests. Cover external API boundaries.`,"absent-edge-case":`${i}: ${n} missing edge case tests. Cover empty inputs, max values, and timeouts.`,"missing-security-check":`${i}: ${n} missing security check tests. Cover auth bypass and injection attacks.`}[e]}};ge();var Q=class{forward(t){return Math.max(0,t)}backward(t){return t>0?1:0}};var K=class{forward(t){return t}backward(t){return 1}},Ie=class c{static forward(t){let e=Math.max(...t),r=t.map(n=>Math.exp(n-e)),i=r.reduce((n,s)=>n+s,0);return new Float32Array(r.map(n=>n/i))}static backward(t,e){let r=c.forward(t),i=new Float32Array(t.length);for(let n=0;n<t.length;n++)i[n]=r[n]-e[n];return i}},Fe=class{forward(t,e){let r=e instanceof Float32Array?e:new Float32Array(e),i=0;for(let n=0;n<t.length;n++){let s=t[n]-r[n];i+=s*s}return i/t.length}backward(t,e){let r=e instanceof Float32Array?e:new Float32Array(e),i=new Float32Array(t.length),n=t.length;for(let s=0;s<n;s++)i[s]=2*(t[s]-r[s])/n;return i}};var Ka=class{weights;biases;weightGradients;biasGradients;activation;inputSize;outputSize;lastInput=null;lastPreActivation=null;lastOutput=null;constructor(t){this.inputSize=t.inputSize,this.outputSize=t.outputSize,this.activation=t.activation;let e=Math.sqrt(2/(this.inputSize+this.outputSize));this.weights=new Float32Array(this.inputSize*this.outputSize),this.biases=new Float32Array(this.outputSize),this.weightGradients=new Float32Array(this.inputSize*this.outputSize),this.biasGradients=new Float32Array(this.outputSize);for(let r=0;r<this.weights.length;r++)this.weights[r]=(z()*2-1)*e;for(let r=0;r<this.biases.length;r++)this.biases[r]=0}forward(t){this.lastInput=t;let e=new Float32Array(this.outputSize),r=new Float32Array(this.outputSize);for(let i=0;i<this.outputSize;i++){let n=this.biases[i];for(let s=0;s<this.inputSize;s++)n+=t[s]*this.weights[i*this.inputSize+s];r[i]=n,e[i]=this.activation.forward(n)}return this.lastPreActivation=r,this.lastOutput=e,e}backward(t){if(!this.lastInput||!this.lastPreActivation)throw new Error("Must call forward before backward");let e=new Float32Array(this.outputSize);for(let i=0;i<this.outputSize;i++)e[i]=this.activation.backward(this.lastPreActivation[i])*t[i];for(let i=0;i<this.outputSize;i++){for(let n=0;n<this.inputSize;n++)this.weightGradients[i*this.inputSize+n]+=e[i]*this.lastInput[n];this.biasGradients[i]+=e[i]}let r=new Float32Array(this.inputSize);for(let i=0;i<this.inputSize;i++)for(let n=0;n<this.outputSize;n++)r[i]+=e[n]*this.weights[n*this.inputSize+i];return r}update(t){for(let e=0;e<this.weights.length;e++)this.weights[e]-=t*this.weightGradients[e],this.weightGradients[e]=0;for(let e=0;e<this.biases.length;e++)this.biases[e]-=t*this.biasGradients[e],this.biasGradients[e]=0}getParameters(){return{weights:Array.from(this.weights),biases:Array.from(this.biases)}}setParameters(t){this.weights=new Float32Array(t.weights),this.biases=new Float32Array(t.biases),this.weightGradients=new Float32Array(this.weights.length),this.biasGradients=new Float32Array(this.biases.length)}},J=class c{layers=[];learningRate;constructor(t){this.learningRate=t.learningRate||.001;for(let e=0;e<t.layerSizes.length-1;e++){let r=new Ka({inputSize:t.layerSizes[e],outputSize:t.layerSizes[e+1],activation:t.activations[e]||new Q});this.layers.push(r)}}forward(t){let e=t instanceof Float32Array?t:new Float32Array(t);for(let r of this.layers)e=r.forward(e);return e}backward(t){let e=t;for(let r=this.layers.length-1;r>=0;r--)e=this.layers[r].backward(e)}train(t,e,r){let i=this.forward(t),n=e instanceof Float32Array?e:new Float32Array(e),s=r.forward(i,n),a=r.backward(i,n);this.backward(a);for(let o of this.layers)o.update(this.learningRate);return s}trainBatch(t,e,r){let i=0;for(let n of this.layers)n.weightGradients.fill(0),n.biasGradients.fill(0);for(let n=0;n<t.length;n++){let s=t[n]instanceof Float32Array?t[n]:new Float32Array(t[n]),a=e[n]instanceof Float32Array?e[n]:new Float32Array(e[n]),o=this.forward(s),l=r.forward(o,a);i+=l;let u=r.backward(o,a);this.backward(u)}for(let n of this.layers){for(let s=0;s<n.weightGradients.length;s++)n.weightGradients[s]/=t.length;for(let s=0;s<n.biasGradients.length;s++)n.biasGradients[s]/=t.length;n.update(this.learningRate)}return i/t.length}getParameters(){return{layers:this.layers.map(t=>t.getParameters())}}setParameters(t){for(let e=0;e<this.layers.length&&e<t.layers.length;e++)this.layers[e].setParameters(t.layers[e])}clone(){let t=new c({layerSizes:[this.layers[0].inputSize,...this.layers.map(e=>e.outputSize)],activations:this.layers.map(e=>e.activation),learningRate:this.learningRate});return t.setParameters(this.getParameters()),t}softUpdate(t,e){for(let r=0;r<this.layers.length;r++){let i=this.layers[r],n=t.layers[r];for(let s=0;s<i.weights.length;s++)i.weights[s]=e*n.weights[s]+(1-e)*i.weights[s];for(let s=0;s<i.biases.length;s++)i.biases[s]=e*n.biases[s]+(1-e)*i.biases[s]}}};ge();var At=class{buffer=[];maxSize;priorities=null;usePrioritized;alpha=.6;beta=.4;betaIncrement=.001;epsilon=1e-6;constructor(t,e=!1){this.maxSize=t,this.usePrioritized=e,e&&(this.priorities=new Float32Array(t),this.priorities.fill(1))}add(t){this.buffer.length>=this.maxSize&&(this.buffer.shift(),this.priorities&&(this.priorities.set(this.priorities.slice(1)),this.priorities[this.maxSize-1]=1)),this.buffer.push(t)}addBatch(t){for(let e of t)this.add(e)}sample(t){if(this.buffer.length===0)return[];if(this.usePrioritized&&this.priorities)return this.samplePrioritized(t);let e=[],r=new Set;for(;r.size<Math.min(t,this.buffer.length);)r.add(Se(0,this.buffer.length));for(let i of r)e.push(this.buffer[i]);return e}samplePrioritized(t){let e=this.getPriorities(),r=[],i=[];for(let n=0;n<Math.min(t,this.buffer.length);n++){let s=z()*e.reduce((o,l)=>o+l,0),a=0;for(let o=0;o<e.length;o++)if(a+=e[o],s<=a){r.push(o);break}}for(let n of r)n<this.buffer.length&&i.push(this.buffer[n]);return this.beta=Math.min(1,this.beta+this.betaIncrement),i}getPriorities(){if(!this.priorities)return[];let t=[],e=this.priorities.reduce((r,i)=>r+Math.pow(i,this.alpha),0);for(let r=0;r<this.buffer.length;r++)t.push(Math.pow(this.priorities[r],this.alpha)/e);return t}updatePriorities(t,e){if(!(!this.priorities||!this.usePrioritized))for(let r=0;r<t.length;r++){let i=t[r],n=e[r];i<this.priorities.length&&(this.priorities[i]=Math.abs(n)+this.epsilon)}}getImportanceWeights(t){if(!this.usePrioritized||!this.priorities)return new Array(t.length).fill(1);let e=[],r=this.getPriorities(),i=this.getMaxImportanceWeight();for(let n of t)if(n<r.length&&r[n]>0){let s=Math.pow(this.buffer.length*r[n],-this.beta);e.push(s/i)}else e.push(1);return e}getMaxImportanceWeight(){if(!this.usePrioritized||!this.priorities)return 1;let t=this.getPriorities(),e=0;for(let r of t)if(r>0){let i=Math.pow(this.buffer.length*r,-this.beta);e=Math.max(e,i)}return e}size(){return this.buffer.length}isReady(t){return this.buffer.length>=t}clear(){this.buffer=[],this.priorities&&this.priorities.fill(1)}getAll(){return[...this.buffer]}getStats(){return{size:this.buffer.length,maxSize:this.maxSize,utilization:this.buffer.length/this.maxSize,usePrioritized:this.usePrioritized}}};var JC={stateSize:10,actionSize:4,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0,maxGradNorm:1},Ja=class extends ve{qNetwork;targetNetwork;replayBufferClass;qConfig;updateCount=0;actions=[];constructor(t={},e=Bp){super("q-learning","value-based",{},e),this.qConfig={...JC,...t},this.qNetwork=new J({layerSizes:[this.qConfig.stateSize,...this.qConfig.hiddenLayers,this.qConfig.actionSize],activations:Array(this.qConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass=new At(this.config.replayBufferSize,!1),this.initializeActions()}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.targetNetwork.forward(e),i=this.argmax(r),n=this.actions[i],s=r[i],a=this.calculateConfidence(r);return{action:n,confidence:a,value:s,reasoning:this.generateReasoning(t,n,s,a)}}async trainCore(t){for(let i of t)this.replayBufferClass.add(i);if(!this.replayBufferClass.isReady(this.qConfig.minReplaySize))return this.getStats();let e=this.replayBufferClass.sample(this.config.batchSize);if(e.length===0)return this.getStats();let r=0;for(let i of e){let n=this.prepareState(i.state),s=this.prepareState(i.nextState),a,o=this.qNetwork.forward(n),l=this.actionToIndex(i.action);if(this.qConfig.doubleDQN&&!i.done){let m=this.qNetwork.forward(s),p=this.argmax(m),v=this.targetNetwork.forward(s)[p];a=i.reward+this.config.discountFactor*v}else{let m=this.targetNetwork.forward(s),p=Math.max(...m);a=i.reward+this.config.discountFactor*p*(i.done?0:1)}let u=new Float32Array(o.length);for(let m=0;m<u.length;m++)u[m]=m===l?a:o[m];let d=this.qNetwork.train(n,u,new Fe);r+=Math.abs(d)}return this.updateCount++,this.updateCount%this.qConfig.targetUpdateFreq===0&&this.updateTargetNetwork(),{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/e.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural Q-Learning (DQN) for Coverage Path Optimization",capabilities:["Deep Q-Network for function approximation","Experience replay for stable learning","Target network for consistent targets","Double DQN for reduced overestimation","Coverage-aware test prioritization"],hyperparameters:{stateSize:this.qConfig.stateSize,actionSize:this.qConfig.actionSize,hiddenLayers:this.qConfig.hiddenLayers.join(","),targetUpdateFreq:this.qConfig.targetUpdateFreq,doubleDQN:String(this.qConfig.doubleDQN)},stats:this.stats}}updateTargetNetwork(){this.targetNetwork=this.qNetwork.clone()}prepareState(t){let e=t.features.slice(0,this.qConfig.stateSize);for(;e.length<this.qConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]=e[i]/r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"generate-unit",value:"standard"},{type:"generate-integration",value:"standard"},{type:"prioritize",value:"high"},{type:"skip",value:0}],this.qConfig.actionSize=this.actions.length,this.qNetwork=new J({layerSizes:[this.qConfig.stateSize,...this.qConfig.hiddenLayers,this.qConfig.actionSize],activations:Array(this.qConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone()}actionToIndex(t){let e=this.actionToKey(t);for(let r=0;r<this.actions.length;r++)if(this.actionToKey(this.actions[r])===e)return r;return 0}indexToAction(t){return this.actions[Math.min(t,this.actions.length-1)]}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}actionToKey(t){return`${t.type}:${JSON.stringify(t.value)}`}calculateConfidence(t){let e=Math.max(...t),r=Math.min(...t);if(e===r)return .5;let i=e-r;return Math.min(1,.3+i*2)}generateReasoning(t,e,r,i){return this.episodeCount<10?`Neural Q-Learning exploration phase (episode ${this.episodeCount}): ${e.type} action`:i>.8?`High-confidence Neural Q-Learning decision (${i.toFixed(2)}): ${e.type} with Q-value ${r.toFixed(3)} based on ${this.updateCount} network updates`:r>.5?`Positive Q-value (${r.toFixed(3)}) suggests ${e.type} is effective for current coverage state`:`Exploratory Neural Q-Learning action: ${e.type} with confidence ${i.toFixed(2)}`}async exportCustomData(){return{qNetwork:this.qNetwork.getParameters(),targetNetwork:this.targetNetwork.getParameters(),qConfig:this.qConfig,updateCount:this.updateCount,replayBufferSize:this.replayBufferClass.size()}}async importCustomData(t){t.qNetwork&&this.qNetwork.setParameters(t.qNetwork),t.targetNetwork&&this.targetNetwork.setParameters(t.targetNetwork),t.qConfig&&(this.qConfig={...this.qConfig,...t.qConfig}),typeof t.updateCount=="number"&&(this.updateCount=t.updateCount),this.initialized=!0}async resetAlgorithm(){this.qNetwork=new J({layerSizes:[this.qConfig.stateSize,...this.qConfig.hiddenLayers,this.qConfig.actionSize],activations:Array(this.qConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass.clear(),this.updateCount=0}};var YC={maxConcurrentWorkflows:5,defaultTimeout:6e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},at=x.create("coverage-analysis"),qn=class extends ie{constructor(e,r,i={},n){let s={...YC,...i};super(e,"coverage-analysis",s,{verifyFindingTypes:["coverage-gap","risk-zone","quality-regression"],...s.consensusConfig});this.memory=r;this.coverageAnalyzer=new Xt({memory:r,llmRouter:n}),this.gapDetector=new di({memory:r,llmRouter:n}),this.riskScorer=new mi(r),this.qLearning=new Ja(this.qlConfig,qp)}memory;coverageAnalyzer;gapDetector;riskScorer;ghostAnalyzer=null;qLearning;qlConfig={stateSize:12,actionSize:4,hiddenLayers:[128,64],targetUpdateFreq:50,minReplaySize:50,doubleDQN:!0};async onInitialize(){}async onDispose(){}subscribeToEvents(){}async getQLRecommendations(e,r=10){try{let i=[];for(let a of e.slice(0,r)){let o=await this.predictQL(a),l=this.actionToTestType(o.action),u=this.estimateCoverageGain(a,o.action),d=this.estimateTestDuration(a,l);i.push({filePath:a.file,testType:l,priority:o.value,estimatedCoverageGain:u,estimatedDuration:d,action:o.action,confidence:o.confidence})}i.sort((a,o)=>o.priority-a.priority);let n=i.reduce((a,o)=>a+o.estimatedCoverageGain,0),s=i.reduce((a,o)=>a+o.estimatedDuration,0);return f({tests:i,totalEstimatedCoverageGain:n,totalEstimatedDuration:s,reasoning:`Q-Learning prioritized ${i.length} tests based on coverage optimization potential`})}catch(i){return g(y(i))}}async predictQL(e){try{let r=this.gapToQLState(e),i=await this.qLearning.predict(r),n=this.estimateCoverageGain(e,i.action),s=this.actionToTestCount(i.action);return{action:i.action,confidence:i.confidence,value:i.value||0,reasoning:i.reasoning||"",estimatedCoverageGain:n,estimatedTestCount:s}}catch(r){return{action:{type:"generate-unit",value:"standard"},confidence:.3,value:0,reasoning:`Fallback prediction due to error: ${r.message}`,estimatedCoverageGain:.1,estimatedTestCount:1}}}async trainQL(e){try{await this.qLearning.trainBatch([e]);let r=this.qLearning.getStats();r.episode%10===0&&await this.memory.set("coverage:ql:model:latest",{stats:r,exportedAt:new Date().toISOString()})}catch(r){at.error("Failed to train Q-Learning model",r instanceof Error?r:void 0)}}gapToQLState(e){let r=[e.riskScore/10,Math.min(1,e.lines.length/50),Math.min(1,e.branches.length/10),this.severityToNumber(e.severity)/4,this.complexityFromPath(e.file),this.changeFrequencyFromPath(e.file),this.businessCriticalityFromPath(e.file),e.lines.length/Math.max(1,e.branches.length),this.calculateCoveragePotential(e),this.calculateFileComplexityScore(e),this.calculateTestComplexity(e),this.calculateExecutionCost(e)];return{id:e.id,features:r,metadata:{filePath:e.file,lines:e.lines,branches:e.branches,riskScore:e.riskScore,severity:e.severity},timestamp:new Date}}estimateCoverageGain(e,r){let i=(e.lines.length+e.branches.length*2)/1e3;switch(r.type){case"generate-unit":return i*.3;case"generate-integration":return i*.5;case"prioritize":return i*.7;case"skip":return 0;default:return i*.2}}estimateTestDuration(e,r){let i=e.lines.length*.5;switch(r){case"unit":return i;case"integration":return i*2;case"e2e":return i*5;default:return i}}actionToTestType(e){switch(e.type){case"generate-unit":return"unit";case"generate-integration":return"integration";case"prioritize":return"integration";default:return"unit"}}actionToTestCount(e){switch(e.type){case"generate-unit":return 3;case"generate-integration":return 2;case"prioritize":return 5;case"skip":return 0;default:return 1}}calculateCoveragePotential(e){let r=Math.min(1,e.lines.length/50),i=Math.min(1,e.branches.length/10),n=e.riskScore/10;return(r+i+n)/3}calculateFileComplexityScore(e){let i=e.file.split("/").length,n=/service|controller|provider|manager/i.test(e.file);return Math.min(1,(i+(n?2:0))/10)}calculateTestComplexity(e){let r=e.branches.length*.6,i=e.lines.length*.1;return Math.min(1,(r+i)/20)}calculateExecutionCost(e){let r=Math.min(1,e.lines.length/100),i=e.riskScore/10;return(r+i)/2}complexityFromPath(e){return["service","controller","provider","manager","handler"].some(n=>e.toLowerCase().includes(n))?.7:.3}changeFrequencyFromPath(e){return["src","lib","services","controllers"].some(n=>e.includes(n))?.6:.2}businessCriticalityFromPath(e){return["auth","payment","user","core","api"].some(n=>e.toLowerCase().includes(n))?.8:.4}isReady(){return this.initialized}async analyze(e){try{if(this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&at.warn("Topology degraded, using conservative analysis mode"),this.minCutMixin.shouldPauseOperations())return g(new Error("Coverage analysis paused: topology is in critical state"));let r=await this.coverageAnalyzer.analyze(e);return r.success&&r.value.measured!==!1&&await this.publishCoverageReport(r.value),r}catch(r){return g(y(r))}}async detectGaps(e){try{if(this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&at.warn("Topology degraded, using conservative gap detection"),this.minCutMixin.shouldPauseOperations())return g(new Error("Gap detection paused: topology is in critical state"));let r=await this.gapDetector.detectGaps(e);if(r.success){let i=[];for(let n of r.value.gaps){if(this.config.enableConsensus&&(n.severity==="critical"||n.severity==="high")){let s=Math.min(.95,n.riskScore/10+.3);if(!await this.verifyCoverageGap(n,s)){at.info(`Coverage gap in '${n.file}' not verified, skipping publication`);continue}}i.push(n)}return Qa(e)&&await this.publishGapEvents(i),f({...r.value,gaps:i})}return r}catch(r){return g(y(r))}}async calculateRisk(e){try{if(this.minCutMixin.shouldPauseOperations())return g(new Error("Risk calculation paused: topology is in critical state"));let r=await this.riskScorer.calculateRisk(e);if(r.success){if(this.config.enableConsensus&&(r.value.riskLevel==="critical"||r.value.riskLevel==="high")&&!await this.verifyRiskZone({file:r.value.file,riskScore:r.value.overallRisk,factors:r.value.factors.map(n=>({name:n.name,weight:n.contribution}))},Math.min(.95,r.value.overallRisk/10+.5)))return at.warn(`Risk zone '${r.value.file}' not verified, downgrading severity`),f({...r.value,riskLevel:r.value.riskLevel==="critical"?"high":"medium"});r.value.riskLevel==="critical"&&await this.publishRiskZoneEvent(r.value)}return r}catch(r){return g(y(r))}}async getTrend(e){try{let{timeRange:r,granularity:i}=e,n=await this.memory.search("coverage:history:*",100);if(n.length===0)return f({dataPoints:[],trend:"stable",forecast:0});let s=[];for(let u of n){let d=parseInt(u.split(":").pop()||"0",10),m=new Date(d);if(m>=r.start&&m<=r.end){let p=await this.memory.get(u);p&&p.measured===!0&&Number.isFinite(p.line)&&s.push({date:m,coverage:p})}}s.sort((u,d)=>u.date.getTime()-d.date.getTime());let a=this.aggregateByGranularity(s,i),o=this.analyzeCoverageTrend(a),l=this.forecastCoverage(a);return f({dataPoints:a,trend:o,forecast:l})}catch(r){return g(y(r))}}async findSimilar(e){try{let{pattern:r,k:i}=e,n=Date.now(),s=this.createGapEmbedding(r),a=await this.memory.vectorSearch(s,i),o=[];for(let u of a){let d=u.metadata;d&&o.push({gap:{id:u.key,file:d.file||"unknown",lines:[],branches:[],riskScore:d.riskScore||0,severity:d.severity||"low",recommendation:"Similar pattern found in codebase"},similarity:u.score})}let l=Date.now()-n;return f({patterns:o,searchTime:l})}catch(r){return g(y(r))}}async analyzeGhostCoverage(e,r){try{if(!this.ghostAnalyzer){let d={hnswIndex:Qi(this.memory),embedder:Vn()};this.ghostAnalyzer=new Bn(d),await this.ghostAnalyzer.initialize()}let i={files:e.map(d=>({path:d,lines:{covered:0,total:100},branches:{covered:0,total:10},functions:{covered:0,total:5},statements:{covered:0,total:100},uncoveredLines:[],uncoveredBranches:[]})),summary:{line:0,branch:0,function:0,statement:0,files:e.length}},n={name:r,sourcePatterns:e},s=await this.ghostAnalyzer.computePhantomSurface(i,n);if(!s.success)return g(s.error);let a=s.value,o=await this.ghostAnalyzer.detectPhantomGaps(a),u={gaps:(o.success?o.value:[]).map(d=>({id:d.id,category:d.category,description:d.description,confidence:d.confidence,severity:d.severity,suggestedTest:d.suggestedLines.length>0?`Add test covering lines ${d.suggestedLines.join(", ")} in ${d.file}`:`Add ${d.category} test for ${d.file}`})),totalGhostScore:a.phantomRatio,coverageCompleteness:1-a.phantomRatio,computedAt:new Date(a.computedAt)};return f(u)}catch(i){return g(y(i))}}async publishCoverageReport(e){let r={reportId:crypto.randomUUID(),line:e.summary.line,branch:e.collected&&!e.collected.branch?null:e.summary.branch,function:e.collected&&!e.collected.function?null:e.summary.function,statement:e.collected&&!e.collected.statement?null:e.summary.statement,files:e.summary.files,measured:!0,...e.runStatus?{runStatus:e.runStatus}:{}},i=N(Ts.CoverageReportCreated,"coverage-analysis",r);await this.eventBus.publish(i)}async publishGapEvents(e){let r=e.filter(i=>i.severity==="critical"||i.severity==="high");for(let i of r){let n={gapId:i.id,file:i.file,uncoveredLines:i.lines,uncoveredBranches:i.branches,riskScore:i.riskScore,measured:!0,coverageMethod:"instrumented-report"},s=N(Ts.CoverageGapDetected,"coverage-analysis",n);await this.eventBus.publish(s)}}async publishRiskZoneEvent(e){let r=N(Ts.RiskZoneIdentified,"coverage-analysis",{file:e.file,overallRisk:e.overallRisk,riskLevel:e.riskLevel,topFactors:e.factors.slice(0,3).map(i=>i.name),recommendations:e.recommendations});await this.eventBus.publish(r)}aggregateByGranularity(e,r){if(e.length===0)return[];let i=new Map;for(let s of e){let a=this.getBucketKey(s.date,r),o=i.get(a)||[];o.push(s),i.set(a,o)}let n=[];for(let[,s]of i)if(s.length>0){let a={line:s.reduce((o,l)=>o+l.coverage.line,0)/s.length,branch:s.reduce((o,l)=>o+l.coverage.branch,0)/s.length,function:s.reduce((o,l)=>o+l.coverage.function,0)/s.length,statement:s.reduce((o,l)=>o+l.coverage.statement,0)/s.length,files:Math.round(s.reduce((o,l)=>o+l.coverage.files,0)/s.length)};n.push({date:s[0].date,coverage:a})}return n.sort((s,a)=>s.date.getTime()-a.date.getTime())}getBucketKey(e,r){let i=e.getFullYear(),n=e.getMonth(),s=e.getDate();switch(r){case"daily":return`${i}-${n}-${s}`;case"weekly":{let a=Math.floor(s/7);return`${i}-${n}-W${a}`}case"monthly":return`${i}-${n}`}}analyzeCoverageTrend(e){if(e.length<2)return"stable";let r=e.map(u=>{let d=u.coverage;return(d.line+d.branch+d.function+d.statement)/4}),i=r.length,n=0,s=0,a=0,o=0;for(let u=0;u<i;u++)n+=u,s+=r[u],a+=u*r[u],o+=u*u;let l=(i*a-n*s)/(i*o-n*n);return l>.5?"improving":l<-.5?"declining":"stable"}forecastCoverage(e){if(e.length===0)return 0;let r=e.map(a=>{let o=a.coverage;return(o.line+o.branch+o.function+o.statement)/4});if(r.length===1)return r[0];let i=.3,n=r[0];for(let a=1;a<r.length;a++)n=i*r[a]+(1-i)*n;let s=this.analyzeCoverageTrend(e);return s==="improving"?n=Math.min(100,n+2):s==="declining"&&(n=Math.max(0,n-2)),n}createGapEmbedding(e){let i=new Array(384).fill(0);i[0]=e.riskScore,i[1]=Math.min(1,e.lines.length/100),i[2]=Math.min(1,e.branches.length/20),i[3]=this.severityToNumber(e.severity)/4;let n=e.file.split("").reduce((s,a)=>s+a.charCodeAt(0),0);i[4]=n%1e3/1e3;for(let s=5;s<384;s++)i[s]=Math.sin(s*e.riskScore)*.5+.5;return i}severityToNumber(e){switch(e){case"critical":return 4;case"high":return 3;case"medium":return 2;case"low":return 1;default:return 0}}async verifyCoverageGap(e,r){let i=U({id:w(),type:"coverage-gap",confidence:r,description:`Verify coverage gap in ${e.file}: ${e.lines.length} uncovered lines, ${e.branches.length} uncovered branches`,payload:e,detectedBy:"coverage-analysis-coordinator",severity:e.severity});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(at.info(`Coverage gap in '${e.file}' verified by consensus`),!0):(at.warn(`Coverage gap in '${e.file}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyRiskZone(e,r){let i=U({id:w(),type:"risk-zone",confidence:r,description:`Verify risk zone: ${e.file} with risk score ${e.riskScore.toFixed(2)}`,payload:e,detectedBy:"coverage-analysis-coordinator",severity:e.riskScore>=.8?"critical":e.riskScore>=.5?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(at.info(`Risk zone '${e.file}' classification verified by consensus`),!0):(at.warn(`Risk zone '${e.file}' classification NOT verified`),!1)}return!0}async verifyQualityRegression(e,r){let i=U({id:w(),type:"quality-regression",confidence:r,description:`Verify quality regression: ${e.metric} dropped from ${e.previousValue.toFixed(1)}% to ${e.currentValue.toFixed(1)}% (threshold: ${e.threshold}%)`,payload:e,detectedBy:"coverage-analysis-coordinator",severity:"critical"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(at.info("Quality regression verified by consensus"),!0):(at.warn(`Quality regression NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}};var Ya=class c extends te{static VERSION="1.0.0";coordinator;_activeAnalyses=0;constructor(t,e,r){super(t,e),this.coordinator=new qn(t,e,{},r)}get name(){return"coverage-analysis"}get version(){return c.VERSION}get dependencies(){return["test-execution"]}getAPI(){return this.coordinator}getCoverageAPI(){return this.coordinator}getTaskHandlers(){return new Map([["analyze-coverage",async t=>{let e=t.coverageData;if(!e)return g(new Error("Invalid analyze-coverage payload: missing coverageData"));this._activeAnalyses++,this.updateAgentMetrics();try{let{instrumented:r,...i}=e;return await this.coordinator.analyze({coverageData:i,threshold:t.threshold,includeFileDetails:t.includeFileDetails,measured:!1})}finally{this._activeAnalyses--,this.updateAgentMetrics()}}],["detect-gaps",async t=>{let e=t.coverageData;if(!e)return g(new Error("Invalid detect-gaps payload: missing coverageData"));this._activeAnalyses++,this.updateAgentMetrics();try{return await this.coordinator.detectGaps({coverageData:e,minCoverage:t.minCoverage,prioritize:t.prioritize})}finally{this._activeAnalyses--,this.updateAgentMetrics()}}],["calculate-risk",async t=>{let e=t.file,r=t.uncoveredLines;if(!e||!r)return g(new Error("Invalid calculate-risk payload: missing file or uncoveredLines"));this._activeAnalyses++,this.updateAgentMetrics();try{return await this.coordinator.calculateRisk({file:e,uncoveredLines:r,factors:t.factors})}finally{this._activeAnalyses--,this.updateAgentMetrics()}}],["analyze-ghost-coverage",async t=>{let e=t.existingTests,r=t.codeContext;if(!e||!r)return g(new Error("Invalid analyze-ghost-coverage payload: missing existingTests or codeContext"));this._activeAnalyses++,this.updateAgentMetrics();try{return await this.coordinator.analyzeGhostCoverage(e,r)}finally{this._activeAnalyses--,this.updateAgentMetrics()}}]])}async onInitialize(){await this.coordinator.initialize(),this.updateHealth({status:"idle",lastActivity:new Date})}async onDispose(){await this.coordinator.dispose(),this.updateHealth({status:"unhealthy",agents:{total:0,active:0,idle:0,failed:0}})}subscribeToEvents(){this.eventBus.subscribe(je.TestRunCompleted,this.handleTestRunCompleted.bind(this))}async onEvent(t){t.type===je.TestRunCompleted&&await this.handleTestRunCompleted(t)}async handleTestRunCompleted(t){let e=t.payload;if(e.coverageData){this._activeAnalyses++,this.updateAgentMetrics();try{await this.coordinator.analyze({coverageData:e.coverageData,includeFileDetails:!0})}finally{this._activeAnalyses--,this.updateAgentMetrics()}}}updateAgentMetrics(){let t={status:(this._activeAnalyses>0,"healthy"),agents:{total:3,active:this._activeAnalyses>0?1:0,idle:this._activeAnalyses>0?2:3,failed:0},lastActivity:new Date,errors:[]};this.updateHealth(t)}getHealth(){return{...this._health,agents:{total:3,active:this._activeAnalyses>0?1:0,idle:this._activeAnalyses>0?2:3,failed:0},lastActivity:new Date}}};function xu(c,t,e){return new Ya(c,t,e)}_();k();k();var XC=["coverage","complexity","maintainability","duplication","testability","security"],ZC={coverage:"coverage",duplication:"duplications"};function nq(c,t){return c??t}function ze(c){return typeof c=="number"&&Number.isFinite(c)&&c>=0}function sq(c){let t=XC,e=`metrics must be a non-empty array of metric names (${t.join(", ")}).`;if(!Array.isArray(c)||c.length===0)throw new Error(e);let r=c.filter(i=>typeof i!="string"||!t.includes(i));if(r.length>0)throw new Error(`${e} Unknown: ${r.map(i=>JSON.stringify(i)).join(", ")}.`);return[...new Set(c)]}function aq(c,t){let e=c.length>0?[...new Set(c)]:Object.keys(t).filter(s=>ze(t[s])),r=e.filter(s=>ze(t[s])),i=e.filter(s=>!ze(t[s])),n=e.length===0?0:Math.round(r.length/e.length*100)/100;return{evidenceStatus:i.length===0&&r.length>0?"measured":Qc,measured:r,unmeasured:i,confidence:n}}function oq(c,t,e={}){let r=Om(e),i=[];for(let n of c){let s=ZC[n],a=s?r[s]:void 0,o=t[n];if(!a||!ze(o))continue;(a.direction==="min"?o<a.value:o>a.value)&&i.push({metric:n,value:o,threshold:a.value,direction:a.direction})}return i}function cq(c){let t=c.direction==="min"?"at least":"at most";return`${c.metric} measured at ${c.value} fails its threshold (${t} ${c.threshold}).`}var eS={strictMode:!1,enableWarnings:!0,defaultSeverities:{coverage:"high",testsPassing:"critical",criticalBugs:"critical",codeSmells:"medium",securityVulnerabilities:"critical",technicalDebt:"medium",duplications:"low"}},tS={strict:{coverage:{min:90},testsPassing:{min:100},criticalBugs:{max:0},codeSmells:{max:10},securityVulnerabilities:{max:0},technicalDebt:{max:2},duplications:{max:3}},standard:{coverage:{min:80},testsPassing:{min:95},criticalBugs:{max:0},codeSmells:{max:20},securityVulnerabilities:{max:0},technicalDebt:{max:5},duplications:{max:5}},relaxed:{coverage:{min:60},testsPassing:{min:90},criticalBugs:{max:2},codeSmells:{max:50},securityVulnerabilities:{max:1},technicalDebt:{max:10},duplications:{max:10}}},Zt=class{constructor(t,e={}){this.memory=t;this.config={...eS,...e};for(let[r,i]of Object.entries(tS))this.presets.set(r,i)}memory;config;presets=new Map;async evaluateGate(t){try{let{gateName:e,metrics:r,thresholds:i}=t;if(!r)return g(new Error("No metrics provided for gate evaluation"));let n=[],s=[];if(n.push(...this.evaluateMinThresholds(r,i)),n.push(...this.evaluateMaxThresholds(r,i)),n.length===0)return g(new Error("No thresholds configured for gate evaluation"));let a=n.filter(d=>!ze(d.value)).map(d=>d.name);for(let d of n)d.passed||s.push(d.name);let o=this.calculateOverallScore(n),l=a.length===0&&this.determineGateStatus(n),u={gateName:e,passed:l,checks:n,overallScore:o,failedChecks:s,evidenceStatus:a.length===0?"measured":"insufficient-evidence",unmeasured:a};return await this.storeEvaluationResult(u),f(u)}catch(e){return g(y(e))}}async createGatePreset(t,e){try{let r=`preset-${t}-${w().slice(0,8)}`;return this.presets.set(t,e),await this.memory.set(`quality-gate:preset:${t}`,{id:r,name:t,thresholds:e,createdAt:new Date().toISOString()},{namespace:"quality-assessment",persist:!0}),f(r)}catch(r){return g(y(r))}}async getGatePreset(t){if(this.presets.has(t))return this.presets.get(t);let e=await this.memory.get(`quality-gate:preset:${t}`);if(e)return this.presets.set(t,e.thresholds),e.thresholds}async listGatePresets(){let t=await this.memory.search("quality-gate:preset:*",100),e=new Set(Array.from(this.presets.keys()));for(let r of t){let i=r.replace("quality-gate:preset:","");e.add(i)}return Array.from(e)}evaluateMinThresholds(t,e){let r=[];return e.coverage?.min!==void 0&&r.push(this.createCheck("coverage",t.coverage,e.coverage.min,"min",this.config.defaultSeverities.coverage)),e.testsPassing?.min!==void 0&&r.push(this.createCheck("testsPassing",t.testsPassing,e.testsPassing.min,"min",this.config.defaultSeverities.testsPassing)),r}evaluateMaxThresholds(t,e){let r=[];return e.criticalBugs?.max!==void 0&&r.push(this.createCheck("criticalBugs",t.criticalBugs,e.criticalBugs.max,"max",this.config.defaultSeverities.criticalBugs)),e.codeSmells?.max!==void 0&&r.push(this.createCheck("codeSmells",t.codeSmells,e.codeSmells.max,"max",this.config.defaultSeverities.codeSmells)),e.securityVulnerabilities?.max!==void 0&&r.push(this.createCheck("securityVulnerabilities",t.securityVulnerabilities,e.securityVulnerabilities.max,"max",this.config.defaultSeverities.securityVulnerabilities)),e.technicalDebt?.max!==void 0&&r.push(this.createCheck("technicalDebt",t.technicalDebt,e.technicalDebt.max,"max",this.config.defaultSeverities.technicalDebt)),e.duplications?.max!==void 0&&r.push(this.createCheck("duplications",t.duplications,e.duplications.max,"max",this.config.defaultSeverities.duplications)),r}createCheck(t,e,r,i,n){let s=ze(e)&&(i==="min"?e>=r:e<=r);return{name:t,passed:s,value:e,threshold:r,severity:n}}calculateOverallScore(t){if(t.length===0)return 100;let e={critical:3,high:2,medium:1.5,low:1,info:.5},r=0,i=0;for(let n of t){let s=e[n.severity];r+=s,n.passed&&(i+=s)}return r>0?Math.round(i/r*100):100}determineGateStatus(t){return this.config.strictMode?t.every(e=>e.passed):t.filter(e=>e.severity==="critical"||e.severity==="high").every(e=>e.passed)}async storeEvaluationResult(t){let e=`quality-gate:evaluation:${t.gateName}:${Date.now()}`;await this.memory.set(e,{...t,evaluatedAt:new Date().toISOString()},{namespace:"quality-assessment",ttl:86400*30})}};_();ei();var rS=/(?:^|[(,=:[!&|?{;+\-*%~^]|\b(?:return|typeof|case|do|else|in|of|void|yield|await))$/,wg=c=>c.replace(/[^\n]/g," ");function iS(c){let t=c.length-1;for(;t>=0&&/\s/.test(c[t]);)t--;return rS.test(c.slice(Math.max(0,t-9),t+1))}function nS(c,t){let e=c[t],r=!1;for(let i=t+1;i<c.length;i++){let n=c[i];if(n==="\\"){i++;continue}if(n===`
2617
2617
  `&&e!=="`")return{end:i,closed:!1};if(e==="/"&&n==="[")r=!0;else if(e==="/"&&n==="]")r=!1;else if(n===e&&!(e==="/"&&r))return{end:i+1,closed:!0}}return{end:c.length,closed:!1}}function sS(c){let t="",e=0;for(;e<c.length;){let r=c[e],i=c[e+1];if(r==="/"&&(i==="/"||i==="*")){let n=i==="/"?c.indexOf(`
2618
2618
  `,e):c.indexOf("*/",e+2),s=n<0?c.length:i==="/"?n:n+2;t+=wg(c.slice(e,s)),e=s}else if(r==='"'||r==="'"||r==="`"||r==="/"&&iS(t)){let{end:n,closed:s}=nS(c,e);t+=r+wg(c.slice(e+1,s?n-1:n))+(s?c[n-1]:""),e=n}else t+=r,e++}return t}function Cg(c){let t=(n,s)=>(n.match(s)||[]).length,e=0,r=[],i=!1;for(let n of sS(c).split(`
2619
2619
  `)){let s=n.trim();for(;s.startsWith("}");)r.pop(),s=s.slice(1).trimStart();let a=r.filter(Boolean).length,o=t(s,/\belse\s+if\s*\(/g)+t(s,/\belse\b(?!\s+if\b)/g),l=t(s,/(?<!\belse\s+)\bif\s*\(/g)+t(s,/\b(?:for|while|switch|catch)\s*\(/g);e+=o+l*(1+a),/\?\s*[^:]/.test(s)&&(e+=1+a),/&&|\|\|/.test(s)&&(e+=1),i||=o+l>0||/\bdo\b/.test(s);for(let u of s.match(/[{}]/g)||[])u==="{"?(r.push(i),i=!1):r.pop();s.endsWith(";")&&(i=!1)}return e}mr();var aS=8192,oS=1024,cS=/^\/\/ Code generated .* DO NOT EDIT\.$/m,lS=/(?:^|[\s*/])@generated(?![\w-])/;function uS(c){let t=c.replace(/^\uFEFF/,"").replace(/^#![^\n]*\n/,"").trimStart();if(t.startsWith("/*")){let r=t.indexOf("*/");return r>=0?t.slice(0,r+2):t}let e=[];for(let r of t.split(`
@@ -2766,7 +2766,7 @@ ${t.slice(0,4e3)}
2766
2766
  // File: ${u}
2767
2767
  ${m.value.slice(0,2e3)}
2768
2768
  `)}}let o=this.calculateModelConfidence(n),l=null;if(this.isLLMPredictionAvailable()&&a.length>0){let u=await this.getHistoricalDefectPatterns(e);if(l=await this.analyzeDefectRiskWithLLM(a,n,u),l){for(let d of n)d.recommendations=this.mergeRecommendationsWithLLM(d.recommendations,l);l.confidenceLevel>.7&&(o=Math.min(1,o*1.1))}}return await this.storePrediction(n),this.modelMetrics.totalPredictions+=n.length,this.modelMetrics.lastUpdated=new Date,f({predictions:n,modelConfidence:o,factors:Array.from(s),llmAnalysis:l??void 0})}catch(e){return g(y(e))}}async getHistoricalDefectPatterns(t){let e=[];for(let i of t.slice(0,5)){let n=await this.memory.get(`${this.config.modelNamespace}:defect-patterns:${i}`);n?.patterns&&e.push(...n.patterns)}let r=await this.memory.get(`${this.config.modelNamespace}:common-defect-patterns`);return r&&e.push(...r),[...new Set(e)].slice(0,10)}async recordConfirmedDefectPattern(t,e){let r=`${this.config.modelNamespace}:defect-patterns:${t}`,i=await this.memory.get(r),n=[...new Set([...i?.patterns??[],e])].slice(-20);await this.memory.set(r,{patterns:n},{namespace:"defect-intelligence",persist:!0});let s=`${this.config.modelNamespace}:common-defect-patterns`,a=await this.memory.get(s)??[],o=[...new Set([...a,e])].slice(-50);await this.memory.set(s,o,{namespace:"defect-intelligence",persist:!0})}async analyzeRegressionRisk(t){try{let{changeset:e,baseline:r,depth:i="shallow"}=t;if(e.length===0)return g(new Error("No files in changeset"));let n=[],s=0;for(let d of e){let m=await this.analyzeFileImpact(d,i);n.push(...m.areas),s+=m.risk}if(r&&this.config.enableHistoricalAnalysis){let d=await this.getBaselineRisk(r);s=(s+d)/2}let a=Math.min(1,s/e.length),o=this.riskToSeverity(a),l=this.generateTestRecommendations(n);return f({overallRisk:a,riskLevel:o,impactedAreas:n,recommendedTests:l,confidence:i==="deep"?.85:.7})}catch(e){return g(y(e))}}async updateModel(t){try{let e=`${this.config.modelNamespace}:feedback:${t.predictionId}`;return await this.memory.set(e,t,{namespace:"defect-intelligence",persist:!0}),await this.recalculateMetrics(t),t.actualDefect&&t.defectType&&await this.recordConfirmedDefectPattern(t.file,t.defectType),f(void 0)}catch(e){return g(y(e))}}async getModelMetrics(){let t=await this.memory.get(`${this.config.modelNamespace}:metrics`);return t&&(this.modelMetrics={...t,lastUpdated:new Date(t.lastUpdated)}),{...this.modelMetrics}}async predictForFile(t,e,r){let{metrics:i,gitTimedOut:n}=await this.extractFileMetrics(t),s=[],a=0;for(let u of e){let m=(i[u.name]??0)*u.weight;a+=m,s.push({name:u.name,contribution:Math.round(m*100)/100})}a=Math.max(0,Math.min(1,a));let o=this.probabilityToRisk(a,r),l=this.generateRecommendations(s,a);return n&&l.unshift(nh),{file:t,probability:a,riskLevel:o,factors:s.filter(u=>u.contribution>.05),recommendations:l,...n?{warnings:[nh]}:{}}}async extractFileMetrics(t){let e=await this.memory.get(`${this.config.modelNamespace}:file-metrics:${t}`);if(e)return{metrics:e,gitTimedOut:!1};let r=async()=>({codeComplexity:await this.calculateComplexity(t),changeFrequency:await this.getChangeFrequency(t),developerExperience:await this.getDeveloperExperience(t),testCoverage:await this.getTestCoverage(t),codeAge:await this.getCodeAge(t),bugHistory:await this.getBugHistory(t)}),i=this.gitAnalyzer.withFileDeadline?await this.gitAnalyzer.withFileDeadline(t,r):await r(),n=this.gitAnalyzer.consumeTimeout?.(t)===!0;return n||await this.memory.set(`${this.config.modelNamespace}:file-metrics:${t}`,i,{namespace:"defect-intelligence",ttl:3600}),{metrics:i,gitTimedOut:n}}async calculateComplexity(t){let e=t.split(".").pop()?.toLowerCase();if(e&&["ts","tsx","js","jsx"].includes(e)){let r=await this.fileReader.readFile(t);if(r.success)try{let i=t.split("/").pop()||t,n=this.tsParser.parseFile(i,r.value),s=this.tsParser.extractFunctions(n),a=this.tsParser.extractClasses(n),o=r.value.split(`
2769
- `).length,l=s.length,u=a.length,d=a.reduce((j,$)=>j+$.methods.length,0),m=s.filter(j=>j.isAsync).length,p=r.value,h=(p.match(/\bif\s*\(/g)||[]).length,v=(p.match(/\b(for|while|do)\s*[{(]/g)||[]).length,b=(p.match(/\bswitch\s*\(/g)||[]).length,C=(p.match(/\bcatch\s*\(/g)||[]).length,S=(p.match(/\?[^?:]+:/g)||[]).length,R=h+v*2+b*2+C+S,E=Math.min(1,o/500),T=Math.min(1,(l+d)/30),I=Math.min(1,R/50),O=m>0?.1:0,q=E*.2+T*.25+I*.4+O+(u>3?.05:0);return Math.max(0,Math.min(1,q))}catch(i){Vu.debug(`AST parse failed: ${i instanceof Error?i.message:i}`)}}return this.estimateComplexityFromPath(t)}estimateComplexityFromPath(t){let e=t.split("/"),r=e[e.length-1],i=.3;return(t.includes("controller")||t.includes("service"))&&(i+=.2),(t.includes("coordinator")||t.includes("orchestrator"))&&(i+=.15),(t.includes("utils")||t.includes("helper"))&&(i-=.1),(t.includes("types")||t.includes("interfaces"))&&(i-=.15),r.length>30&&(i+=.1),Math.max(0,Math.min(1,i))}async getChangeFrequency(t){let e=await this.gitAnalyzer.getChangeFrequency(t);if(e!==.4)return await this.memory.set(`${this.config.modelNamespace}:history:${t}`,{changes:Math.round(e*30)},{ttl:3600}),e;let r=`${this.config.modelNamespace}:history:${t}`,i=await this.memory.get(r);return i?Math.min(1,i.changes/50):.4}async getDeveloperExperience(t){let e=await this.gitAnalyzer.getDeveloperExperience(t);if(e!==.5)return await this.memory.set(`${this.config.modelNamespace}:developer-exp:${t}`,{score:e},{ttl:3600}),e;let r=`${this.config.modelNamespace}:developer-exp:${t}`,i=await this.memory.get(r);return i?i.score:.5}async getTestCoverage(t){try{for(let r of ya(t)){let i=Os(await this.memory.get(r));if(i)return 1-i.line/100}let e=rt(await this.memory.get("coverage:latest"));if(e)return 1-e.line/100}catch{}return .4}async getCodeAge(t){let e=await this.gitAnalyzer.getCodeAge(t);if(e!==.4)return e;let r=`${this.config.modelNamespace}:age:${t}`,i=await this.memory.get(r);return i?i.days<7?.7:i.days>365?.3:.4:.4}async getBugHistory(t){let e=await this.gitAnalyzer.getBugHistory(t);if(e!==.2)return await this.memory.set(`${this.config.modelNamespace}:bugs:${t}`,{count:Math.round(e*10)},{ttl:3600}),e;let r=`${this.config.modelNamespace}:bugs:${t}`,i=await this.memory.get(r);return i?Math.min(1,i.count/10):.2}probabilityToRisk(t,e){return t>=e+.3?"critical":t>=e+.15?"high":t>=e?"medium":t>=e-.2?"low":"info"}riskToSeverity(t){return t>=.8?"critical":t>=.6?"high":t>=.4?"medium":t>=.2?"low":"info"}generateRecommendations(t,e){let r=[],i=[...t].sort((n,s)=>s.contribution-n.contribution);for(let n of i.slice(0,3))switch(n.name){case"codeComplexity":n.contribution>.1&&(r.push("Consider refactoring to reduce cyclomatic complexity"),r.push("Break down large functions into smaller, testable units"));break;case"changeFrequency":n.contribution>.1&&(r.push("High churn area - add comprehensive regression tests"),r.push("Consider stabilizing the interface before further changes"));break;case"testCoverage":n.contribution>.1&&(r.push("Increase test coverage to reduce defect risk"),r.push("Add unit tests for critical paths"));break;case"bugHistory":n.contribution>.1&&(r.push("Review past bug fixes for patterns"),r.push("Add regression tests for previously fixed issues"));break;case"codeAge":n.contribution>.1&&r.push("New code requires thorough review and testing");break;case"developerExperience":n.contribution>.1&&r.push("Request code review from senior developer");break}return e>.7&&r.push("CRITICAL: Schedule immediate code review"),r}async analyzeFileImpact(t,e){let r=[],i=0,n=this.categorizeFile(t),s=(await this.extractFileMetrics(t)).metrics.codeComplexity;if(r.push({area:n,files:[t],risk:s,reason:`Modified file in ${n} area`}),i+=s,e==="deep"){let a=await this.analyzeDependencies(t);for(let o of a){let l=(await this.extractFileMetrics(o)).metrics.codeComplexity*.5;r.push({area:this.categorizeFile(o),files:[o],risk:l,reason:`Dependency of ${t}`}),i+=l}}return{areas:r,risk:i}}categorizeFile(t){return t.includes("controller")?"API Layer":t.includes("service")?"Business Logic":t.includes("repository")||t.includes("dao")?"Data Access":t.includes("model")||t.includes("entity")?"Domain Model":t.includes("util")||t.includes("helper")?"Utilities":t.includes("test")?"Tests":t.includes("config")?"Configuration":"General"}async analyzeDependencies(t){let e=`code-intelligence:dependencies:${t}`,r=await this.memory.get(e);if(r&&r.length>0)return r;let i=[];try{let n=await this.fileReader.readFile(t);if(!n.success)return[];let s=t.split("/").pop()||t,a=this.tsParser.parseFile(s,n.value),o=this.tsParser.extractImports(a);for(let l of o)if(l.module.startsWith(".")){let u=this.resolveRelativeImport(t,l.module);i.push(u)}else l.module.startsWith("node:")||i.push(l.module);i.length>0&&await this.memory.set(e,i,{namespace:"code-intelligence",ttl:3600})}catch(n){Vu.error(`Failed to analyze dependencies for ${t}`,n instanceof Error?n:void 0)}return i}resolveRelativeImport(t,e){let i=t.substring(0,t.lastIndexOf("/")).split("/"),n=e.split("/");for(let a of n)a!=="."&&(a===".."?i.pop():i.push(a));let s=i.join("/");return!s.endsWith(".ts")&&!s.endsWith(".tsx")&&!s.endsWith(".js")&&(s=s+".ts"),s}async getBaselineRisk(t){let e=`${this.config.modelNamespace}:baseline:${t}`;return(await this.memory.get(e))?.risk??.3}generateTestRecommendations(t){let e=[],r=new Set(t.map(n=>n.area));for(let n of r)switch(n){case"API Layer":e.push("Run API integration tests"),e.push("Verify endpoint response contracts");break;case"Business Logic":e.push("Run unit tests for business rules"),e.push("Execute scenario-based tests");break;case"Data Access":e.push("Run database integration tests"),e.push("Verify data integrity constraints");break;case"Domain Model":e.push("Run entity validation tests"),e.push("Check serialization/deserialization");break}return t.filter(n=>n.risk>.6).length>0&&(e.push("Run full regression test suite"),e.push("Consider exploratory testing for edge cases")),[...new Set(e)]}calculateModelConfidence(t){let e=this.modelMetrics.accuracy,r=t.map(n=>n.probability);return this.calculateVariance(r)>.2&&(e*=.9),t.length>10&&(e*=1.05),Math.min(1,Math.max(0,e))}calculateVariance(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n,0)/t.length;return t.map(i=>Math.pow(i-e,2)).reduce((i,n)=>i+n,0)/t.length}async storePrediction(t){let e=w();await this.memory.set(`${this.config.modelNamespace}:prediction:${e}`,{id:e,predictions:t,timestamp:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*7}),await jm(this.memory,this.config.modelNamespace)}async recalculateMetrics(t){let e=t.predictedProbability>=this.config.defaultThreshold,r=e===t.actualDefect,i=.01;this.modelMetrics.accuracy=this.modelMetrics.accuracy*(1-i)+(r?1:0)*i,e&&t.actualDefect?(this.modelMetrics.precision=this.modelMetrics.precision*(1-i)+1*i,this.modelMetrics.recall=this.modelMetrics.recall*(1-i)+1*i):e&&!t.actualDefect?this.modelMetrics.precision=this.modelMetrics.precision*(1-i)+0*i:!e&&t.actualDefect&&(this.modelMetrics.recall=this.modelMetrics.recall*(1-i)+0*i),this.modelMetrics.f1Score=2*this.modelMetrics.precision*this.modelMetrics.recall/(this.modelMetrics.precision+this.modelMetrics.recall||1),this.modelMetrics.lastUpdated=new Date,await this.memory.set(`${this.config.modelNamespace}:metrics`,this.modelMetrics,{namespace:"defect-intelligence",persist:!0})}};_();k();var WS={minPatternFrequency:2,maxPatterns:50,clusterThreshold:.7,embeddingDimension:vr.DIMENSIONS,patternNamespace:"defect-intelligence:patterns",enableSemanticClustering:!0,enableFlashAttention:!0},mo={"null-pointer":{indicators:["null","undefined","NullPointerException","TypeError: Cannot read"],prevention:"Use null-safe operators and defensive programming"},"race-condition":{indicators:["concurrent","async","race","timing","intermittent"],prevention:"Implement proper synchronization and use atomic operations"},"memory-leak":{indicators:["memory","leak","OutOfMemory","heap","gc"],prevention:"Ensure proper resource cleanup and avoid circular references"},"off-by-one":{indicators:["index","boundary","array","loop","range"],prevention:"Validate array bounds and use inclusive/exclusive ranges consistently"},"input-validation":{indicators:["validation","sanitize","input","injection","XSS"],prevention:"Implement strict input validation and sanitization"},"resource-exhaustion":{indicators:["timeout","resource","exhausted","limit","quota"],prevention:"Implement rate limiting and resource pooling"},"state-corruption":{indicators:["state","inconsistent","corrupt","invalid state"],prevention:"Use immutable state patterns and proper state machines"},"encoding-issue":{indicators:["encoding","charset","UTF","unicode","character"],prevention:"Use consistent encoding throughout the application"}},US=x.create("defect-intelligence/pattern-learner"),hi=class{constructor(t,e={}){this.memory=t;this.config={...WS,...e},this.embedder=e.embedder??new wt({enableFallback:!0}),this.config.enableFlashAttention&&this.initializeFlashAttention()}memory;config;patternCache=new Map;embedder;flashAttention=null;flashAttentionAvailable=!1;MAX_CACHED_PATTERNS=5e3;async initializeFlashAttention(){let{createQEFlashAttention:t}=await import("./wrappers-AVZ3GPAL.js");this.flashAttention=await t("defect-matching",this.config.flashAttentionConfig),this.flashAttentionAvailable=!0,US.info("Flash Attention initialized for defect matching")}async ensureFlashAttentionInitialized(){this.config.enableFlashAttention&&!this.flashAttention&&await this.initializeFlashAttention()}async learnPatterns(t){try{let{defects:e,includeResolutions:r=!1}=t;if(e.length===0)return g(new Error("No defects provided for learning"));let i=[],n=!1,s=await this.extractPatterns(e),a=this.mergeWithKnownPatterns(s);for(let l of a)l.frequency>=this.config.minPatternFrequency&&(i.push(l),await this.storePattern(l),n=!0);let o=this.calculateImprovementEstimate(e.length,i);return r&&await this.learnResolutions(e,i),f({patterns:i.slice(0,this.config.maxPatterns),modelUpdated:n,improvementEstimate:o})}catch(e){return g(y(e))}}async clusterDefects(t){try{let{defects:e,method:r,minClusterSize:i=2}=t;if(e.length===0)return g(new Error("No defects provided for clustering"));let n;switch(r){case"semantic":n=await this.clusterBySemantic(e,i);break;case"behavioral":n=await this.clusterByBehavior(e,i);break;case"temporal":n=await this.clusterByTemporal(e,i);break;default:return g(new Error(`Unknown clustering method: ${r}`))}let s=new Set(n.flatMap(l=>l.defects)),a=e.filter(l=>!s.has(l.id)).map(l=>l.id),o=this.calculateClusteringMetrics(n,e.length);return f({clusters:n,outliers:a,clusteringMetrics:o})}catch(e){return g(y(e))}}async findSimilarDefects(t,e=5){try{let r=await this.generateDefectEmbedding(t),i=await this.memory.vectorSearch(r,e+1),n=[];for(let s of i)if(s.score>=this.config.clusterThreshold){let a=await this.memory.get(s.key);a&&a.id!==t.id&&n.push(a)}return f(n.slice(0,e))}catch(r){return g(y(r))}}async getPatternById(t){if(this.patternCache.has(t))return this.patternCache.get(t);let e=`${this.config.patternNamespace}:${t}`,r=await this.memory.get(e);if(r)return this.cachePattern(r),r}async listPatterns(t=this.config.maxPatterns){let e=[],r=await this.memory.search(`${this.config.patternNamespace}:*`,t*2);for(let i of r){let n=await this.memory.get(i);if(n&&(e.push(n),e.length>=t))break}return e.sort((i,n)=>n.frequency-i.frequency)}getFlashAttentionStatus(){let t=0,e=null,r=null;return this.flashAttention&&(t=this.flashAttention.getMetrics().length,e=this.flashAttention.getAverageSpeedup(),r=this.flashAttention.getWorkload()),{enabled:this.config.enableFlashAttention??!1,available:this.flashAttentionAvailable,workload:r,metricsCount:t,averageSpeedup:e}}async extractPatterns(t){let e=new Map;for(let i of t){let n=`${i.title} ${i.description}`.toLowerCase();for(let[s,a]of Object.entries(mo)){let o=a.indicators.filter(l=>n.includes(l.toLowerCase()));if(o.length>0){let l=e.get(s);l?(l.defects.push(i.id),l.indicators.push(...o.filter(u=>!l.indicators.includes(u)))):e.set(s,{indicators:o,defects:[i.id]})}}if(i.tags)for(let s of i.tags){let a=`tag-${s}`,o=e.get(a);o?o.defects.push(i.id):e.set(a,{indicators:[s],defects:[i.id]})}}let r=[];for(let[i,n]of e){let s=mo[i];r.push({id:w(),name:this.formatPatternName(i),indicators:[...new Set(n.indicators)],frequency:n.defects.length,prevention:s?.prevention||`Address ${i} issues proactively`})}return r}mergeWithKnownPatterns(t){let e=[...t];for(let[r,i]of Object.entries(mo))e.some(s=>s.name.toLowerCase().includes(r.replace("-"," ")))||e.push({id:w(),name:this.formatPatternName(r),indicators:i.indicators,frequency:0,prevention:i.prevention});return e}formatPatternName(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}async storePattern(t){let e=`${this.config.patternNamespace}:${t.id}`;if(await this.memory.set(e,t,{namespace:"defect-intelligence",persist:!0}),this.config.enableSemanticClustering){let r=await this.generatePatternEmbedding(t);await this.memory.storeVector(e,r,{patternId:t.id,name:t.name})}this.cachePattern(t)}async learnResolutions(t,e){for(let r of e){let i=t.filter(n=>{let s=`${n.title} ${n.description}`.toLowerCase();return r.indicators.some(a=>s.includes(a.toLowerCase()))});i.length>0&&await this.memory.set(`${this.config.patternNamespace}:resolutions:${r.id}`,{patternId:r.id,defectIds:i.map(n=>n.id),learnedAt:new Date().toISOString()},{namespace:"defect-intelligence",persist:!0})}}calculateImprovementEstimate(t,e){if(t===0)return 0;let r=e.reduce((s,a)=>s+a.frequency,0),i=Math.min(1,r/t),n=e.length>0?e.reduce((s,a)=>s+(a.prevention?.1:0),0)/e.length:0;return i*.7+n*.3}async clusterBySemantic(t,e){let r=new Map;await this.ensureFlashAttentionInitialized();let i=[];for(let s of t){let a=await this.generateDefectEmbedding(s);i.push({defect:s,embedding:a}),await this.memory.storeVector(`${this.config.patternNamespace}:defect:${s.id}`,a,{defectId:s.id})}let n=new Set;for(let{defect:s,embedding:a}of i){if(n.has(s.id))continue;let o=[s.id];n.add(s.id);for(let l of i){if(l.defect.id===s.id||n.has(l.defect.id))continue;await this.computeSimilarity(a,l.embedding)>=this.config.clusterThreshold&&(o.push(l.defect.id),n.add(l.defect.id))}if(o.length>=e){let l=w(),u=this.findCommonFactors(t.filter(d=>o.includes(d.id)));r.set(l,{id:l,label:this.generateClusterLabel(t.filter(d=>o.includes(d.id))),defects:o,commonFactors:u,suggestedFix:this.suggestFix(u)})}}return Array.from(r.values())}async computeSimilarity(t,e){if(!this.flashAttention)throw new Error("[PatternLearnerService] Flash Attention not initialized. Call ensureFlashAttentionInitialized() first.");return this.computeFlashAttentionSimilarity(t,e)}async computeFlashAttentionSimilarity(t,e){let r=t.length,i=new Float32Array(r),n=new Float32Array(r),s=new Float32Array(r);for(let l=0;l<r;l++)i[l]=t[l],n[l]=e[l],s[l]=e[l];let a=await this.flashAttention.computeFlashAttention(i,n,s,1,r),o=0;for(let l=0;l<r;l++)o+=a[l]*t[l];return Math.max(0,Math.min(1,(o+1)/2))}async batchComputeSimilarities(t,e){if(await this.ensureFlashAttentionInitialized(),!this.flashAttention)throw new Error("[PatternLearnerService] Flash Attention not initialized. Ensure @ruvector/attention is installed as a dependency.");let r=new Float32Array(t),i=e.map(a=>new Float32Array(a)),n=await this.flashAttention.matchDefectPattern(r,i),s=new Array(e.length).fill(0);for(let a of n)a.pattern<s.length&&(s[a.pattern]=Math.max(0,Math.min(1,(a.score+1)/2)));return s}async clusterByBehavior(t,e){let r=new Map,i=new Map;for(let n of t){let s=n.tags?.sort().join("|")||n.file||"unknown",a=i.get(s)||[];a.push(n),i.set(s,a)}for(let[n,s]of i)if(s.length>=e){let a=w(),o=this.findCommonFactors(s);r.set(a,{id:a,label:`Behavioral: ${n.replace(/\|/g,", ")}`,defects:s.map(l=>l.id),commonFactors:o,suggestedFix:this.suggestFix(o)})}return Array.from(r.values())}async clusterByTemporal(t,e){let r=new Map,i=new Map;for(let n of t){let s=n.title.toLowerCase().split(/\s+/).slice(0,2).join(" "),a=i.get(s)||[];a.push(n),i.set(s,a)}for(let[n,s]of i)if(s.length>=2){let a=w(),o=this.findCommonFactors(s);r.set(a,{id:a,label:`Temporal: ${n}`,defects:s.map(l=>l.id),commonFactors:o,suggestedFix:this.suggestFix(o)})}return Array.from(r.values())}findCommonFactors(t){let e=[];if(t.every(n=>n.tags)){let n=t.map(a=>new Set(a.tags)),s=[...n[0]].filter(a=>n.every(o=>o.has(a)));e.push(...s)}if(t.every(n=>n.file)){let n=t.map(a=>a.file.split("/")),s=Math.min(...n.map(a=>a.length));for(let a=0;a<s;a++)n.every(o=>o[a]===n[0][a])&&e.push(`Path: ${n[0][a]}`)}let r=t.map(n=>new Set(n.title.toLowerCase().split(/\s+/))),i=[...r[0]].filter(n=>n.length>3&&r.every(s=>s.has(n)));return e.push(...i.map(n=>`Keyword: ${n}`)),[...new Set(e)]}generateClusterLabel(t){let r=t.map(s=>s.title.toLowerCase()).flatMap(s=>s.split(/\s+/)),i=new Map;for(let s of r)s.length>3&&i.set(s,(i.get(s)||0)+1);return[...i.entries()].sort((s,a)=>a[1]-s[1]).slice(0,2).map(([s])=>s).join(" ")||"Unnamed Cluster"}suggestFix(t){for(let e of t)for(let[r,i]of Object.entries(mo))if(e.toLowerCase().includes(r)||i.indicators.some(n=>e.toLowerCase().includes(n.toLowerCase())))return i.prevention;return"Review common factors and implement targeted fixes"}calculateClusteringMetrics(t,e){if(t.length===0||e===0)return{silhouette:0,cohesion:0};let r=t.reduce((l,u)=>l+u.defects.length,0),i=r/t.length,n=r/e,s=t.map(l=>l.defects.length),a=s.reduce((l,u)=>l+Math.pow(u-i,2),0)/s.length,o=Math.max(0,1-a/(i*i||1));return{silhouette:Math.round(o*100)/100,cohesion:Math.round(n*100)/100}}async generateDefectEmbedding(t){let e=this.formatDefectForEmbedding(t);return this.embedder.embed(e)}async generatePatternEmbedding(t){let e=this.formatPatternForEmbedding(t);return this.embedder.embed(e)}formatDefectForEmbedding(t){return[`Title: ${t.title}`,t.description?`Description: ${t.description}`:"",t.tags?.length?`Tags: ${t.tags.join(", ")}`:"",t.file?`File: ${t.file}`:""].filter(Boolean).join(`
2769
+ `).length,l=s.length,u=a.length,d=a.reduce((j,$)=>j+$.methods.length,0),m=s.filter(j=>j.isAsync).length,p=r.value,h=(p.match(/\bif\s*\(/g)||[]).length,v=(p.match(/\b(for|while|do)\s*[{(]/g)||[]).length,b=(p.match(/\bswitch\s*\(/g)||[]).length,C=(p.match(/\bcatch\s*\(/g)||[]).length,S=(p.match(/\?[^?:]+:/g)||[]).length,R=h+v*2+b*2+C+S,E=Math.min(1,o/500),T=Math.min(1,(l+d)/30),I=Math.min(1,R/50),O=m>0?.1:0,q=E*.2+T*.25+I*.4+O+(u>3?.05:0);return Math.max(0,Math.min(1,q))}catch(i){Vu.debug(`AST parse failed: ${i instanceof Error?i.message:i}`)}}return this.estimateComplexityFromPath(t)}estimateComplexityFromPath(t){let e=t.split("/"),r=e[e.length-1],i=.3;return(t.includes("controller")||t.includes("service"))&&(i+=.2),(t.includes("coordinator")||t.includes("orchestrator"))&&(i+=.15),(t.includes("utils")||t.includes("helper"))&&(i-=.1),(t.includes("types")||t.includes("interfaces"))&&(i-=.15),r.length>30&&(i+=.1),Math.max(0,Math.min(1,i))}async getChangeFrequency(t){let e=await this.gitAnalyzer.getChangeFrequency(t);if(e!==.4)return await this.memory.set(`${this.config.modelNamespace}:history:${t}`,{changes:Math.round(e*30)},{ttl:3600}),e;let r=`${this.config.modelNamespace}:history:${t}`,i=await this.memory.get(r);return i?Math.min(1,i.changes/50):.4}async getDeveloperExperience(t){let e=await this.gitAnalyzer.getDeveloperExperience(t);if(e!==.5)return await this.memory.set(`${this.config.modelNamespace}:developer-exp:${t}`,{score:e},{ttl:3600}),e;let r=`${this.config.modelNamespace}:developer-exp:${t}`,i=await this.memory.get(r);return i?i.score:.5}async getTestCoverage(t){try{for(let r of ya(t)){let i=Os(await this.memory.get(r));if(i)return 1-i.line/100}let e=rt(await this.memory.get("coverage:latest"));if(e)return 1-e.line/100}catch{}return .4}async getCodeAge(t){let e=await this.gitAnalyzer.getCodeAge(t);if(e!==.4)return e;let r=`${this.config.modelNamespace}:age:${t}`,i=await this.memory.get(r);return i?i.days<7?.7:i.days>365?.3:.4:.4}async getBugHistory(t){let e=await this.gitAnalyzer.getBugHistory(t);if(e!==.2)return await this.memory.set(`${this.config.modelNamespace}:bugs:${t}`,{count:Math.round(e*10)},{ttl:3600}),e;let r=`${this.config.modelNamespace}:bugs:${t}`,i=await this.memory.get(r);return i?Math.min(1,i.count/10):.2}probabilityToRisk(t,e){return t>=e+.3?"critical":t>=e+.15?"high":t>=e?"medium":t>=e-.2?"low":"info"}riskToSeverity(t){return t>=.8?"critical":t>=.6?"high":t>=.4?"medium":t>=.2?"low":"info"}generateRecommendations(t,e){let r=[],i=[...t].sort((n,s)=>s.contribution-n.contribution);for(let n of i.slice(0,3))switch(n.name){case"codeComplexity":n.contribution>.1&&(r.push("Consider refactoring to reduce cyclomatic complexity"),r.push("Break down large functions into smaller, testable units"));break;case"changeFrequency":n.contribution>.1&&(r.push("High churn area - add comprehensive regression tests"),r.push("Consider stabilizing the interface before further changes"));break;case"testCoverage":n.contribution>.1&&(r.push("Increase test coverage to reduce defect risk"),r.push("Add unit tests for critical paths"));break;case"bugHistory":n.contribution>.1&&(r.push("Review past bug fixes for patterns"),r.push("Add regression tests for previously fixed issues"));break;case"codeAge":n.contribution>.1&&r.push("New code requires thorough review and testing");break;case"developerExperience":n.contribution>.1&&r.push("Request code review from senior developer");break}return e>.7&&r.push("CRITICAL: Schedule immediate code review"),r}async analyzeFileImpact(t,e){let r=[],i=0,n=this.categorizeFile(t),s=(await this.extractFileMetrics(t)).metrics.codeComplexity;if(r.push({area:n,files:[t],risk:s,reason:`Modified file in ${n} area`}),i+=s,e==="deep"){let a=await this.analyzeDependencies(t);for(let o of a){let l=(await this.extractFileMetrics(o)).metrics.codeComplexity*.5;r.push({area:this.categorizeFile(o),files:[o],risk:l,reason:`Dependency of ${t}`}),i+=l}}return{areas:r,risk:i}}categorizeFile(t){return t.includes("controller")?"API Layer":t.includes("service")?"Business Logic":t.includes("repository")||t.includes("dao")?"Data Access":t.includes("model")||t.includes("entity")?"Domain Model":t.includes("util")||t.includes("helper")?"Utilities":t.includes("test")?"Tests":t.includes("config")?"Configuration":"General"}async analyzeDependencies(t){let e=`code-intelligence:dependencies:${t}`,r=await this.memory.get(e);if(r&&r.length>0)return r;let i=[];try{let n=await this.fileReader.readFile(t);if(!n.success)return[];let s=t.split("/").pop()||t,a=this.tsParser.parseFile(s,n.value),o=this.tsParser.extractImports(a);for(let l of o)if(l.module.startsWith(".")){let u=this.resolveRelativeImport(t,l.module);i.push(u)}else l.module.startsWith("node:")||i.push(l.module);i.length>0&&await this.memory.set(e,i,{namespace:"code-intelligence",ttl:3600})}catch(n){Vu.error(`Failed to analyze dependencies for ${t}`,n instanceof Error?n:void 0)}return i}resolveRelativeImport(t,e){let i=t.substring(0,t.lastIndexOf("/")).split("/"),n=e.split("/");for(let a of n)a!=="."&&(a===".."?i.pop():i.push(a));let s=i.join("/");return!s.endsWith(".ts")&&!s.endsWith(".tsx")&&!s.endsWith(".js")&&(s=s+".ts"),s}async getBaselineRisk(t){let e=`${this.config.modelNamespace}:baseline:${t}`;return(await this.memory.get(e))?.risk??.3}generateTestRecommendations(t){let e=[],r=new Set(t.map(n=>n.area));for(let n of r)switch(n){case"API Layer":e.push("Run API integration tests"),e.push("Verify endpoint response contracts");break;case"Business Logic":e.push("Run unit tests for business rules"),e.push("Execute scenario-based tests");break;case"Data Access":e.push("Run database integration tests"),e.push("Verify data integrity constraints");break;case"Domain Model":e.push("Run entity validation tests"),e.push("Check serialization/deserialization");break}return t.filter(n=>n.risk>.6).length>0&&(e.push("Run full regression test suite"),e.push("Consider exploratory testing for edge cases")),[...new Set(e)]}calculateModelConfidence(t){let e=this.modelMetrics.accuracy,r=t.map(n=>n.probability);return this.calculateVariance(r)>.2&&(e*=.9),t.length>10&&(e*=1.05),Math.min(1,Math.max(0,e))}calculateVariance(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n,0)/t.length;return t.map(i=>Math.pow(i-e,2)).reduce((i,n)=>i+n,0)/t.length}async storePrediction(t){let e=w();await this.memory.set(`${this.config.modelNamespace}:prediction:${e}`,{id:e,predictions:t,timestamp:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*7}),await jm(this.memory,this.config.modelNamespace)}async recalculateMetrics(t){let e=t.predictedProbability>=this.config.defaultThreshold,r=e===t.actualDefect,i=.01;this.modelMetrics.accuracy=this.modelMetrics.accuracy*(1-i)+(r?1:0)*i,e&&t.actualDefect?(this.modelMetrics.precision=this.modelMetrics.precision*(1-i)+1*i,this.modelMetrics.recall=this.modelMetrics.recall*(1-i)+1*i):e&&!t.actualDefect?this.modelMetrics.precision=this.modelMetrics.precision*(1-i)+0*i:!e&&t.actualDefect&&(this.modelMetrics.recall=this.modelMetrics.recall*(1-i)+0*i),this.modelMetrics.f1Score=2*this.modelMetrics.precision*this.modelMetrics.recall/(this.modelMetrics.precision+this.modelMetrics.recall||1),this.modelMetrics.lastUpdated=new Date,await this.memory.set(`${this.config.modelNamespace}:metrics`,this.modelMetrics,{namespace:"defect-intelligence",persist:!0})}};_();k();var WS={minPatternFrequency:2,maxPatterns:50,clusterThreshold:.7,embeddingDimension:vr.DIMENSIONS,patternNamespace:"defect-intelligence:patterns",enableSemanticClustering:!0,enableFlashAttention:!0},mo={"null-pointer":{indicators:["null","undefined","NullPointerException","TypeError: Cannot read"],prevention:"Use null-safe operators and defensive programming"},"race-condition":{indicators:["concurrent","async","race","timing","intermittent"],prevention:"Implement proper synchronization and use atomic operations"},"memory-leak":{indicators:["memory","leak","OutOfMemory","heap","gc"],prevention:"Ensure proper resource cleanup and avoid circular references"},"off-by-one":{indicators:["index","boundary","array","loop","range"],prevention:"Validate array bounds and use inclusive/exclusive ranges consistently"},"input-validation":{indicators:["validation","sanitize","input","injection","XSS"],prevention:"Implement strict input validation and sanitization"},"resource-exhaustion":{indicators:["timeout","resource","exhausted","limit","quota"],prevention:"Implement rate limiting and resource pooling"},"state-corruption":{indicators:["state","inconsistent","corrupt","invalid state"],prevention:"Use immutable state patterns and proper state machines"},"encoding-issue":{indicators:["encoding","charset","UTF","unicode","character"],prevention:"Use consistent encoding throughout the application"}},US=x.create("defect-intelligence/pattern-learner"),hi=class{constructor(t,e={}){this.memory=t;this.config={...WS,...e},this.embedder=e.embedder??new wt({enableFallback:!0}),this.config.enableFlashAttention&&this.initializeFlashAttention()}memory;config;patternCache=new Map;embedder;flashAttention=null;flashAttentionAvailable=!1;MAX_CACHED_PATTERNS=5e3;async initializeFlashAttention(){let{createQEFlashAttention:t}=await import("./wrappers-EHOL62TS.js");this.flashAttention=await t("defect-matching",this.config.flashAttentionConfig),this.flashAttentionAvailable=!0,US.info("Flash Attention initialized for defect matching")}async ensureFlashAttentionInitialized(){this.config.enableFlashAttention&&!this.flashAttention&&await this.initializeFlashAttention()}async learnPatterns(t){try{let{defects:e,includeResolutions:r=!1}=t;if(e.length===0)return g(new Error("No defects provided for learning"));let i=[],n=!1,s=await this.extractPatterns(e),a=this.mergeWithKnownPatterns(s);for(let l of a)l.frequency>=this.config.minPatternFrequency&&(i.push(l),await this.storePattern(l),n=!0);let o=this.calculateImprovementEstimate(e.length,i);return r&&await this.learnResolutions(e,i),f({patterns:i.slice(0,this.config.maxPatterns),modelUpdated:n,improvementEstimate:o})}catch(e){return g(y(e))}}async clusterDefects(t){try{let{defects:e,method:r,minClusterSize:i=2}=t;if(e.length===0)return g(new Error("No defects provided for clustering"));let n;switch(r){case"semantic":n=await this.clusterBySemantic(e,i);break;case"behavioral":n=await this.clusterByBehavior(e,i);break;case"temporal":n=await this.clusterByTemporal(e,i);break;default:return g(new Error(`Unknown clustering method: ${r}`))}let s=new Set(n.flatMap(l=>l.defects)),a=e.filter(l=>!s.has(l.id)).map(l=>l.id),o=this.calculateClusteringMetrics(n,e.length);return f({clusters:n,outliers:a,clusteringMetrics:o})}catch(e){return g(y(e))}}async findSimilarDefects(t,e=5){try{let r=await this.generateDefectEmbedding(t),i=await this.memory.vectorSearch(r,e+1),n=[];for(let s of i)if(s.score>=this.config.clusterThreshold){let a=await this.memory.get(s.key);a&&a.id!==t.id&&n.push(a)}return f(n.slice(0,e))}catch(r){return g(y(r))}}async getPatternById(t){if(this.patternCache.has(t))return this.patternCache.get(t);let e=`${this.config.patternNamespace}:${t}`,r=await this.memory.get(e);if(r)return this.cachePattern(r),r}async listPatterns(t=this.config.maxPatterns){let e=[],r=await this.memory.search(`${this.config.patternNamespace}:*`,t*2);for(let i of r){let n=await this.memory.get(i);if(n&&(e.push(n),e.length>=t))break}return e.sort((i,n)=>n.frequency-i.frequency)}getFlashAttentionStatus(){let t=0,e=null,r=null;return this.flashAttention&&(t=this.flashAttention.getMetrics().length,e=this.flashAttention.getAverageSpeedup(),r=this.flashAttention.getWorkload()),{enabled:this.config.enableFlashAttention??!1,available:this.flashAttentionAvailable,workload:r,metricsCount:t,averageSpeedup:e}}async extractPatterns(t){let e=new Map;for(let i of t){let n=`${i.title} ${i.description}`.toLowerCase();for(let[s,a]of Object.entries(mo)){let o=a.indicators.filter(l=>n.includes(l.toLowerCase()));if(o.length>0){let l=e.get(s);l?(l.defects.push(i.id),l.indicators.push(...o.filter(u=>!l.indicators.includes(u)))):e.set(s,{indicators:o,defects:[i.id]})}}if(i.tags)for(let s of i.tags){let a=`tag-${s}`,o=e.get(a);o?o.defects.push(i.id):e.set(a,{indicators:[s],defects:[i.id]})}}let r=[];for(let[i,n]of e){let s=mo[i];r.push({id:w(),name:this.formatPatternName(i),indicators:[...new Set(n.indicators)],frequency:n.defects.length,prevention:s?.prevention||`Address ${i} issues proactively`})}return r}mergeWithKnownPatterns(t){let e=[...t];for(let[r,i]of Object.entries(mo))e.some(s=>s.name.toLowerCase().includes(r.replace("-"," ")))||e.push({id:w(),name:this.formatPatternName(r),indicators:i.indicators,frequency:0,prevention:i.prevention});return e}formatPatternName(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}async storePattern(t){let e=`${this.config.patternNamespace}:${t.id}`;if(await this.memory.set(e,t,{namespace:"defect-intelligence",persist:!0}),this.config.enableSemanticClustering){let r=await this.generatePatternEmbedding(t);await this.memory.storeVector(e,r,{patternId:t.id,name:t.name})}this.cachePattern(t)}async learnResolutions(t,e){for(let r of e){let i=t.filter(n=>{let s=`${n.title} ${n.description}`.toLowerCase();return r.indicators.some(a=>s.includes(a.toLowerCase()))});i.length>0&&await this.memory.set(`${this.config.patternNamespace}:resolutions:${r.id}`,{patternId:r.id,defectIds:i.map(n=>n.id),learnedAt:new Date().toISOString()},{namespace:"defect-intelligence",persist:!0})}}calculateImprovementEstimate(t,e){if(t===0)return 0;let r=e.reduce((s,a)=>s+a.frequency,0),i=Math.min(1,r/t),n=e.length>0?e.reduce((s,a)=>s+(a.prevention?.1:0),0)/e.length:0;return i*.7+n*.3}async clusterBySemantic(t,e){let r=new Map;await this.ensureFlashAttentionInitialized();let i=[];for(let s of t){let a=await this.generateDefectEmbedding(s);i.push({defect:s,embedding:a}),await this.memory.storeVector(`${this.config.patternNamespace}:defect:${s.id}`,a,{defectId:s.id})}let n=new Set;for(let{defect:s,embedding:a}of i){if(n.has(s.id))continue;let o=[s.id];n.add(s.id);for(let l of i){if(l.defect.id===s.id||n.has(l.defect.id))continue;await this.computeSimilarity(a,l.embedding)>=this.config.clusterThreshold&&(o.push(l.defect.id),n.add(l.defect.id))}if(o.length>=e){let l=w(),u=this.findCommonFactors(t.filter(d=>o.includes(d.id)));r.set(l,{id:l,label:this.generateClusterLabel(t.filter(d=>o.includes(d.id))),defects:o,commonFactors:u,suggestedFix:this.suggestFix(u)})}}return Array.from(r.values())}async computeSimilarity(t,e){if(!this.flashAttention)throw new Error("[PatternLearnerService] Flash Attention not initialized. Call ensureFlashAttentionInitialized() first.");return this.computeFlashAttentionSimilarity(t,e)}async computeFlashAttentionSimilarity(t,e){let r=t.length,i=new Float32Array(r),n=new Float32Array(r),s=new Float32Array(r);for(let l=0;l<r;l++)i[l]=t[l],n[l]=e[l],s[l]=e[l];let a=await this.flashAttention.computeFlashAttention(i,n,s,1,r),o=0;for(let l=0;l<r;l++)o+=a[l]*t[l];return Math.max(0,Math.min(1,(o+1)/2))}async batchComputeSimilarities(t,e){if(await this.ensureFlashAttentionInitialized(),!this.flashAttention)throw new Error("[PatternLearnerService] Flash Attention not initialized. Ensure @ruvector/attention is installed as a dependency.");let r=new Float32Array(t),i=e.map(a=>new Float32Array(a)),n=await this.flashAttention.matchDefectPattern(r,i),s=new Array(e.length).fill(0);for(let a of n)a.pattern<s.length&&(s[a.pattern]=Math.max(0,Math.min(1,(a.score+1)/2)));return s}async clusterByBehavior(t,e){let r=new Map,i=new Map;for(let n of t){let s=n.tags?.sort().join("|")||n.file||"unknown",a=i.get(s)||[];a.push(n),i.set(s,a)}for(let[n,s]of i)if(s.length>=e){let a=w(),o=this.findCommonFactors(s);r.set(a,{id:a,label:`Behavioral: ${n.replace(/\|/g,", ")}`,defects:s.map(l=>l.id),commonFactors:o,suggestedFix:this.suggestFix(o)})}return Array.from(r.values())}async clusterByTemporal(t,e){let r=new Map,i=new Map;for(let n of t){let s=n.title.toLowerCase().split(/\s+/).slice(0,2).join(" "),a=i.get(s)||[];a.push(n),i.set(s,a)}for(let[n,s]of i)if(s.length>=2){let a=w(),o=this.findCommonFactors(s);r.set(a,{id:a,label:`Temporal: ${n}`,defects:s.map(l=>l.id),commonFactors:o,suggestedFix:this.suggestFix(o)})}return Array.from(r.values())}findCommonFactors(t){let e=[];if(t.every(n=>n.tags)){let n=t.map(a=>new Set(a.tags)),s=[...n[0]].filter(a=>n.every(o=>o.has(a)));e.push(...s)}if(t.every(n=>n.file)){let n=t.map(a=>a.file.split("/")),s=Math.min(...n.map(a=>a.length));for(let a=0;a<s;a++)n.every(o=>o[a]===n[0][a])&&e.push(`Path: ${n[0][a]}`)}let r=t.map(n=>new Set(n.title.toLowerCase().split(/\s+/))),i=[...r[0]].filter(n=>n.length>3&&r.every(s=>s.has(n)));return e.push(...i.map(n=>`Keyword: ${n}`)),[...new Set(e)]}generateClusterLabel(t){let r=t.map(s=>s.title.toLowerCase()).flatMap(s=>s.split(/\s+/)),i=new Map;for(let s of r)s.length>3&&i.set(s,(i.get(s)||0)+1);return[...i.entries()].sort((s,a)=>a[1]-s[1]).slice(0,2).map(([s])=>s).join(" ")||"Unnamed Cluster"}suggestFix(t){for(let e of t)for(let[r,i]of Object.entries(mo))if(e.toLowerCase().includes(r)||i.indicators.some(n=>e.toLowerCase().includes(n.toLowerCase())))return i.prevention;return"Review common factors and implement targeted fixes"}calculateClusteringMetrics(t,e){if(t.length===0||e===0)return{silhouette:0,cohesion:0};let r=t.reduce((l,u)=>l+u.defects.length,0),i=r/t.length,n=r/e,s=t.map(l=>l.defects.length),a=s.reduce((l,u)=>l+Math.pow(u-i,2),0)/s.length,o=Math.max(0,1-a/(i*i||1));return{silhouette:Math.round(o*100)/100,cohesion:Math.round(n*100)/100}}async generateDefectEmbedding(t){let e=this.formatDefectForEmbedding(t);return this.embedder.embed(e)}async generatePatternEmbedding(t){let e=this.formatPatternForEmbedding(t);return this.embedder.embed(e)}formatDefectForEmbedding(t){return[`Title: ${t.title}`,t.description?`Description: ${t.description}`:"",t.tags?.length?`Tags: ${t.tags.join(", ")}`:"",t.file?`File: ${t.file}`:""].filter(Boolean).join(`
2770
2770
  `)}formatPatternForEmbedding(t){return[`Pattern: ${t.name}`,`Indicators: ${t.indicators.join(", ")}`,`Prevention: ${t.prevention}`,`Frequency: ${t.frequency}`].filter(Boolean).join(`
2771
2771
  `)}cachePattern(t){if(this.patternCache.size>=this.MAX_CACHED_PATTERNS){let e=this.patternCache.keys().next().value;e&&this.patternCache.delete(e)}this.patternCache.set(t.id,t)}destroy(){this.patternCache.clear(),this.flashAttention=null,this.flashAttentionAvailable=!1}};_();k();X();Pe();var QS={maxTimelineEvents:20,maxRelatedFiles:10,minConfidenceThreshold:.3,analyzerNamespace:"defect-intelligence:root-cause",enableDeepAnalysis:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},po={"logic-error":{symptoms:["wrong result","incorrect output","unexpected behavior","calculation"],causes:["Incorrect algorithm implementation","Missing edge case handling","Wrong operator usage","Off-by-one error"],impact:"high",remediation:["Review algorithm logic step by step","Add comprehensive unit tests","Use property-based testing for edge cases"]},"null-reference":{symptoms:["null","undefined","cannot read property","NullPointerException"],causes:["Missing null check","Uninitialized variable","Race condition in initialization","API returning null unexpectedly"],impact:"high",remediation:["Add defensive null checks","Use Optional/Maybe pattern","Initialize variables at declaration"]},concurrency:{symptoms:["race","deadlock","intermittent","timing","thread"],causes:["Missing synchronization","Shared mutable state","Lock ordering issue","Async operation not awaited"],impact:"high",remediation:["Use immutable data structures","Implement proper locking strategy","Add synchronization primitives"]},"resource-management":{symptoms:["memory","leak","connection","file handle","exhausted"],causes:["Resource not properly released","Missing cleanup in error path","Connection pool misconfiguration","Circular reference preventing GC"],impact:"medium",remediation:["Use try-finally or using blocks","Implement IDisposable pattern","Configure resource pools properly"]},configuration:{symptoms:["config","environment","setting","property","parameter"],causes:["Wrong configuration value","Missing required setting","Environment mismatch","Hardcoded values"],impact:"medium",remediation:["Validate configuration at startup","Use configuration schema validation","Document all required settings"]},integration:{symptoms:["api","service","external","timeout","connection"],causes:["External service change","API contract violation","Network configuration issue","Missing retry logic"],impact:"high",remediation:["Implement circuit breaker pattern","Add contract tests","Use retry with exponential backoff"]},"data-integrity":{symptoms:["corrupt","invalid","constraint","duplicate","data"],causes:["Missing validation","Database constraint violated","Race condition in data update","Inconsistent state transitions"],impact:"high",remediation:["Add input validation at all layers","Use database transactions properly","Implement optimistic locking"]},security:{symptoms:["injection","auth","permission","access","security"],causes:["Missing input sanitization","Broken authentication","Insufficient authorization checks","Sensitive data exposure"],impact:"high",remediation:["Sanitize all user inputs","Implement proper authentication","Follow principle of least privilege"]}},KS=x.create("defect-intelligence/root-cause-analyzer"),fi=class{config;memory;llmRouter;constructor(t,e={}){this.config={...QS,...e},this.isMemoryBackend(t)?(this.memory=t,this.llmRouter=void 0):(this.memory=t.memory,this.llmRouter=t.llmRouter)}isMemoryBackend(t){return typeof t.get=="function"&&typeof t.set=="function"&&!("memory"in t)}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis===!0&&this.llmRouter!==void 0}getModelForTier(t){return ae(t)}async analyzeRootCauseWithLLM(t,e,r){if(!this.llmRouter)return null;try{let i=this.buildLLMAnalysisPrompt(t,e,r),n=this.getModelForTier(this.config.llmModelTier??2),s=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software engineer specialized in debugging and root cause analysis.
2772
2772
  Analyze the provided defect information and provide:
@@ -2867,18 +2867,18 @@ ${i}
2867
2867
  `)}generateContextRelationships(t,e,r,i){let n=[];for(let s of e)n.push({sourceId:s.id,targetId:t.id,description:s.external?"Interacts with":"Uses",type:"uses"});for(let s of r){let o=i.find(l=>this.sanitizeName(l.name)===s.id)?.relationshipDescription??this.getRelationshipLabel(s.systemType??"third_party");n.push({sourceId:t.id,targetId:s.id,description:o,type:this.getRelationshipType(s.systemType??"third_party")})}return n}generateContainerRelationships(t,e,r){let i=[],n=new Map(t.map(a=>[a.id,a])),s=new Map(t.map(a=>[a.name.toLowerCase(),a]));for(let a of r){let o=this.sanitizeName(a.from),l=this.sanitizeName(a.to),u=n.get(o)??s.get(a.from.toLowerCase()),d=n.get(l)??s.get(a.to.toLowerCase());if(u&&d){let m=this.inferContainerRelationship(u,d);i.push({sourceId:u.id,targetId:d.id,description:a.description??m??"Uses",technology:a.technology,type:"uses"})}}if(r.length===0)for(let a of t)for(let o of t){if(a.id===o.id)continue;let l=this.inferContainerRelationship(a,o);l&&i.push({sourceId:a.id,targetId:o.id,description:l,type:"uses"})}for(let a of t)for(let o of e){let l=this.getRelationshipLabel(o.systemType??"third_party");i.push({sourceId:a.id,targetId:o.id,description:l,type:this.getRelationshipType(o.systemType??"third_party")})}return i}generateComponentRelationships(t,e){let r=[],i=new Map(t.map(a=>[a.id,a])),n=new Map(t.map(a=>[a.name.toLowerCase(),a])),s=new Set;for(let a of e){let o=this.sanitizeName(a.from),l=this.sanitizeName(a.to),u=i.get(o)??n.get(a.from.toLowerCase()),d=i.get(l)??n.get(a.to.toLowerCase());if(u&&d){let m=`${u.id}-${d.id}-${a.type??"uses"}`;s.has(m)||(s.add(m),r.push({sourceId:u.id,targetId:d.id,description:a.description??this.getComponentRelationshipDescription(a.type),type:a.type??"uses"}))}}return r}async storeDiagram(t,e,r,i,n){let s=this.getStorageKey(t),a={type:e,model:r,mermaid:i,storedAt:new Date,embedding:n},o={namespace:this.namespace,persist:!0};await this.memory.set(s,a,o),n&&await this.memory.storeVector(s,n,{type:e,title:this.getDiagramTitle(a)})}getStorageKey(t){return t.startsWith(this.namespace)?t:`${this.namespace}:${t}`}sanitizeName(t){return t.replace(/[^a-zA-Z0-9_\s-]/g,"").replace(/\s+/g,"_").replace(/-+/g,"_").replace(/^_+|_+$/g,"").toLowerCase()}getDefaultPersons(){return[{id:"user",name:"User",description:"A user of the system"},{id:"developer",name:"Developer",description:"A developer maintaining the system"}]}getSystemDescription(t){return{web_application:"Web application",mobile_application:"Mobile application",api:"API service",database:"Database system",message_queue:"Message queue system",cache:"Caching system",storage:"Storage system",monitoring:"Monitoring system",authentication:"Authentication service",third_party:"Third-party service",microservice:"Microservice",monolith:"Monolithic application",library:"Library/SDK",cli:"Command-line tool"}[t]??"External system"}getContainerDescription(t,e){let r=e.toLowerCase();return r.includes("api")?"Provides application functionality via API":r.includes("frontend")?"Delivers web interface to users":r.includes("service")?"Handles business logic and processing":r.includes("worker")?"Processes background tasks":r.includes("gateway")?"Routes and manages traffic":{web_application:"Web application",mobile_application:"Mobile application",single_page_application:"Single-page application",desktop_application:"Desktop application",api_application:"API application",serverless_function:"Serverless function",microservice:"Microservice",console_application:"Console application",database:"Stores application data",file_system:"File storage",cache:"Caching layer",message_queue:"Message queue",search_index:"Search index",blob_storage:"Binary storage"}[t]??"Application component"}inferContainerTechnology(t,e){let r=e.toLowerCase();return r.includes("postgres")?"PostgreSQL":r.includes("mysql")?"MySQL":r.includes("mongo")?"MongoDB":r.includes("redis")?"Redis":r.includes("elastic")?"Elasticsearch":r.includes("rabbitmq")?"RabbitMQ":r.includes("kafka")?"Apache Kafka":r.includes("react")?"React, TypeScript":r.includes("node")||r.includes("api")?"Node.js, TypeScript":{web_application:"TypeScript, React",mobile_application:"React Native",single_page_application:"React, TypeScript",desktop_application:"Electron",api_application:"Node.js, TypeScript",serverless_function:"Node.js",microservice:"Node.js",console_application:"Node.js",database:"PostgreSQL",file_system:"S3-compatible",cache:"Redis",message_queue:"RabbitMQ",search_index:"Elasticsearch",blob_storage:"S3"}[t]??"Application"}getComponentDescription(t,e){let r=e.toLowerCase();return r.includes("controller")?"Handles HTTP requests and responses":r.includes("service")?"Implements business logic":r.includes("repository")?"Manages data persistence":r.includes("auth")?"Provides authentication and authorization":r.includes("validator")?"Validates input data":r.includes("middleware")?"Processes requests in pipeline":r.includes("util")||r.includes("helper")?"Provides utility functions":r.includes("handler")?"Handles events and messages":r.includes("adapter")?"Adapts external interfaces":r.includes("model")||r.includes("entity")?"Represents data structure":{controller:"Handles requests",service:"Business logic",repository:"Data access",middleware:"Request processing",validator:"Input validation",utility:"Utility functions",security:"Security controls",model:"Data model",handler:"Event handling",adapter:"External adapter",factory:"Object creation",observer:"Event observation",facade:"Simplified interface",gateway:"External gateway",interface:"Interface definition",module:"Module",class:"Class",function:"Function"}[t]??"Application component"}inferComponentTechnology(t){return{controller:"MVC Controller",service:"Service Component",repository:"Data Access Object",middleware:"Middleware",validator:"Validator",utility:"Utility Component",security:"Security Component",model:"Data Model",handler:"Event Handler",adapter:"External Adapter",factory:"Factory Pattern",observer:"Observer Pattern",facade:"Facade Pattern",gateway:"Gateway Pattern",interface:"Interface",module:"Module",class:"Class Component",function:"Function Component"}[t]??"Component"}getRelationshipLabel(t){return{database:"Reads from and writes to",api:"Makes API calls to",cache:"Reads from and writes to",message_queue:"Publishes to and consumes from",storage:"Stores files in",monitoring:"Sends metrics to",authentication:"Authenticates with",third_party:"Integrates with",web_application:"Uses",mobile_application:"Uses",microservice:"Calls",monolith:"Depends on",library:"Uses",cli:"Executes"}[t]??"Depends on"}getRelationshipType(t){return{database:"reads_from",api:"calls",cache:"reads_from",message_queue:"sends_to",storage:"writes_to",monitoring:"sends_to",authentication:"authenticates_with",third_party:"uses",web_application:"uses",mobile_application:"uses",microservice:"calls",monolith:"depends_on",library:"uses",cli:"uses"}[t]??"uses"}inferContainerRelationship(t,e){let r=t.name.toLowerCase(),i=e.name.toLowerCase();return r.includes("frontend")&&(i.includes("api")||i.includes("backend"))?"Makes API calls to":(r.includes("api")||r.includes("backend")||r.includes("service"))&&this.isDatabase(e)?"Reads from and writes to":r.includes("gateway")&&(i.includes("api")||i.includes("service"))?"Routes requests to":r.includes("worker")&&i.includes("queue")?"Consumes messages from":(r.includes("service")||r.includes("api"))&&i.includes("cache")?"Caches data in":null}getComponentRelationshipDescription(t){return t?{depends_on:"Depends on",uses:"Uses",calls:"Calls",inherits:"Inherits from",implements:"Implements",contains:"Contains",imports:"Imports",injects:"Injects",configures:"Configures",validates:"Validates with",handles:"Handles via",delegates:"Delegates to"}[t]??"Uses":"Uses"}isDatabase(t){if("containerType"in t&&t.containerType==="database")return!0;let e=(t.name??"").toLowerCase();return["database","db","postgres","mysql","mongo","redis","cache"].some(i=>e.includes(i))}getContextEmbeddingText(t,e,r){return[`C4 Context: ${e.name}`,e.description,`Type: ${e.systemType??"system"}`,e.technology?`Technology: ${e.technology}`:"",r.length>0?`External systems: ${r.map(n=>n.name).join(", ")}`:""].filter(Boolean).join(". ")}getContainerEmbeddingText(t,e,r){return[`C4 Container: ${t.systemName}`,`Containers: ${e.map(n=>`${n.name} (${n.containerType})`).join(", ")}`,r.length>0?`External: ${r.map(n=>n.name).join(", ")}`:""].filter(Boolean).join(". ")}getComponentEmbeddingText(t,e){return[`C4 Component: ${t.containerName}`,`Components: ${e.map(i=>`${i.name} (${i.componentType})`).join(", ")}`,t.boundaries&&t.boundaries.length>0?`Boundaries: ${t.boundaries.map(i=>i.name).join(", ")}`:""].filter(Boolean).join(". ")}getDiagramTitle(t){return"title"in t.model?t.model.title:"Unknown Diagram"}getDiagramPreview(t){switch(t.type){case"context":{let e=t.model;return`System: ${e.system.name}, External: ${e.externalSystems.length}`}case"container":{let e=t.model;return`Containers: ${e.containers.length}, External: ${e.externalSystems.length}`}case"component":{let e=t.model;return`Components: ${e.components.length}, Relations: ${e.relationships.length}`}default:return"No preview available"}}detectArchitecturePattern(t){let e=new Set(t.map(o=>o.boundary).filter(Boolean)),r=new Set(t.map(o=>o.componentType)),i=r.has("controller")&&r.has("service")&&r.has("repository"),n=e.size>=3,s=["auth","user","order","payment","notification"],a=Array.from(e).some(o=>s.some(l=>(o??"").toLowerCase().includes(l)));return i&&!n?"layered":n&&a?"feature":n?"modular":t.length<=5?"microservice":"mixed"}detectLayers(t){let e=new Set;for(let i of t){let n=i.componentType;n==="controller"&&e.add("presentation"),n==="service"&&e.add("application"),n==="repository"&&e.add("infrastructure"),n==="model"&&e.add("domain"),i.boundary&&e.add(i.boundary)}let r=["presentation","application","domain","infrastructure"];return Array.from(e).sort((i,n)=>{let s=r.indexOf(i),a=r.indexOf(n);return s===-1&&a===-1?i.localeCompare(n):s===-1?1:a===-1?-1:s-a})}analyzeCoupling(t,e){let r=new Set(t.map(d=>d.id)),i=new Map,n=new Map;for(let d of r)i.set(d,0),n.set(d,0);for(let d of e)r.has(d.sourceId)&&n.set(d.sourceId,(n.get(d.sourceId)??0)+1),r.has(d.targetId)&&i.set(d.targetId,(i.get(d.targetId)??0)+1);let s=t.length-1,a=[];for(let d of e){let m=n.get(d.sourceId)??0,p=i.get(d.targetId)??0,h=s>0?(m+p)/(2*s):0;h>.5&&a.push({from:d.sourceId,to:d.targetId,score:h})}let o=this.detectCycles(e,r),l=Array.from(n.values()).reduce((d,m)=>d+m,0),u=t.length>0&&l/(t.length*s)||0;return{averageCoupling:Math.min(1,u),highCouplingPairs:a.sort((d,m)=>m.score-d.score).slice(0,10),circularDependencies:o}}detectCycles(t,e){let r=[],i=new Map;for(let o of e)i.set(o,[]);for(let o of t)e.has(o.sourceId)&&e.has(o.targetId)&&i.get(o.sourceId)?.push(o.targetId);let n=new Set,s=new Set,a=(o,l)=>{n.add(o),s.add(o);for(let u of i.get(o)??[])if(!n.has(u))a(u,[...l,u]);else if(s.has(u)){let d=l.indexOf(u);d>=0&&r.push([...l.slice(d),u])}s.delete(o)};for(let o of e)n.has(o)||a(o,[o]);return r}generateRecommendations(t,e,r){let i=[];for(let a of r.circularDependencies)i.push({severity:a.length>3?"critical":"high",priority:"p0",category:"dependency",issue:`Circular dependency detected: ${a.join(" -> ")}`,suggestion:`Break the cycle by introducing an abstraction layer or event-based communication between ${a[0]} and ${a[a.length-2]}`,affectedElements:a});for(let a of r.highCouplingPairs)a.score>.7&&i.push({severity:"medium",priority:"p1",category:"coupling",issue:`High coupling (${(a.score*100).toFixed(0)}%) between ${a.from} and ${a.to}`,suggestion:"Consider extracting shared logic into a separate component or using dependency injection",affectedElements:[a.from,a.to]});let n=new Map;for(let a of e)n.set(a.sourceId,(n.get(a.sourceId)??0)+1);for(let[a,o]of n)if(o>5){let l=t.find(u=>u.id===a);i.push({severity:"medium",priority:"p2",category:"coupling",issue:`${l?.name??a} has ${o} outgoing dependencies`,suggestion:"Consider breaking this component into smaller, more focused units",affectedElements:[a]})}let s=t.filter(a=>!a.boundary);return s.length>3&&s.length<t.length&&i.push({severity:"low",priority:"p3",category:"layering",issue:`${s.length} components lack boundary/layer assignment`,suggestion:"Assign components to appropriate layers or modules for better organization",affectedElements:s.map(a=>a.id)}),i.sort((a,o)=>{let l={p0:0,p1:1,p2:2,p3:3};return l[a.priority]-l[o.priority]})}calculatePatternConfidence(t,e,r){let i=.5;return t==="layered"&&(i+=Math.min(.3,e.length*.1)),i+=Math.min(.2,r.length*.02),new Set(r.map(s=>s.boundary).filter(Boolean)).size>0&&(i+=.1),Math.min(1,i)}};var Uu="Application",CR={database:"database",cache:"cache",queue:"message_queue",api:"api",storage:"storage",auth:"authentication",monitoring:"monitoring",cloud:"third_party"},SR={controller:"controller",service:"service",repository:"repository",facade:"facade",factory:"factory",adapter:"adapter",gateway:"gateway",handler:"handler",validator:"validator",transformer:"adapter",utility:"utility",module:"module",layer:"module",feature:"module",package:"module",other:"module"};function RR(c){return CR[c]??"third_party"}function TR(c){return SR[c]??"module"}var ER={uses:"uses",calls:"calls",imports:"depends_on",depends_on:"depends_on",extends:"extends",implements:"implements",sends:"sends_to",reads:"reads_from",writes:"writes_to",stores_data_in:"writes_to",authenticates_with:"authenticates_with"};function AR(c){return ER[c]??"uses"}function vh(c){return c.map(t=>({name:t.name,type:RR(t.type),technology:t.technology,relationshipDescription:t.relationship}))}function xR(c){return c.map(t=>({name:t.name,type:TR(t.type),technology:t.technology,boundary:t.boundary,files:t.files,responsibilities:t.responsibilities}))}function PR(c,t){let e=new Map(c.map(i=>[i.id,i.name])),r=[];for(let i of t){let n=e.get(i.sourceId),s=e.get(i.targetId);n===void 0||s===void 0||r.push({from:n,to:s,type:AR(i.type)})}return r}function bh(c,t){return{systemName:c.name,systemDescription:c.description,externalSystems:vh(t)}}function wh(c,t){let e=vh(t);return{systemName:c.name,containers:[{name:Uu,type:"web_application",technology:"TypeScript",description:"Main application"}],externalSystems:e,dependencies:e.map(r=>({from:Uu,to:r.name,description:r.relationshipDescription}))}}function Ch(c,t,e=Uu){return{containerName:e,components:xR(c),relationships:PR(c,t)}}var kR={cacheTtlMs:36e5,publishEvents:!0,excludePatterns:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/coverage/**"],maxFiles:1e3},Sh={pg:{type:"database",technology:"PostgreSQL"},mysql:{type:"database",technology:"MySQL"},mysql2:{type:"database",technology:"MySQL"},mongodb:{type:"database",technology:"MongoDB"},mongoose:{type:"database",technology:"MongoDB"},sqlite3:{type:"database",technology:"SQLite"},"better-sqlite3":{type:"database",technology:"SQLite"},prisma:{type:"database",technology:"Prisma ORM"},typeorm:{type:"database",technology:"TypeORM"},sequelize:{type:"database",technology:"Sequelize"},"drizzle-orm":{type:"database",technology:"Drizzle"},"@supabase/supabase-js":{type:"database",technology:"Supabase"},redis:{type:"cache",technology:"Redis"},ioredis:{type:"cache",technology:"Redis"},memcached:{type:"cache",technology:"Memcached"},amqplib:{type:"queue",technology:"RabbitMQ"},kafkajs:{type:"queue",technology:"Kafka"},bullmq:{type:"queue",technology:"BullMQ"},bull:{type:"queue",technology:"Bull"},"@aws-sdk/client-sqs":{type:"queue",technology:"AWS SQS"},"@aws-sdk/client-s3":{type:"storage",technology:"AWS S3"},"@google-cloud/storage":{type:"storage",technology:"Google Cloud Storage"},"@azure/storage-blob":{type:"storage",technology:"Azure Blob Storage"},"@auth0/auth0-spa-js":{type:"auth",technology:"Auth0"},passport:{type:"auth",technology:"Passport.js"},jsonwebtoken:{type:"auth",technology:"JWT"},"@clerk/clerk-sdk-node":{type:"auth",technology:"Clerk"},"@sentry/node":{type:"monitoring",technology:"Sentry"},newrelic:{type:"monitoring",technology:"New Relic"},"@datadog/dd-trace":{type:"monitoring",technology:"Datadog"},pino:{type:"monitoring",technology:"Pino Logger"},winston:{type:"monitoring",technology:"Winston Logger"},axios:{type:"api",technology:"HTTP Client"},"node-fetch":{type:"api",technology:"HTTP Client"},got:{type:"api",technology:"HTTP Client"},"@anthropic-ai/sdk":{type:"api",technology:"Anthropic API"},openai:{type:"api",technology:"OpenAI API"},stripe:{type:"api",technology:"Stripe API"},twilio:{type:"api",technology:"Twilio API"}},lt=x.create("code-intelligence/product-factors-bridge"),Co=class{constructor(t,e,r={}){this.eventBus=t;this.memory=e;this.config={...kR,...r}}eventBus;memory;config;initialized=!1;eventSubscriptions=[];c4Service;getC4Service(){return this.c4Service||(this.c4Service=new wo(this.memory,{enableEmbeddings:this.config.enableC4Embeddings??!1})),this.c4Service}async initialize(){this.initialized||(this.subscribeToEvents(),this.initialized=!0)}async dispose(){for(let t of this.eventSubscriptions)t.unsubscribe();this.eventSubscriptions=[],this.initialized=!1}subscribeToEvents(){let t=this.eventBus.subscribe(Lt.KnowledgeGraphUpdated,this.handleKnowledgeGraphUpdated.bind(this));this.eventSubscriptions.push(t);let e=this.eventBus.subscribe(Lt.ImpactAnalysisCompleted,this.handleImpactAnalysisCompleted.bind(this));this.eventSubscriptions.push(e)}async handleKnowledgeGraphUpdated(t){lt.info("[ProductFactorsBridge] Knowledge graph updated, considering cache invalidation")}async handleImpactAnalysisCompleted(t){let e=t.payload;e.changedFiles&&e.changedFiles.length>0&&lt.info(`[ProductFactorsBridge] Impact analysis detected ${e.changedFiles.length} changed files`)}async requestC4Diagrams(t){let e=Date.now(),r=w();try{let i=await this.getCachedDiagrams(t.projectPath);if(i)return lt.info(`[ProductFactorsBridge] Returning cached C4 diagrams for ${t.projectPath}`),f(i);let n=await this.generateC4Diagrams(t);return n.success&&(await this.cacheResult(t.projectPath,n.value),this.config.publishEvents&&await this.publishC4DiagramsGenerated(r,t.projectPath,n.value,Date.now()-e)),n}catch(i){let n=y(i);return g(n)}}async generateC4Diagrams(t){let e=Date.now();try{let r=await this.getProjectMetadata(t.projectPath),i=[];t.detectExternalSystems!==!1&&(i=await this.detectExternalSystems(t.projectPath));let n=[],s=[];if(t.analyzeComponents!==!1){let d=await this.analyzeComponents(t.projectPath);n=d.components,s=d.relationships}let a;t.analyzeCoupling&&n.length>1&&(a=this.analyzeCoupling(n,s));let o={};t.includeContext!==!1&&(o.context=await this.renderContext(r,i)),t.includeContainer!==!1&&(o.container=await this.renderContainer(r,i)),t.includeComponent!==!1&&n.length>0&&(o.component=await this.renderComponent(r,n,s)),t.includeDependency&&n.length>0&&(o.dependency=this.generateDependencyGraph(n,s));let l=n.reduce((d,m)=>d+m.files.length,0),u={projectName:r.name,projectDescription:r.description,generatedAt:new Date,source:"codebase-analysis",analysisMetadata:{filesAnalyzed:l,componentsDetected:n.length,externalSystemsDetected:i.length,analysisTimeMs:Date.now()-e,confidence:hh({componentsDetected:n.length,relationshipsDetected:s.length,externalSystemsDetected:i.length,filesAnalyzed:l})}};return f({diagrams:o,metadata:u,externalSystems:i,components:n,relationships:s,couplingAnalysis:a})}catch(r){let i=y(r);return g(i)}}async renderContext(t,e){let r=await this.getC4Service().buildContext(bh(t,e));if(!r.success)throw lt.error("[ProductFactorsBridge] C4 context render failed",r.error),r.error;return r.value.mermaid}async renderContainer(t,e){let r=await this.getC4Service().buildContainer(wh(t,e));if(!r.success)throw lt.error("[ProductFactorsBridge] C4 container render failed",r.error),r.error;return r.value.mermaid}async renderComponent(t,e,r){let i=await this.getC4Service().buildComponent(Ch(e,r));if(!i.success)throw lt.error("[ProductFactorsBridge] C4 component render failed",i.error),i.error;return i.value.mermaid}generateDependencyGraph(t,e){let r=`graph TD
2868
2868
  `;for(let i of t)r+=` ${i.id}["${i.name}"]
2869
2869
  `;for(let i of e){let n=i.type==="depends_on"?"-->|depends|":"-->";r+=` ${i.sourceId} ${n} ${i.targetId}
2870
- `}return r}async getProjectMetadata(t){try{let e=kt.join(t,"package.json"),r=await Re(e,{outsideRoot:"allow"}),i=D(r);return{name:i.name||"Project",description:i.description||"Application system"}}catch{return{name:"Project",description:"Application system"}}}async detectExternalSystems(t){let e=[];try{let r=kt.join(t,"package.json");try{await wi.access(r)}catch{return e}let i=await Re(r,{outsideRoot:"allow"}),n=D(i),s={...n.dependencies,...n.devDependencies};for(let[a]of Object.entries(s)){let o=Object.hasOwn(Sh,a)?Sh[a]:void 0;o&&e.push({id:bo(a),name:o.technology,type:o.type,technology:o.technology,detectedFrom:"package.json",relationship:this.inferRelationship(o.type)})}}catch(r){lt.error("External system detection failed",r instanceof Error?r:void 0)}return e}inferRelationship(t){switch(t){case"database":return"stores_data_in";case"auth":return"authenticates_with";case"queue":return"sends";default:return"uses"}}async analyzeComponents(t){let e=[],r=[];try{let i=kt.join(t,"src"),n=t;try{await wi.access(i),n=i}catch{}let s=await wi.readdir(n,{withFileTypes:!0});for(let a of s)if(a.isDirectory()&&!this.shouldExclude(a.name)){let o=kt.join(n,a.name),l=await this.getFilesInDirectory(o,t);l.length>0&&e.push({id:bo(a.name),name:this.formatComponentName(a.name),type:yh(a.name),boundary:this.inferBoundary(a.name),technology:"TypeScript",files:l,responsibilities:[this.inferResponsibility(a.name)]})}for(let a=0;a<e.length;a++)for(let o=a+1;o<e.length;o++){let l=e[a],u=e[o];this.likelyHasRelationship(l.id,u.id)&&r.push({sourceId:l.id,targetId:u.id,type:"uses",weight:1})}}catch(i){lt.error("Component analysis failed:",i instanceof Error?i:void 0)}if(this.config.relationshipResolver&&e.length>0)try{let i=await this.config.relationshipResolver(e,t);if(i&&i.length>0)return{components:e,relationships:i}}catch(i){lt.debug(`KG relationship resolver failed; using heuristic: ${y(i).message}`)}return{components:e,relationships:r}}shouldExclude(t){return["node_modules",".git","dist","build","coverage","__tests__","__mocks__"].includes(t)||t.startsWith(".")}async getFilesInDirectory(t,e,r=3){let i=[],n=async(s,a)=>{if(!(a>r))try{let o=await wi.readdir(s,{withFileTypes:!0});for(let l of o){if(this.shouldExclude(l.name))continue;let u=kt.join(s,l.name),d=kt.relative(e,u);l.isDirectory()?await n(u,a+1):l.isFile()&&this.isSourceFile(l.name)&&i.push(d)}}catch{lt.debug("Directory scan error:")}};return await n(t,0),i}isSourceFile(t){return[".ts",".tsx",".js",".jsx",".vue",".svelte"].some(r=>t.endsWith(r))&&!t.endsWith(".d.ts")}formatComponentName(t){return t.split(/[-_]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}inferBoundary(t){let e=t.toLowerCase();return e.includes("api")||e.includes("controller")?"API Layer":e.includes("service")?"Service Layer":e.includes("domain")?"Domain Layer":e.includes("infra")||e.includes("database")?"Infrastructure Layer":e.includes("ui")||e.includes("component")?"Presentation Layer":"Core"}inferResponsibility(t){let e=t.toLowerCase();return e.includes("auth")?"Authentication and authorization":e.includes("user")?"User management":e.includes("api")?"API endpoint handling":e.includes("service")?"Business logic processing":e.includes("model")?"Data modeling and validation":e.includes("util")?"Utility functions":e.includes("config")?"Configuration management":`${this.formatComponentName(t)} functionality`}likelyHasRelationship(t,e){let r=[["service","model"],["service","repository"],["controller","service"],["api","service"],["domain","infra"]],i=t.toLowerCase(),n=e.toLowerCase();return r.some(([s,a])=>i.includes(s)&&n.includes(a)||i.includes(a)&&n.includes(s))}analyzeCoupling(t,e){let r=[];try{if(t.length<2)return r;let i=new Set;for(let n of e)if(e.some(a=>a.sourceId===n.targetId&&a.targetId===n.sourceId)){let a=[n.sourceId,n.targetId].sort().join("::");i.add(a)}for(let n=0;n<t.length;n++)for(let s=n+1;s<t.length;s++){let a=t[n],o=t[s],l=e.filter(u=>u.sourceId===a.id&&u.targetId===o.id||u.sourceId===o.id&&u.targetId===a.id);if(l.length>0){let u=l.reduce((h,v)=>h+(v.weight||1),0),d=Math.min(1,u/10),m=[a.id,o.id].sort().join("::"),p=i.has(m);r.push({moduleA:a.name,moduleB:o.name,couplingStrength:d,isCircular:p,recommendation:this.getCouplingRecommendation(d,p)})}}}catch(i){lt.error("Coupling analysis failed:",i instanceof Error?i:void 0)}return r}getCouplingRecommendation(t,e){return e?"CRITICAL: Circular dependency detected. Consider extracting shared interface.":t>.8?"HIGH: Tightly coupled. Consider interface segregation or facade pattern.":t>.5?"MEDIUM: Moderate coupling. Monitor for growth.":"LOW: Acceptable coupling level."}async getCachedDiagrams(t){let e=this.getCacheKey(t),r=await this.memory.get(e);return r&&fh(r)?r.result:null}async invalidateCache(t){let e=this.getCacheKey(t);await this.memory.delete(e)}async cacheResult(t,e){let r=this.getCacheKey(t),i=await this.computeProjectHash(t),n={result:e,cachedAt:new Date,ttlMs:this.config.cacheTtlMs,projectHash:i};await this.memory.set(r,n,{namespace:"code-intelligence",ttl:this.config.cacheTtlMs/1e3})}getCacheKey(t){return`c4-diagrams:${bo(t)}`}async computeProjectHash(t){try{let e=kt.join(t,"package.json"),r=await Re(e,{outsideRoot:"allow"});return this.hashString(r)}catch{return this.hashString(t+Date.now())}}hashString(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e).toString(16)}async getExternalSystems(t){try{let e=await this.getCachedDiagrams(t);if(e)return f(e.externalSystems);let r=await this.detectExternalSystems(t);return f(r)}catch(e){let r=y(e);return g(r)}}async getComponents(t){try{let e=await this.getCachedDiagrams(t);if(e)return f(e.components);let{components:r}=await this.analyzeComponents(t);return f(r)}catch(e){let r=y(e);return g(r)}}async publishC4DiagramsGenerated(t,e,r,i){let n={requestId:t,projectPath:e,componentsDetected:r.components.length,externalSystemsDetected:r.externalSystems.length,relationshipsDetected:r.relationships.length,analysisTimeMs:i,hasContextDiagram:!!r.diagrams.context,hasContainerDiagram:!!r.diagrams.container,hasComponentDiagram:!!r.diagrams.component},s=N(Lt.C4DiagramsGenerated,"code-intelligence",n);await this.eventBus.publish(s)}};import*as Qu from"path";var Rh=(c,t)=>Qu.resolve(c,t).replace(/\\/g,"/");function DR(c,t,e){let r=new Map;for(let a of c)for(let o of a.files??[])r.set(Rh(e,o),a.id);let i=new Map(t.nodes.map(a=>[a.id,Rh(e,a.path)])),n=a=>{let o=i.get(a);if(!o)return;let l=r.get(o);if(l)return l;for(let[u,d]of r)if(o.endsWith(u)||u.endsWith(o))return d},s=new Map;for(let a of t.edges){let o=n(a.source),l=n(a.target);if(!o||!l||o===l)continue;let u=`${o}->${l}`,d=s.get(u);d?d.weight=(d.weight??1)+1:s.set(u,{sourceId:o,targetId:l,type:"depends_on",weight:1})}return[...s.values()]}function Th(c,t={}){let e=t.autoIndex??!0,r=typeof c=="function"?c:()=>c;return async(i,n)=>{let s=i.flatMap(a=>(a.files??[]).map(o=>Qu.resolve(n,o)));if(s.length===0)return null;try{let a=r(n);e&&await a.index({paths:s,incremental:!0});let o=await a.mapDependencies({files:s,direction:"both"});if(!o.success||!o.value)return null;let l=DR(i,o.value,n);return l.length>0?l:null}catch{return null}}}k();var IR={embeddingDimension:vr.DIMENSIONS,minScore:.5,maxResults:100,namespace:"code-intelligence:semantic",enableCaching:!0,cacheSize:1e3,useNomicEmbeddings:!0},Fr=class{constructor(t,e={}){this.memory=t;this.config={...IR,...e},e.embeddingProvider&&(this.embedder=e.embeddingProvider,this.embedderInitialized=!0)}memory;config;embeddingCache=new Map;analysisCache=new Map;embedder=null;embedderInitialized=!1;async initializeEmbedder(){if(!this.embedderInitialized){if(this.config.useNomicEmbeddings){let t=new wt({enableFallback:!0,...this.config.nomicConfig});await t.healthCheck()&&(this.embedder=t,this.config.embeddingDimension=vr.DIMENSIONS)}this.embedderInitialized=!0}}async search(t){let e=Date.now();try{let{query:r,type:i,scope:n,limit:s=this.config.maxResults,filters:a}=t,o;switch(i){case"semantic":o=await this.semanticSearch(r,s,n,a);break;case"exact":o=await this.exactSearch(r,s,n,a);break;case"fuzzy":o=await this.fuzzySearch(r,s,n,a);break;default:return g(new Error(`Unknown search type: ${i}`))}let l=Date.now()-e;return f({results:o,total:o.length,searchTime:l})}catch(r){return g(y(r))}}async indexCode(t,e){try{let r=await this.getEmbedding(e),i=this.extractCodeMetadata(t,e),n=`${this.config.namespace}:code:${this.fileToKey(t)}`;return await this.memory.storeVector(n,r,{file:t,...i,indexedAt:new Date().toISOString()}),await this.memory.set(`${this.config.namespace}:content:${this.fileToKey(t)}`,{file:t,content:e,metadata:i}),f(void 0)}catch(r){return g(y(r))}}async findSimilar(t,e=10){try{let r=await this.getEmbedding(t),i=await this.memory.vectorSearch(r,e),n=[];for(let s of i){if(s.score<this.config.minScore)continue;let a=s.metadata;if(!a?.file)continue;let o=`${this.config.namespace}:content:${this.fileToKey(a.file)}`,l=await this.memory.get(o);l&&n.push({file:l.file,snippet:this.extractSnippet(l.content,200),score:s.score,highlights:this.findHighlights(l.content,t),metadata:l.metadata})}return f(n)}catch(r){return g(y(r))}}async analyze(t){try{let e=this.hashCode(t);if(this.config.enableCaching&&this.analysisCache.has(e))return f(this.analysisCache.get(e));let r=this.extractConcepts(t),i=this.detectPatterns(t),n=this.calculateComplexity(t),s=this.extractDependencies(t),a=this.generateSuggestions(t,n,i),o={concepts:r,patterns:i,complexity:n,dependencies:s,suggestions:a};return this.config.enableCaching&&this.cacheAnalysis(e,o),f(o)}catch(e){return g(y(e))}}async getEmbedding(t){let e=this.hashCode(t);if(this.config.enableCaching&&this.embeddingCache.has(e))return this.embeddingCache.get(e);await this.initializeEmbedder();let r;return this.embedder?r=await this.embedder.embed(t):r=this.generateCodeEmbedding(t),this.config.enableCaching&&this.cacheEmbedding(e,r),r}isUsingNomicEmbeddings(){return this.embedder!==null&&this.embedder instanceof wt}async semanticSearch(t,e,r,i){let n=await this.getEmbedding(t),s=await this.memory.vectorSearch(n,e*2),a=[];for(let o of s){if(o.score<this.config.minScore)continue;let l=o.metadata;if(!l?.file||r&&r.length>0&&!r.some(p=>l.file.includes(p)))continue;let u=`${this.config.namespace}:content:${this.fileToKey(l.file)}`,d=await this.memory.get(u);if(d){if(i&&!this.matchesFilters(d.metadata,i))continue;if(a.push({file:d.file,snippet:this.extractSnippet(d.content,200),score:o.score,highlights:this.findSemanticHighlights(d.content,t),metadata:d.metadata}),a.length>=e)break}}return a}async exactSearch(t,e,r,i){let n=[],s=`${this.config.namespace}:content:*`,a=await this.memory.search(s,e*3);for(let o of a){let l=await this.memory.get(o);if(!l||r&&r.length>0&&!r.some(m=>l.file.includes(m))||i&&!this.matchesFilters(l.metadata,i))continue;let u=l.content.indexOf(t);if(u>=0){let d=this.getLineNumber(l.content,u);if(n.push({file:l.file,line:d,snippet:this.extractSnippetAround(l.content,u,100),score:1,highlights:[t],metadata:l.metadata}),n.length>=e)break}}return n}async fuzzySearch(t,e,r,i){let n=[],s=`${this.config.namespace}:content:*`,a=await this.memory.search(s,e*5),o=this.tokenize(t.toLowerCase());for(let l of a){let u=await this.memory.get(l);if(!u||r&&r.length>0&&!r.some(h=>u.file.includes(h))||i&&!this.matchesFilters(u.metadata,i))continue;let d=this.tokenize(u.content.toLowerCase()),m=this.calculateFuzzyScore(o,d);if(m>=this.config.minScore){let p=o.filter(h=>d.some(v=>v.includes(h)||h.includes(v)));n.push({file:u.file,snippet:this.extractSnippet(u.content,200),score:m,highlights:p,metadata:u.metadata})}}return n.sort((l,u)=>u.score-l.score).slice(0,e)}extractConcepts(t){let e=[];return/class\s+\w+/.test(t)&&e.push("object-oriented"),/async\s+|await\s+|Promise/.test(t)&&e.push("asynchronous"),/\([^)]*\)\s*=>/.test(t)&&e.push("functional"),/interface\s+\w+/.test(t)&&e.push("type-safe"),/export\s+(default\s+)?/.test(t)&&e.push("modular"),/import\s+.*from/.test(t)&&e.push("dependency-injection"),/try\s*{[\s\S]*catch/.test(t)&&e.push("error-handling"),/\.map\(|\.filter\(|\.reduce\(/.test(t)&&e.push("collection-processing"),/new\s+Map\(|new\s+Set\(/.test(t)&&e.push("data-structures"),/describe\(|it\(|test\(|expect\(/.test(t)&&e.push("testing"),Array.from(new Set(e))}detectPatterns(t){let e=[];return/private\s+static\s+instance|getInstance\(\)/.test(t)&&e.push("singleton"),/factory|create\w+\(\)/.test(t)&&e.push("factory"),/constructor\(.*private.*\)/.test(t)&&e.push("dependency-injection"),/extends\s+\w+.*implements\s+\w+/.test(t)&&e.push("decorator"),/subscribe\(|on\w+\(|emit\(|publish\(/.test(t)&&e.push("observer"),/strategy|Strategy/.test(t)&&e.push("strategy"),/Repository|DAO/.test(t)&&e.push("repository"),/Builder|\.with\w+\(/.test(t)&&e.push("builder"),e}calculateComplexity(t){let e=[/\bif\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*:/g,/&&/g,/\|\|/g],r=1;for(let E of e){let T=t.match(E);r+=T?T.length:0}let i=0,n=t.split(`
2870
+ `}return r}async getProjectMetadata(t){try{let e=kt.join(t,"package.json"),r=await Re(e,{outsideRoot:"allow"}),i=D(r);return{name:i.name||"Project",description:i.description||"Application system"}}catch{return{name:"Project",description:"Application system"}}}async detectExternalSystems(t){let e=[];try{let r=kt.join(t,"package.json");try{await wi.access(r)}catch{return e}let i=await Re(r,{outsideRoot:"allow"}),n=D(i),s={...n.dependencies,...n.devDependencies};for(let[a]of Object.entries(s)){let o=Object.hasOwn(Sh,a)?Sh[a]:void 0;o&&e.push({id:bo(a),name:o.technology,type:o.type,technology:o.technology,detectedFrom:"package.json",relationship:this.inferRelationship(o.type)})}}catch(r){lt.error("External system detection failed",r instanceof Error?r:void 0)}return e}inferRelationship(t){switch(t){case"database":return"stores_data_in";case"auth":return"authenticates_with";case"queue":return"sends";default:return"uses"}}async analyzeComponents(t){let e=[],r=[];try{let i=kt.join(t,"src"),n=t;try{await wi.access(i),n=i}catch{}let s=await wi.readdir(n,{withFileTypes:!0});for(let a of s)if(a.isDirectory()&&!this.shouldExclude(a.name)){let o=kt.join(n,a.name),l=await this.getFilesInDirectory(o,t);l.length>0&&e.push({id:bo(a.name),name:this.formatComponentName(a.name),type:yh(a.name),boundary:this.inferBoundary(a.name),technology:"TypeScript",files:l,responsibilities:[this.inferResponsibility(a.name)]})}for(let a=0;a<e.length;a++)for(let o=a+1;o<e.length;o++){let l=e[a],u=e[o];this.likelyHasRelationship(l.id,u.id)&&r.push({sourceId:l.id,targetId:u.id,type:"uses",weight:1})}}catch(i){lt.error("Component analysis failed:",i instanceof Error?i:void 0)}if(this.config.relationshipResolver&&e.length>0)try{let i=await this.config.relationshipResolver(e,t);if(i&&i.length>0)return{components:e,relationships:i}}catch(i){lt.debug(`KG relationship resolver failed; using heuristic: ${y(i).message}`)}return{components:e,relationships:r}}shouldExclude(t){return["node_modules",".git","dist","build","coverage","__tests__","__mocks__"].includes(t)||t.startsWith(".")}async getFilesInDirectory(t,e,r=3){let i=[],n=async(s,a)=>{if(!(a>r))try{let o=await wi.readdir(s,{withFileTypes:!0});for(let l of o){if(this.shouldExclude(l.name))continue;let u=kt.join(s,l.name),d=kt.relative(e,u);l.isDirectory()?await n(u,a+1):l.isFile()&&this.isSourceFile(l.name)&&i.push(d)}}catch{lt.debug("Directory scan error:")}};return await n(t,0),i}isSourceFile(t){return[".ts",".tsx",".js",".jsx",".vue",".svelte"].some(r=>t.endsWith(r))&&!t.endsWith(".d.ts")}formatComponentName(t){return t.split(/[-_]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}inferBoundary(t){let e=t.toLowerCase();return e.includes("api")||e.includes("controller")?"API Layer":e.includes("service")?"Service Layer":e.includes("domain")?"Domain Layer":e.includes("infra")||e.includes("database")?"Infrastructure Layer":e.includes("ui")||e.includes("component")?"Presentation Layer":"Core"}inferResponsibility(t){let e=t.toLowerCase();return e.includes("auth")?"Authentication and authorization":e.includes("user")?"User management":e.includes("api")?"API endpoint handling":e.includes("service")?"Business logic processing":e.includes("model")?"Data modeling and validation":e.includes("util")?"Utility functions":e.includes("config")?"Configuration management":`${this.formatComponentName(t)} functionality`}likelyHasRelationship(t,e){let r=[["service","model"],["service","repository"],["controller","service"],["api","service"],["domain","infra"]],i=t.toLowerCase(),n=e.toLowerCase();return r.some(([s,a])=>i.includes(s)&&n.includes(a)||i.includes(a)&&n.includes(s))}analyzeCoupling(t,e){let r=[];try{if(t.length<2)return r;let i=new Set;for(let n of e)if(e.some(a=>a.sourceId===n.targetId&&a.targetId===n.sourceId)){let a=[n.sourceId,n.targetId].sort().join("::");i.add(a)}for(let n=0;n<t.length;n++)for(let s=n+1;s<t.length;s++){let a=t[n],o=t[s],l=e.filter(u=>u.sourceId===a.id&&u.targetId===o.id||u.sourceId===o.id&&u.targetId===a.id);if(l.length>0){let u=l.reduce((h,v)=>h+(v.weight||1),0),d=Math.min(1,u/10),m=[a.id,o.id].sort().join("::"),p=i.has(m);r.push({moduleA:a.name,moduleB:o.name,couplingStrength:d,isCircular:p,recommendation:this.getCouplingRecommendation(d,p)})}}}catch(i){lt.error("Coupling analysis failed:",i instanceof Error?i:void 0)}return r}getCouplingRecommendation(t,e){return e?"CRITICAL: Circular dependency detected. Consider extracting shared interface.":t>.8?"HIGH: Tightly coupled. Consider interface segregation or facade pattern.":t>.5?"MEDIUM: Moderate coupling. Monitor for growth.":"LOW: Acceptable coupling level."}async getCachedDiagrams(t){let e=this.getCacheKey(t),r=await this.memory.get(e);return r&&fh(r)?r.result:null}async invalidateCache(t){let e=this.getCacheKey(t);await this.memory.delete(e)}async cacheResult(t,e){let r=this.getCacheKey(t),i=await this.computeProjectHash(t),n={result:e,cachedAt:new Date,ttlMs:this.config.cacheTtlMs,projectHash:i};await this.memory.set(r,n,{namespace:"code-intelligence",ttl:this.config.cacheTtlMs/1e3})}getCacheKey(t){return`c4-diagrams:${bo(t)}`}async computeProjectHash(t){try{let e=kt.join(t,"package.json"),r=await Re(e,{outsideRoot:"allow"});return this.hashString(r)}catch{return this.hashString(t+Date.now())}}hashString(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e).toString(16)}async getExternalSystems(t){try{let e=await this.getCachedDiagrams(t);if(e)return f(e.externalSystems);let r=await this.detectExternalSystems(t);return f(r)}catch(e){let r=y(e);return g(r)}}async getComponents(t){try{let e=await this.getCachedDiagrams(t);if(e)return f(e.components);let{components:r}=await this.analyzeComponents(t);return f(r)}catch(e){let r=y(e);return g(r)}}async publishC4DiagramsGenerated(t,e,r,i){let n={requestId:t,projectPath:e,componentsDetected:r.components.length,externalSystemsDetected:r.externalSystems.length,relationshipsDetected:r.relationships.length,analysisTimeMs:i,hasContextDiagram:!!r.diagrams.context,hasContainerDiagram:!!r.diagrams.container,hasComponentDiagram:!!r.diagrams.component},s=N(Lt.C4DiagramsGenerated,"code-intelligence",n);await this.eventBus.publish(s)}};import*as Qu from"path";var Rh=(c,t)=>Qu.resolve(c,t).replace(/\\/g,"/");function DR(c,t,e){let r=new Map;for(let a of c)for(let o of a.files??[])r.set(Rh(e,o),a.id);let i=new Map(t.nodes.map(a=>[a.id,Rh(e,a.path)])),n=a=>{let o=i.get(a);if(!o)return;let l=r.get(o);if(l)return l;for(let[u,d]of r)if(o.endsWith(u)||u.endsWith(o))return d},s=new Map;for(let a of t.edges){let o=n(a.source),l=n(a.target);if(!o||!l||o===l)continue;let u=`${o}->${l}`,d=s.get(u);d?d.weight=(d.weight??1)+1:s.set(u,{sourceId:o,targetId:l,type:"depends_on",weight:1})}return[...s.values()]}function Th(c,t={}){let e=t.autoIndex??!0,r=typeof c=="function"?c:()=>c;return async(i,n)=>{let s=i.flatMap(a=>(a.files??[]).map(o=>Qu.resolve(n,o)));if(s.length===0)return null;try{let a=r(n);e&&await a.index({paths:s,incremental:!0});let o=await a.mapDependencies({files:s,direction:"both"});if(!o.success||!o.value)return null;let l=DR(i,o.value,n);return l.length>0?l:null}catch{return null}}}import{createHash as IR}from"node:crypto";k();var MR={embeddingDimension:vr.DIMENSIONS,minScore:.5,maxResults:100,namespace:"code-intelligence:semantic",enableCaching:!0,cacheSize:1e3,useNomicEmbeddings:!0},Fr=class{constructor(t,e={}){this.memory=t;this.config={...MR,...e},e.embeddingProvider&&(this.embedder=e.embeddingProvider,this.embedderInitialized=!0)}memory;config;embeddingCache=new Map;analysisCache=new Map;embedder=null;embedderInitialized=!1;async initializeEmbedder(){if(!this.embedderInitialized){if(this.config.useNomicEmbeddings){let t=new wt({enableFallback:!0,...this.config.nomicConfig});await t.healthCheck()&&(this.embedder=t,this.config.embeddingDimension=vr.DIMENSIONS)}this.embedderInitialized=!0}}async search(t){let e=Date.now();try{let{query:r,type:i,scope:n,limit:s=this.config.maxResults,filters:a}=t,o;switch(i){case"semantic":o=await this.semanticSearch(r,s,n,a);break;case"exact":o=await this.exactSearch(r,s,n,a);break;case"fuzzy":o=await this.fuzzySearch(r,s,n,a);break;default:return g(new Error(`Unknown search type: ${i}`))}let l=Date.now()-e;return f({results:o,total:o.length,searchTime:l})}catch(r){return g(y(r))}}async indexCode(t,e){try{let r=await this.getEmbedding(e),i=this.extractCodeMetadata(t,e),n=`${this.config.namespace}:code:${this.fileToKey(t)}`;return await this.memory.storeVector(n,r,{file:t,...i,indexedAt:new Date().toISOString()}),await this.memory.set(`${this.config.namespace}:content:${this.fileToKey(t)}`,{file:t,content:e,metadata:i}),f(void 0)}catch(r){return g(y(r))}}async findSimilar(t,e=10){try{let r=await this.getEmbedding(t),i=await this.memory.vectorSearch(r,e),n=[];for(let s of i){if(s.score<this.config.minScore)continue;let a=s.metadata;if(!a?.file)continue;let o=`${this.config.namespace}:content:${this.fileToKey(a.file)}`,l=await this.memory.get(o);l&&n.push({file:l.file,snippet:this.extractSnippet(l.content,200),score:s.score,highlights:this.findHighlights(l.content,t),metadata:l.metadata})}return f(n)}catch(r){return g(y(r))}}async analyze(t){try{let e=this.hashCode(t);if(this.config.enableCaching&&this.analysisCache.has(e))return f(this.analysisCache.get(e));let r=this.extractConcepts(t),i=this.detectPatterns(t),n=this.calculateComplexity(t),s=this.extractDependencies(t),a=this.generateSuggestions(t,n,i),o={concepts:r,patterns:i,complexity:n,dependencies:s,suggestions:a};return this.config.enableCaching&&this.cacheAnalysis(e,o),f(o)}catch(e){return g(y(e))}}async getEmbedding(t){let e=this.hashCode(t);if(this.config.enableCaching&&this.embeddingCache.has(e))return this.embeddingCache.get(e);await this.initializeEmbedder();let r;return this.embedder?r=await this.embedder.embed(t):r=this.generateCodeEmbedding(t),this.config.enableCaching&&this.cacheEmbedding(e,r),r}isUsingNomicEmbeddings(){return this.embedder!==null&&this.embedder instanceof wt}async semanticSearch(t,e,r,i){let n=await this.getEmbedding(t),s=await this.memory.vectorSearch(n,e*2),a=[];for(let o of s){if(o.score<this.config.minScore)continue;let l=o.metadata;if(!l?.file||r&&r.length>0&&!r.some(p=>l.file.includes(p)))continue;let u=`${this.config.namespace}:content:${this.fileToKey(l.file)}`,d=await this.memory.get(u);if(d){if(i&&!this.matchesFilters(d.metadata,i))continue;if(a.push({file:d.file,snippet:this.extractSnippet(d.content,200),score:o.score,highlights:this.findSemanticHighlights(d.content,t),metadata:d.metadata}),a.length>=e)break}}return a}async exactSearch(t,e,r,i){let n=[],s=`${this.config.namespace}:content:*`,a=await this.memory.search(s,e*3);for(let o of a){let l=await this.memory.get(o);if(!l||r&&r.length>0&&!r.some(m=>l.file.includes(m))||i&&!this.matchesFilters(l.metadata,i))continue;let u=l.content.indexOf(t);if(u>=0){let d=this.getLineNumber(l.content,u);if(n.push({file:l.file,line:d,snippet:this.extractSnippetAround(l.content,u,100),score:1,highlights:[t],metadata:l.metadata}),n.length>=e)break}}return n}async fuzzySearch(t,e,r,i){let n=[],s=`${this.config.namespace}:content:*`,a=await this.memory.search(s,e*5),o=this.tokenize(t.toLowerCase());for(let l of a){let u=await this.memory.get(l);if(!u||r&&r.length>0&&!r.some(h=>u.file.includes(h))||i&&!this.matchesFilters(u.metadata,i))continue;let d=this.tokenize(u.content.toLowerCase()),m=this.calculateFuzzyScore(o,d);if(m>=this.config.minScore){let p=o.filter(h=>d.some(v=>v.includes(h)||h.includes(v)));n.push({file:u.file,snippet:this.extractSnippet(u.content,200),score:m,highlights:p,metadata:u.metadata})}}return n.sort((l,u)=>u.score-l.score).slice(0,e)}extractConcepts(t){let e=[];return/class\s+\w+/.test(t)&&e.push("object-oriented"),/async\s+|await\s+|Promise/.test(t)&&e.push("asynchronous"),/\([^)]*\)\s*=>/.test(t)&&e.push("functional"),/interface\s+\w+/.test(t)&&e.push("type-safe"),/export\s+(default\s+)?/.test(t)&&e.push("modular"),/import\s+.*from/.test(t)&&e.push("dependency-injection"),/try\s*{[\s\S]*catch/.test(t)&&e.push("error-handling"),/\.map\(|\.filter\(|\.reduce\(/.test(t)&&e.push("collection-processing"),/new\s+Map\(|new\s+Set\(/.test(t)&&e.push("data-structures"),/describe\(|it\(|test\(|expect\(/.test(t)&&e.push("testing"),Array.from(new Set(e))}detectPatterns(t){let e=[];return/private\s+static\s+instance|getInstance\(\)/.test(t)&&e.push("singleton"),/factory|create\w+\(\)/.test(t)&&e.push("factory"),/constructor\(.*private.*\)/.test(t)&&e.push("dependency-injection"),/extends\s+\w+.*implements\s+\w+/.test(t)&&e.push("decorator"),/subscribe\(|on\w+\(|emit\(|publish\(/.test(t)&&e.push("observer"),/strategy|Strategy/.test(t)&&e.push("strategy"),/Repository|DAO/.test(t)&&e.push("repository"),/Builder|\.with\w+\(/.test(t)&&e.push("builder"),e}calculateComplexity(t){let e=[/\bif\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*:/g,/&&/g,/\|\|/g],r=1;for(let E of e){let T=t.match(E);r+=T?T.length:0}let i=0,n=t.split(`
2871
2871
  `),s=0;for(let E of n)/{/.test(E)&&s++,/}/.test(E)&&(s=Math.max(0,s-1)),/\bif\b|\bfor\b|\bwhile\b/.test(E)&&(i+=1+s);let a=t.match(/[+\-*/%=<>!&|^~?:;,.()\[\]{}]+|function|return|if|else|for|while|switch|case|break|continue|throw|try|catch|finally|new|delete|typeof|instanceof|void|in|of/g)||[],o=t.match(/\b[a-zA-Z_]\w*\b|\b\d+\b|'[^']*'|"[^"]*"|`[^`]*`/g)||[],l=new Set(a).size,u=new Set(o).size,d=a.length,m=o.length,p=l+u,h=d+m,v=u>0?l/2*(m/u):0,b=h>0?h*Math.log2(p||1):0,C=v*b,S=C/18,R=b/3e3;return{cyclomatic:r,cognitive:i,halstead:{vocabulary:p,length:h,difficulty:Math.round(v*100)/100,effort:Math.round(C),time:Math.round(S),bugs:Math.round(R*1e3)/1e3}}}extractDependencies(t){let e=[],r=/import\s+(?:\{[^}]+\}|\*\s+as\s+\w+|\w+)\s+from\s+['"]([^'"]+)['"]/g,i;for(;(i=r.exec(t))!==null;)e.push(i[1]);let n=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,s;for(;(s=n.exec(t))!==null;)e.push(s[1]);return Array.from(new Set(e))}generateSuggestions(t,e,r){let i=[];return e.cyclomatic>10&&i.push("Consider breaking down complex functions into smaller units"),e.cognitive>15&&i.push("Reduce nesting depth to improve readability"),e.halstead.bugs>.5&&i.push("High estimated bug density - add comprehensive tests"),!r.includes("error-handling")&&/async|Promise/.test(t)&&i.push("Add error handling for async operations"),!r.includes("testing")&&t.length>500&&i.push("Consider adding unit tests for this code"),t.split(`
2872
2872
  `).length>200&&i.push("Consider splitting this file into smaller modules"),t.split(`
2873
2873
  `).filter(s=>s.length>120).length>5&&i.push("Some lines exceed 120 characters - consider reformatting"),i}generateCodeEmbedding(t){let e=new Array(this.config.embeddingDimension).fill(0),r=this.tokenize(t),i=this.extractConcepts(t);for(let a=0;a<r.length;a++){let o=r[a];for(let l=0;l<o.length&&l<e.length;l++)e[(a+l)%e.length]+=o.charCodeAt(l)/1e3}let n=new Map([["object-oriented",0],["asynchronous",1],["functional",2],["type-safe",3],["modular",4]]);for(let a of i){let o=n.get(a);o!==void 0&&(e[o]+=.5)}let s=Math.sqrt(e.reduce((a,o)=>a+o*o,0))||1;return e.map(a=>a/s)}extractCodeMetadata(t,e){return{language:this.detectLanguage(t),lines:e.split(`
2874
2874
  `).length,size:e.length,hasClasses:/class\s+\w+/.test(e),hasFunctions:/function\s+\w+/.test(e),hasTests:/describe\(|it\(|test\(/.test(e)}}detectLanguage(t){let e=t.split(".").pop()?.toLowerCase()||"";return{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",py:"python",go:"go",java:"java",rs:"rust"}[e]||"unknown"}tokenize(t){return t.split(/\s+|[^\w]+/).filter(e=>e.length>0)}calculateFuzzyScore(t,e){if(t.length===0)return 0;let r=0;for(let i of t)e.some(n=>n.includes(i)||i.includes(n))&&r++;return r/t.length}matchesFilters(t,e){for(let r of e){let i=t[r.field];switch(r.operator){case"eq":if(i!==r.value)return!1;break;case"contains":if(typeof i!="string"||!i.includes(String(r.value)))return!1;break;case"gt":if(typeof i!="number"||i<=r.value)return!1;break;case"lt":if(typeof i!="number"||i>=r.value)return!1;break}}return!0}extractSnippet(t,e){return t.length<=e?t:t.slice(0,e)+"..."}extractSnippetAround(t,e,r){let i=Math.max(0,e-r),n=Math.min(t.length,e+r),s=t.slice(i,n);return i>0&&(s="..."+s),n<t.length&&(s=s+"..."),s}getLineNumber(t,e){return t.slice(0,e).split(`
2875
- `).length}findHighlights(t,e){let r=[],i=this.tokenize(e.toLowerCase()),n=this.tokenize(t.toLowerCase());for(let s of i){let a=n.find(o=>o.includes(s)||s.includes(o));a&&!r.includes(a)&&r.push(a)}return r}findSemanticHighlights(t,e){let r=this.extractConcepts(t),i=e.toLowerCase();return r.filter(n=>i.includes(n)||n.includes(i))}fileToKey(t){return t.replace(/[/\\]/g,":").replace(/\./g,"_")}hashCode(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return e.toString(16)}cacheEmbedding(t,e){if(this.embeddingCache.size>=this.config.cacheSize){let r=this.embeddingCache.keys().next().value;r&&this.embeddingCache.delete(r)}this.embeddingCache.set(t,e)}cacheAnalysis(t,e){if(this.analysisCache.size>=this.config.cacheSize){let r=this.analysisCache.keys().next().value;r&&this.analysisCache.delete(r)}this.analysisCache.set(t,e)}};import{existsSync as rr,readFileSync as fT,readdirSync as yT}from"fs";import{join as ir,extname as vT}from"path";var MR=Object.freeze(["package-lock.json","npm-shrinkwrap.json","yarn.lock","pnpm-lock.yaml","bun.lockb","bun.lock","deno.lock","poetry.lock","Pipfile.lock","uv.lock","pdm.lock","Cargo.lock","go.sum","Gemfile.lock","composer.lock","mix.lock","pubspec.lock","packages.lock.json","Package.resolved","flake.lock","gradle.lockfile"]),FR=Object.freeze([".claude"]),Lr={timeout:6e4,excludeDirs:["node_modules","dist","build","coverage",".nyc_output",".next",".nuxt",".output","__pycache__",".venv","venv",".tox",".mypy_cache",".pytest_cache",".eggs","*.egg-info","target",".gradle","vendor",".bundle",".git",".svn",".hg",".agentic-qe"],excludeFiles:[...MR],excludeRootDirs:[...FR],testPatterns:["**/*.test.ts","**/*.spec.ts","**/*.test.js","**/*.spec.js"],enableCache:!0,cacheTTL:3e5};import{existsSync as So,readdirSync as LR,readFileSync as $R,statSync as OR}from"fs";import{join as Ro,extname as Eh}from"path";X();Yr();async function Ku(c,t={}){let e={...Lr,...t},r=await VR(c,e);if(r)return r;let i=await BR(c,e);return i||HR(c,e)}async function Ju(){return Promise.all(["cloc","tokei"].map(async c=>{let t=await Nt(c,["--version"],{cwd:process.cwd(),timeout:5e3});return t.error||t.status!==0?{name:c,available:!1}:{name:c,available:!0,version:t.stdout.trim().split(`
2876
- `)[0]}}))}function NR(c){return!c||c.length===0?null:`(^|[\\\\/])(${c.map(xh).join("|")})$`}function _R(c,t){if(!t||t.length===0)return null;let e="[\\\\/]",r=s=>s.split(/[\\/]+/).filter(Boolean).map(xh).join(e),i=r(c);return`^${/^[\\/]/.test(c)?e:""}${i}${e}(${t.map(r).join("|")})(${e}|$)`}function Ah(c,t){let e=t.excludeRootDirs??[];if(!e.includes(Kc))return e.filter(i=>So(Ro(c,i)));let r=e.filter(i=>i!==Kc&&So(Ro(c,i)));return[...Nm(c,t.excludeDirs),...r]}function xh(c){return c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function VR(c,t){try{let e=["--json",`--exclude-dir=${t.excludeDirs.join(",")}`],r=_R(c,Ah(c,t));r&&e.push("--fullpath",`--not-match-d=${r}`);let i=NR(t.excludeFiles);i&&e.push(`--not-match-f=${i}`),e.push(c);let n=await Nt("cloc",e,{cwd:process.cwd(),timeout:t.timeout,maxBuffer:10*1024*1024});return n.error||n.status!==0?null:zR(n.stdout,t.excludeDirs)}catch{return null}}function zR(c,t){let e=D(c),r={},i=0;for(let[n,s]of Object.entries(e)){if(n==="header"||n==="SUM")continue;let a=s;r[n]=a.code,i+=a.code}return{total:i,byLanguage:r,source:"cloc",excludedDirs:t}}async function BR(c,t){try{let e=["--output","json"];for(let i of t.excludeDirs)e.push("-e",i);for(let i of t.excludeFiles??[])e.push("-e",i);for(let i of Ah(c,t))e.push("-e",`/${i}`);e.push(".");let r=await Nt("tokei",e,{cwd:c,timeout:t.timeout,maxBuffer:10*1024*1024});return r.error||r.status!==0?null:qR(r.stdout,t.excludeDirs)}catch{return null}}function qR(c,t){let e=D(c),r={},i=0;for(let[n,s]of Object.entries(e)){if(n==="Total")continue;let a=s;r[n]=a.code,i+=a.code}return{total:i,byLanguage:r,source:"tokei",excludedDirs:t}}var GR={TypeScript:[".ts",".tsx"],JavaScript:[".js",".jsx",".mjs",".cjs"],Python:[".py",".pyw"],Rust:[".rs"],Go:[".go"],Java:[".java"],"C#":[".cs"],C:[".c",".h"],"C++":[".cpp",".hpp",".cc",".cxx"],Ruby:[".rb"],PHP:[".php"],Swift:[".swift"],Kotlin:[".kt",".kts"],Scala:[".scala"],Shell:[".sh",".bash",".zsh"],SQL:[".sql"],HTML:[".html",".htm"],CSS:[".css",".scss",".sass",".less"],JSON:[".json"],YAML:[".yaml",".yml"],Markdown:[".md",".markdown"],XML:[".xml"]};function jR(c){for(let[t,e]of Object.entries(GR))if(e.includes(c.toLowerCase()))return t;return null}function HR(c,t){let e={},r=0,i=new Set(t.excludeDirs),n=new Set(t.excludeFiles??[]),s=new Set(t.excludeRootDirs??[]),a=2*1024*1024;function o(l,u){if(!So(l)||u>20)return;let d;try{d=LR(l,{withFileTypes:!0})}catch{return}for(let m of d){let p=Ro(l,m.name);if(m.isDirectory()){if(i.has(m.name)||m.name.startsWith(".")||s.has(m.name)&&(l===c||So(Ro(l,Kr))))continue;o(p,u+1)}else if(m.isFile()){if(n.has(m.name))continue;let h=Eh(m.name),v=jR(h);if(v){try{if(OR(p).size>a)continue}catch{continue}let b=WR(p);e[v]=(e[v]||0)+b,r+=b}}}}return o(c,0),{total:r,byLanguage:e,source:"node-native",excludedDirs:t.excludeDirs}}function WR(c){try{let e=$R(c,"utf-8").split(`
2877
- `),r=Eh(c).toLowerCase(),i=0,n=!1,s=UR(r),a=QR(r),o=KR(r);for(let l of e){let u=l.trim();if(u==="")continue;if(a&&n){o&&u.includes(o)&&(n=!1);continue}if(a&&u.startsWith(a)){o&&!u.includes(o)&&(n=!0);continue}let d=!1;for(let m of s)if(u.startsWith(m)){d=!0;break}d||i++}return i}catch{return 0}}function UR(c){switch(c){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":case".java":case".c":case".h":case".cpp":case".hpp":case".cc":case".cxx":case".cs":case".go":case".rs":case".swift":case".kt":case".kts":case".scala":case".php":return["//","/*"];case".py":case".pyw":case".rb":case".sh":case".bash":case".zsh":case".yaml":case".yml":return["#"];case".sql":return["--","/*"];case".html":case".htm":case".xml":return["<!--"];case".css":case".scss":case".sass":case".less":return["/*"];default:return["//"]}}function QR(c){switch(c){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":case".java":case".c":case".h":case".cpp":case".hpp":case".cc":case".cxx":case".cs":case".go":case".rs":case".swift":case".kt":case".kts":case".scala":case".php":case".css":case".scss":case".sass":case".less":case".sql":return"/*";case".py":case".pyw":return'"""';case".html":case".htm":case".xml":return"<!--";default:return null}}function KR(c){switch(c){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":case".java":case".c":case".h":case".cpp":case".hpp":case".cc":case".cxx":case".cs":case".go":case".rs":case".swift":case".kt":case".kts":case".scala":case".php":case".css":case".scss":case".sass":case".less":case".sql":return"*/";case".py":case".pyw":return'"""';case".html":case".htm":case".xml":return"-->";default:return null}}import{spawn as YR,spawnSync as XR}from"child_process";import{createRequire as ZR}from"module";import{existsSync as Ee,mkdtempSync as eT,readFileSync as tr,readdirSync as tT,rmSync as rT,statSync as iT}from"fs";import{tmpdir as nT}from"os";import{join as fe,extname as sT,resolve as aT}from"path";X();import{rmSync as JR}from"node:fs";var Ci=new Set,Ph=["SIGINT","SIGTERM","SIGHUP"];function kh(){process.removeListener("exit",Xu);for(let c of Ph)process.removeListener(c,Dh[c])}function Xu(){let c=[...Ci];Ci.clear();for(let t of c)try{t.stopTree()}catch{}for(let t of new Set(c.map(e=>e.directory)))try{JR(t,{recursive:!0,force:!0})}catch{}}function Yu(c){Xu(),kh(),process.kill(process.pid,c)}var Dh={SIGINT:()=>Yu("SIGINT"),SIGTERM:()=>Yu("SIGTERM"),SIGHUP:()=>Yu("SIGHUP")};function Ih(c,t){if(Ci.size===0){process.once("exit",Xu);for(let r of Ph)process.on(r,Dh[r])}let e={directory:c,stopTree:t};return Ci.add(e),()=>{Ci.delete(e),Ci.size===0&&kh()}}Yr();Xc();async function Zu(c,t={}){let e={...Lr,...t};switch(Mh(c)){case"vitest":return oT(c,e);case"jest":return cT(c,e);case"cargo":return lT(c,e);case"pytest":return uT(c,e);case"go":return dT(c,e);default:return $r(c,e)}}function Mh(c){let t=fe(c,"package.json");if(Ee(t))try{let e=D(tr(t,"utf-8")),r={...e.dependencies||{},...e.devDependencies||{}};if(r.vitest)return"vitest";if(r.jest)return"jest";let i=e.scripts?.test||"";if(i.includes("vitest"))return"vitest";if(i.includes("jest"))return"jest"}catch{}return Ee(fe(c,"Cargo.toml"))?"cargo":Ee(fe(c,"pyproject.toml"))||Ee(fe(c,"setup.py"))||Ee(fe(c,"pytest.ini"))||Ee(fe(c,"requirements.txt"))?"pytest":Ee(fe(c,"go.mod"))?"go":"fallback"}async function ed(c){let t=Xr("npx"),e=[["vitest",t,["vitest","--version"],c,1e4],["jest",t,["jest","--version"],c,1e4],["cargo",["cargo",[]],["--version"],process.cwd(),5e3],["pytest",["pytest",[]],["--version"],process.cwd(),5e3],["go",["go",[]],["version"],process.cwd(),5e3]];return Promise.all(e.map(async([r,i,n,s,a])=>{let o=await Zn(i,n,s,a);return o===null?{name:r,available:!1}:{name:r,available:!0,version:o.trim()}}))}async function Zn(c,t,e,r,i){if(!c)return null;let[n,s]=c,a=await Nt(n,[...s,...t],{cwd:e,timeout:r,maxBuffer:i});return a.error||a.status!==0?null:a.stdout}async function oT(c,t){let e;try{let r=!1;try{let d=ZR(aT(c,"package.json")),m=D(tr(d.resolve("vitest/package.json"),"utf-8")),[p,h]=String(m.version).split(".").map(Number);r=p>4||p===4&&h>=1}catch{}e=eT(fe(nT(),"aqe-vitest-list-"));let i=d=>{try{if(iT(d).size>10*1024*1024)return;let m=D(tr(d,"utf-8"));if(Array.isArray(m)&&m.every(p=>p&&typeof p.name=="string"&&typeof p.file=="string"))return m.length;if(m&&typeof m.numTotalTests=="number")return m.numTotalTests}catch{}},n=async d=>{let m=fe(e,`${d}.json`),p=["vitest","list",`--json=${m}`];return d!=="legacy"&&p.push(d==="static"?"--static-parse":"--no-static-parse"),await new Promise(v=>{let b=process.platform==="win32",R=YR(b?`npx vitest list --json="%AQE_VITEST_LIST_JSON%"${d==="legacy"?"":d==="static"?" --static-parse":" --no-static-parse"}`:"npx",b?[]:p,{cwd:c,detached:!b,shell:b,env:{...process.env,AQE_VITEST_LIST_JSON:m},stdio:["ignore","pipe","pipe"]}),E=!1,T=0,I=()=>{if(R.pid)try{b?XR("taskkill",["/PID",String(R.pid),"/T","/F"],{stdio:"ignore",timeout:5e3}):process.kill(-R.pid,"SIGKILL")}catch{}},O=Ih(e,I),q=setTimeout(()=>{E=!0,I()},Math.min(t.timeout,3e4)),j=$=>{T+=$.length,T>10*1024*1024&&(E=!0,I())};R.stdout?.on("data",j),R.stderr?.on("data",j),R.once("error",()=>{clearTimeout(q),I(),O(),v(!1)}),R.once("close",$=>{clearTimeout(q),I(),O(),v(!E&&$===0)})})?i(m):void 0};if(!r){let d=await n("legacy");return d===void 0?$r(c,t):To(d,"vitest",c)}let s=await n("static"),a=fe(e,"static.json"),o=0;if(s!==void 0){try{let d=D(tr(a,"utf-8"));Array.isArray(d)&&(o=new Set(d.map(m=>m.file)).size)}catch{}if(s>1e3||o>100)return To(s,"vitest",c)}let u=await n("collection")??s;return u===void 0?$r(c,t):To(u,"vitest",c)}catch{return $r(c,t)}finally{if(e)try{rT(e,{recursive:!0,force:!0})}catch{}}}async function cT(c,t){try{let e=await Zn(Xr("npx"),["jest","--listTests"],c,Math.min(t.timeout,3e4),10485760);if(e===null)return $r(c,t);let r=e.split(`
2878
- `).map(i=>i.trim()).filter(i=>i.length>0&&Ee(i));if(r.length>0){let i=0;for(let n of r)i+=Fh(n);return To(i,"jest",c)}return $r(c,t)}catch{return $r(c,t)}}async function lT(c,t){try{let e=await Zn(["cargo",[]],["test","--","--list"],c,t.timeout);if(e===null)throw new Error("listing failed");let r=e.split(`
2879
- `).filter(o=>o.endsWith(": test")),i=r.length,n=r.filter(o=>o.includes("e2e")).length,s=r.filter(o=>!o.includes("e2e")&&o.includes("integration")).length,a=i-s-n;return{total:i,unit:a,integration:s,e2e:n,source:"cargo"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"cargo"}}}async function uT(c,t){try{let e=await Zn(["pytest",[]],["--collect-only","-q"],c,t.timeout);if(e===null)throw new Error("listing failed");let r=e.split(`
2880
- `).filter(o=>o.includes("::test_")||o.includes("::Test")),i=r.length,n=r.filter(o=>o.includes("e2e")||o.includes("end_to_end")).length,s=r.filter(o=>!o.includes("e2e")&&!o.includes("end_to_end")&&o.includes("integration")).length,a=i-s-n;return{total:i,unit:a,integration:s,e2e:n,source:"pytest"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"pytest"}}}async function dT(c,t){try{let e=await Zn(["go",[]],["test","-list",".*","./..."],c,t.timeout);if(e===null)throw new Error("listing failed");let r=e.split(`
2881
- `).filter(o=>o.startsWith("Test")),i=r.length,n=r.filter(o=>o.includes("E2E")).length,s=r.filter(o=>!o.includes("E2E")&&o.includes("Integration")).length,a=i-s-n;return{total:i,unit:a,integration:s,e2e:n,source:"go"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"go"}}}function $r(c,t){let e=0,r=0,i=0,n=0;function s(a){if(!Ee(a))return;let o=tT(a,{withFileTypes:!0});for(let l of o){let u=fe(a,l.name);if(l.isDirectory()){if(t.excludeDirs.includes(l.name)||(t.excludeRootDirs??[]).includes(l.name)&&(a===c||Ee(fe(a,Kr))))continue;s(u)}else if(l.isFile()&&mT(l.name)){let d=sT(l.name).toLowerCase(),m=0;[".ts",".tsx",".js",".jsx",".mjs"].includes(d)?m=Fh(u):d===".py"?m=pT(u):d===".rs"?m=gT(u):d===".go"&&(m=hT(u)),e+=m;let p=u.toLowerCase();p.includes("e2e")||p.includes("end-to-end")?n+=m:p.includes("integration")?i+=m:r+=m}}}return s(c),{total:e,unit:r,integration:i,e2e:n,source:"fallback"}}function mT(c){let t=c.toLowerCase();return t.includes(".test.")||t.includes(".spec.")||t.includes("_test.")||t.startsWith("test_")||t.endsWith("_test.ts")||t.endsWith("_test.js")||t.endsWith("_test.py")||t.endsWith("_test.go")||t.endsWith("_test.rs")}function Fh(c){try{let t=tr(c,"utf-8"),e=t.match(/\bit\s*\(/g)||[],r=t.match(/\btest\s*\(/g)||[];return e.length+r.length}catch{return 0}}function pT(c){try{return(tr(c,"utf-8").match(/\bdef\s+test_\w+\s*\(/g)||[]).length}catch{return 0}}function gT(c){try{let t=tr(c,"utf-8"),e=t.match(/#\[test\]/g)||[],r=t.match(/#\[tokio::test\]/g)||[],i=t.match(/#\[async_std::test\]/g)||[];return e.length+r.length+i.length}catch{return 0}}function hT(c){try{return(tr(c,"utf-8").match(/\bfunc\s+Test\w+\s*\(/g)||[]).length}catch{return 0}}function To(c,t,e){let r=c,i=0,n=0;return(Ee(fe(e,"tests","integration"))||Ee(fe(e,"test","integration"))||Ee(fe(e,"__tests__","integration")))&&(i=Math.floor(c*.2),r-=i),(Ee(fe(e,"tests","e2e"))||Ee(fe(e,"test","e2e"))||Ee(fe(e,"e2e"))||Ee(fe(e,"cypress")))&&(n=Math.floor(c*.1),r-=n),{total:c,unit:Math.max(0,r),integration:i,e2e:n,source:t}}var td=class{config;cache=new Map;cacheHits=0;cacheMisses=0;constructor(t={}){this.config={...Lr,...t}}async collectAll(t){let e=`all:${t}`;if(this.config.enableCache){let u=this.getFromCache(e);if(u)return u}let[r,i,n]=await Promise.all([this.countLOC(t),this.countTests(t),this.countPatterns(t,this.detectLanguage(t))]),s=[];r.source!=="fallback"&&s.push(r.source),i.source!=="fallback"&&s.push(i.source);let a=r.source==="fallback"?"approximate":"accurate",o=i.source==="fallback"?"approximate":"accurate",l={loc:r,tests:i,patterns:n,collectedAt:new Date,toolsUsed:s,accuracy:{loc:a,tests:o,overall:a==="accurate"&&o==="accurate"?"accurate":"approximate"}};return this.config.enableCache&&this.setInCache(e,l),l}async countLOC(t){let e=`loc:${t}`;if(this.config.enableCache){let i=this.getFromCache(e);if(i)return i}let r=await Ku(t,this.config);return this.config.enableCache&&this.setInCache(e,r),r}async countTests(t){let e=`tests:${t}`;if(this.config.enableCache){let i=this.getFromCache(e);if(i)return i}let r=await Zu(t,this.config);return this.config.enableCache&&this.setInCache(e,r),r}async countPatterns(t,e){let r=`patterns:${t}:${e}`;if(this.config.enableCache){let n=this.getFromCache(r);if(n)return n}let i=this.countPatternsInternal(t,e);return this.config.enableCache&&this.setInCache(r,i),i}async checkTools(){let[t,e]=await Promise.all([Ju(),ed(process.cwd())]);return[...t,...e]}clearCache(){this.cache.clear(),this.cacheHits=0,this.cacheMisses=0}getCacheStats(){return{hits:this.cacheHits,misses:this.cacheMisses,size:this.cache.size}}getFromCache(t){let e=this.cache.get(t);return e&&Date.now()-e.timestamp<this.config.cacheTTL?(this.cacheHits++,e.data):(this.cacheMisses++,null)}setInCache(t,e){this.cache.set(t,{data:e,timestamp:Date.now()})}detectLanguage(t){return rr(ir(t,"Cargo.toml"))?"rust":rr(ir(t,"go.mod"))?"go":rr(ir(t,"pyproject.toml"))||rr(ir(t,"requirements.txt"))?"python":rr(ir(t,"package.json"))?rr(ir(t,"tsconfig.json"))?"typescript":"javascript":"unknown"}countPatternsInternal(t,e){let r={},i=0,n=0,s=0,a=0,o=this.getPatternsForLanguage(e),l=new Set(this.config.excludeDirs),u=new Set(this.config.excludeRootDirs??[]);function d(m){if(!rr(m))return;let p=yT(m,{withFileTypes:!0});for(let h of p){let v=ir(m,h.name);if(h.isDirectory()){if(l.has(h.name)||u.has(h.name)&&(m===t||rr(ir(m,Kr))))continue;d(v)}else if(h.isFile()){let b=vT(h.name).toLowerCase();if(bT(b,e)){let C=wT(v,o);(C.unwraps>0||C.unsafeBlocks>0||C.todoComments>0||C.consoleStatements>0)&&(r[v]=C,i+=C.unwraps,n+=C.unsafeBlocks,s+=C.todoComments,a+=C.consoleStatements)}}}}return d(t),{unwraps:i,unsafeBlocks:n,todoComments:s,consoleStatements:a,byFile:r}}getPatternsForLanguage(t){switch(t){case"rust":return{unwrap:/\.unwrap\s*\(/g,unsafe:/\bunsafe\s*\{/g,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(println!|print!|eprintln!|eprint!|dbg!)\s*\(/g};case"python":return{unwrap:null,unsafe:null,todo:/#\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(print)\s*\(/g};case"go":return{unwrap:null,unsafe:/\bunsafe\./g,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(fmt\.Print|fmt\.Printf|fmt\.Println|log\.Print|log\.Printf|log\.Println)\s*\(/g};default:return{unwrap:null,unsafe:null,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\bconsole\.(log|debug|info|warn|error)\s*\(/g}}}};function bT(c,t){switch(t){case"rust":return c===".rs";case"python":return[".py",".pyw"].includes(c);case"go":return c===".go";case"typescript":return[".ts",".tsx"].includes(c);case"javascript":return[".js",".jsx",".mjs",".cjs"].includes(c);default:return[".ts",".tsx",".js",".jsx",".py",".rs",".go"].includes(c)}}function wT(c,t){try{let e=fT(c,"utf-8");return{unwraps:t.unwrap?(e.match(t.unwrap)||[]).length:0,unsafeBlocks:t.unsafe?(e.match(t.unsafe)||[]).length:0,todoComments:(e.match(t.todo)||[]).length,consoleStatements:(e.match(t.console)||[]).length}}catch{return{unwraps:0,unsafeBlocks:0,todoComments:0,consoleStatements:0}}}function Lh(c={}){return new td(c)}_();k();ge();yr();k();yr();k();yr();k();yr();k();ge();yr();k();var s3=300*1e3;vt();vt();_();vt();var v3=x.create("temporal-compression");k();_();Wi();var R3=x.create("ruvector-server-client");yb();import{Buffer as FT}from"buffer";var D3=FT.from("COGCNTNR","ascii");vt();vt();var $T={capacity:1e4,minCoherenceThreshold:.3,highTierThreshold:.8,mediumTierThreshold:.5,highTierWeight:3,mediumTierWeight:1.5,lowTierWeight:1},rd=class{config;cusumDetector;buffer;totalSeen=0;totalAdmitted=0;totalRejected=0;totalEvicted=0;totalSampled=0;constructor(t){this.config={...$T,...t},this.cusumDetector=new _c({threshold:this.config.cusumConfig?.threshold??5,slack:this.config.cusumConfig?.slack??.5,resetOnAlarm:!1,warmupSamples:20}),this.buffer=[]}admit(t,e,r){this.totalSeen++;let i=this.getEffectiveThreshold();if(r<i)return this.totalRejected++,!1;let n=this.classifyTier(r),s={id:t,data:e,coherenceScore:r,tier:n,admittedAt:Date.now(),replayCount:0};if(this.buffer.length<this.config.capacity)return this.buffer.push(s),this.totalAdmitted++,!0;let a=Math.floor(Math.random()*this.totalAdmitted),o=this.getTierWeight(n),l=Math.floor(a/o);if(l<this.config.capacity){let u=this.selectEvictionTarget(l);return this.buffer[u]=s,this.totalEvicted++,this.totalAdmitted++,!0}return this.totalRejected++,!1}sample(t,e){if(this.buffer.length===0)return[];let r=e!==void 0?this.buffer.filter(a=>a.coherenceScore>=e):this.buffer;if(r.length===0)return[];if(t>=r.length){let a=[...r];for(let o of a)o.replayCount++;return this.totalSampled+=a.length,a}let i=r.map(a=>this.getTierWeight(a.tier)),n=[],s=new Set;for(;n.length<t&&s.size<r.length;){let a=0;for(let u=0;u<r.length;u++)s.has(u)||(a+=i[u]);if(a<=0)break;let o=Math.random()*a,l=-1;for(let u=0;u<r.length;u++)if(!s.has(u)&&(o-=i[u],o<=0)){l=u;break}if(l===-1){for(let u=0;u<r.length;u++)if(!s.has(u)){l=u;break}}l>=0&&(s.add(l),r[l].replayCount++,n.push(r[l]))}return this.totalSampled+=n.length,n}size(){return this.buffer.length}getStats(){let t={high:0,medium:0,low:0};for(let e of this.buffer)t[e.tier]++;return{size:this.buffer.length,capacity:this.config.capacity,totalAdmitted:this.totalAdmitted,totalRejected:this.totalRejected,totalEvicted:this.totalEvicted,tierCounts:t,totalSampled:this.totalSampled}}getByTier(t){return this.buffer.filter(e=>e.tier===t)}clear(){this.buffer.length=0,this.totalSeen=0,this.totalAdmitted=0,this.totalRejected=0,this.totalEvicted=0,this.totalSampled=0,this.cusumDetector.reset()}getCusumState(t){return this.cusumDetector.getState(t)}observeCoherence(t,e){return this.cusumDetector.update(t,e)}classifyTier(t){return t>=this.config.highTierThreshold?"high":t>=this.config.mediumTierThreshold?"medium":"low"}getTierWeight(t){switch(t){case"high":return this.config.highTierWeight;case"medium":return this.config.mediumTierWeight;case"low":return this.config.lowTierWeight}}getEffectiveThreshold(){let t=["retrieve","write","learn","act"],e=!1;for(let r of t)if(this.cusumDetector.getState(r).driftDetected){e=!0;break}return e?Math.min(this.config.minCoherenceThreshold*1.5,.9):this.config.minCoherenceThreshold}selectEvictionTarget(t){let e=Math.min(10,this.buffer.length),r=Math.max(0,t-Math.floor(e/2)),i=Math.min(this.buffer.length,r+e),n=t,s=this.buffer[t].coherenceScore;for(let a=r;a<i;a++)this.buffer[a].coherenceScore<s&&(s=this.buffer[a].coherenceScore,n=a);return n}};ge();var Si=x.create("code-intelligence/gnn");async function $h(c,t,e){try{for(let r of e)try{let i=await t.readFile(r);if(i.success&&i.value){let s={vector:await id(r,i.value),dimension:384,namespace:"code",text:i.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:r}};c.addEmbedding(s)}}catch(i){Si.error(`Failed to index ${r}:`,i instanceof Error?i:void 0)}Si.info(`Indexed ${e.length} code embeddings`)}catch(r){Si.error("Failed to index code embeddings:",r instanceof Error?r:void 0)}}async function id(c,t){let e=[],r=c.split(".").pop(),i=Eo(r||"");e.push(i%1e3/1e3),e.push(Math.min(1,t.length/1e4));let n=t.match(/function\s+\w+/g)||[],s=t.match(/class\s+\w+/g)||[];e.push(Math.min(1,(n.length+s.length)/50));let a=t.match(/import\s+.*from|require\s*\(/g)||[];e.push(Math.min(1,a.length/20));let o=t.match(/for\s*\(|while\s*\(/g)||[],l=t.match(/if\s*\(/g)||[];e.push(Math.min(1,(o.length+l.length)/30));let u=t.match(/\/\/.*|\/\*[\s\S]*?\*\//g)||[];e.push(Math.min(1,u.length/50));let d=Eo(t.slice(0,500));for(let m=e.length;m<384;m++)e.push(d*(m+1)%1e4/1e4);return e.slice(0,384)}async function Oh(c,t){try{let r={vector:await id("query",t),dimension:384,namespace:"code",text:t,timestamp:Date.now(),quantization:"none"};return c.search(r,{limit:10,namespace:"code"}).map(n=>({file:n.metadata?.path??`file-${n.id}`,similarity:1-n.distance}))}catch(e){return Si.error("Failed to search with GNN:",e instanceof Error?e:void 0),[]}}async function Nh(c,t,e){try{for(let r of e.changedFiles){let i=await t.readFile(r);if(i.success&&i.value){let s={vector:await id(r,i.value),dimension:384,namespace:"code",text:i.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:r}},a=c.search(s,{limit:5,namespace:"code"});Si.info(`Found ${a.length} semantically similar files to ${r}`)}}}catch(r){Si.error("Failed to enhance impact analysis:",r instanceof Error?r:void 0)}}function _h(c,t){let e=new Map,r=new Map;for(let i of c)e.set(i.file,i.score),r.set(i.file,i);for(let i of t){let n=e.get(i.file);n!==void 0?e.set(i.file,(n+i.similarity)/2):(e.set(i.file,i.similarity*.8),r.set(i.file,{file:i.file,snippet:"",score:i.similarity*.8,highlights:[]}))}return Array.from(r.values()).map(i=>({...i,score:e.get(i.file)??i.score})).sort((i,n)=>n.score-i.score).slice(0,20)}function Eo(c){let t=0;for(let e=0;e<c.length;e++)t=(t<<5)-t+c.charCodeAt(e),t=t|0;return Math.abs(t)}_();k();var pt=x.create("code-intelligence/hypergraph");async function Vh(c,t,e){try{let r=await c.findUntestedFunctions();if(pt.info(`[CodeIntelligence] Found ${r.length} untested functions via hypergraph`),e){let i=N("code-intelligence.UntestedFunctionsFound","code-intelligence",{count:r.length,functions:r.slice(0,10).map(n=>({name:n.name,file:n.filePath,complexity:n.complexity}))});await t.publish(i)}return{success:!0,value:r}}catch(r){let i=y(r);return pt.error("Failed to find untested functions:"),g(i)}}async function zh(c,t,e,r){if(t.length===0)return{success:!0,value:[]};try{let i=await c.findImpactedTests(t);if(pt.info(`[CodeIntelligence] Found ${i.length} impacted tests for ${t.length} changed files via hypergraph`),r){let n=N("code-intelligence.ImpactedTestsFound","code-intelligence",{changedFiles:t,testCount:i.length,tests:i.slice(0,10).map(s=>({name:s.name,file:s.filePath}))});await e.publish(n)}return{success:!0,value:i}}catch(i){let n=y(i);return pt.error("Failed to find impacted tests:"),g(n)}}async function Bh(c,t,e,r){try{let i=await c.findCoverageGaps(t);if(pt.info(`[CodeIntelligence] Found ${i.length} coverage gaps (functions with <=${t}% coverage) via hypergraph`),r){let n=N("code-intelligence.CoverageGapsFound","code-intelligence",{maxCoverage:t,gapCount:i.length,gaps:i.slice(0,10).map(s=>({name:s.name,file:s.filePath,coverage:s.coverage,complexity:s.complexity}))});await e.publish(n)}return{success:!0,value:i}}catch(i){let n=y(i);return pt.error("Failed to find coverage gaps:"),g(n)}}async function qh(c,t,e,r,i){try{pt.info(`[CodeIntelligence] Building hypergraph from ${t.files.length} indexed files`);let n=await c.buildFromIndexResult(t);if(pt.info(`[CodeIntelligence] Hypergraph built: ${n.nodesCreated} nodes created, ${n.nodesUpdated} nodes updated, ${n.edgesCreated} edges created (${n.durationMs}ms)`),await e.set("hypergraph:build:latest",{timestamp:new Date().toISOString(),...n},{namespace:"code-intelligence",persist:!0}),i){let s=N("code-intelligence.HypergraphBuilt","code-intelligence",{nodesCreated:n.nodesCreated,nodesUpdated:n.nodesUpdated,edgesCreated:n.edgesCreated,durationMs:n.durationMs,errorCount:n.errors.length});await r.publish(s)}return{success:!0,value:n}}catch(n){let s=y(n);return pt.error("Failed to build hypergraph:"),g(s)}}async function Gh(c,t,e){try{let r=await c.findImpactedTests(t.changedFiles),i=new Set([...e.impactedTests,...r.map(a=>a.filePath||a.name)]),n=e.riskLevel;if(r.length>e.impactedTests.length){let a=e.directImpact.length+e.transitiveImpact.length;a>10&&i.size>20?n="critical":a>5&&i.size>10&&(n="high")}let s=[...e.recommendations];return r.length>0&&s.push(`Hypergraph analysis found ${r.length} additional test(s) to run`),{...e,impactedTests:Array.from(i),riskLevel:n,recommendations:s}}catch(r){return pt.error("Failed to enhance impact with hypergraph:",r instanceof Error?r:void 0),e}}_();var Ri=x.create("code-intelligence/consensus");async function jh(c,t,e,r){let i=U({id:w(),type:"code-pattern-detection",confidence:t,description:`Verify code pattern: ${c.name} (${c.type}) at ${c.location}`,payload:c,detectedBy:"code-intelligence-coordinator",severity:t>.9?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Ri.info(`Code pattern '${c.name}' verified by consensus`),!0):(Ri.warn(`Code pattern '${c.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Hh(c,t,e,r){let i=U({id:w(),type:"impact-analysis",confidence:t,description:`Verify impact analysis: ${c.changedFiles.length} files, risk=${c.riskLevel}, ${c.impactedTests.length} tests`,payload:c,detectedBy:"code-intelligence-coordinator",severity:c.riskLevel==="critical"||c.riskLevel==="high"?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Ri.info(`Impact analysis verified by consensus (risk=${c.riskLevel})`),!0):(Ri.warn(`Impact analysis NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Wh(c,t,e,r){let i=U({id:w(),type:"dependency-mapping",confidence:t,description:`Verify dependency: ${c.source} -> ${c.targets.length} targets (${c.type})`,payload:c,detectedBy:"code-intelligence-coordinator",severity:t>.85?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Ri.info("Dependency mapping verified by consensus"),!0):(Ri.warn(`Dependency mapping NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}var XT={maxConcurrentWorkflows:5,defaultTimeout:12e4,publishEvents:!0,enableIncrementalIndex:!0,enableGNN:!0,enableSONA:!0,enableMetricCollector:!0,enableHypergraph:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},ce=x.create("code-intelligence"),ts=class extends ie{constructor(e,r,i,n={},s){let a={...XT,...n};super(e,"code-intelligence",a,{verifyFindingTypes:["code-pattern-detection","impact-analysis","dependency-mapping"]});this.memory=r;this.agentCoordinator=i;this.knowledgeGraph=new _t({memory:r,llmRouter:s}),this.semanticAnalyzer=new Fr(r),this.impactAnalyzer=new rn(r,this.knowledgeGraph),this.fileReader=new it({projectRoot:Ce()}),this.productFactorsBridge=new Co(e,r,{publishEvents:this.config.publishEvents,relationshipResolver:Th(o=>new _t({memory:r,llmRouter:s},{basePath:o}))})}memory;agentCoordinator;knowledgeGraph;semanticAnalyzer;impactAnalyzer;fileReader;gnnIndex;sonaEngine;rlInitialized=!1;metricCollector;hypergraph;hypergraphDb;productFactorsBridge;async onInitialize(){this.subscribeToEvents(),await this.loadWorkflowState(),(this.config.enableGNN||this.config.enableSONA)&&await this.initializeRLIntegrations(),this.config.enableMetricCollector&&(this.metricCollector=Lh({enableCache:!0,cacheTTL:3e5}),ce.info("MetricCollector initialized for real code metrics")),this.config.enableHypergraph&&await this.initializeHypergraph(),await this.productFactorsBridge.initialize()}async initializeHypergraph(){try{let{openDatabase:e}=await import("./safe-db-PE6G3L55.js"),r=await import("fs"),i=await import("path"),{findProjectRoot:n}=await import("./unified-memory-AGDZQ5XD.js"),s=n(),a=process.env.AQE_MEMORY_BACKEND==="memory",o=a?":memory:":this.config.hypergraphDbPath||i.join(s,".agentic-qe","memory.db");if(!a){let l=i.dirname(o);r.existsSync(l)||r.mkdirSync(l,{recursive:!0})}this.hypergraphDb=e(o),this.hypergraph=await Ns({db:this.hypergraphDb,maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:this.config.enableGNN}),ce.info(`Hypergraph Engine initialized at ${o}`)}catch(e){let r=e instanceof Error?e.message:String(e);if(ce.warn(`Hypergraph Engine initialization failed (feature degraded): ${r}`),this.hypergraph=void 0,this.hypergraphDb=void 0,this.config.publishEvents){let i=N("code-intelligence.HypergraphDegraded","code-intelligence",{reason:r});this.eventBus.publish(i).catch(()=>{})}}}async initializeRLIntegrations(){try{if(this.config.enableGNN&&(Wc(),this.gnnIndex=Ds.getInstance("code-intelligence",{M:16,efConstruction:200,efSearch:50,dimension:384,metric:"cosine"}),this.gnnIndex.initializeIndex("code"),this.gnnIndex.initializeIndex("test")),this.config.enableSONA)try{this.sonaEngine=await De({domain:"code-intelligence",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.6}),ce.info("PersistentSONAEngine initialized for code pattern learning")}catch(e){ce.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),this.sonaEngine=void 0}this.rlInitialized=!0}catch(e){throw ce.error("Failed to initialize RL integrations:",e instanceof Error?e:void 0),e}}async onDispose(){if(await this.saveWorkflowState(),this.gnnIndex&&Ds.closeInstance("code-intelligence"),this.sonaEngine)try{await this.sonaEngine.close(),this.sonaEngine=void 0}catch(e){ce.error("Error closing SONA engine:",e instanceof Error?e:void 0)}if(this.hypergraphDb){try{this.hypergraphDb.close()}catch(e){ce.error("Error closing hypergraph database:",e instanceof Error?e:void 0)}this.hypergraphDb=void 0}this.hypergraph=void 0,await this.productFactorsBridge.dispose()}getActiveWorkflows(){return super.getActiveWorkflows()}async index(e){let r=Wm(e.paths,"paths","Invalid index payload",Number.POSITIVE_INFINITY);if(!r.success)return r;let i=w();try{if(this.startWorkflow(i,"index"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ce.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return g(new Error("Indexing paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return g(new Error("Agent limit reached, cannot spawn indexing agents"));let n=await this.spawnIndexerAgent(i,e);if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);this.addAgentToWorkflow(i,n.value),this.updateWorkflowProgress(i,10);let s=await this.knowledgeGraph.index(e);if(s.success&&s.value.filesIndexed===0&&e.paths.length>0){let a=Um(e.paths.length,s.value.skipped??[],s.value.errors);return this.failWorkflow(i,a.message),await this.agentCoordinator.stop(n.value),g(a)}if(s.success){this.updateWorkflowProgress(i,40);let a=new Set([...(s.value.skipped??[]).map(l=>l.path),...s.value.errors.map(l=>l.file)]),o=e.paths.filter(l=>!a.has(l));if(this.config.enableGNN&&this.gnnIndex&&o.length>0&&await this.indexCodeEmbeddings(o),this.updateWorkflowProgress(i,60),this.config.enableMetricCollector&&this.metricCollector&&o.length>0){let l=this.getProjectRootFromPaths(o,e.target);l?await this.collectProjectMetrics(l):ce.debug("Skipping project metrics: no project root resolved (filesystem root or no paths)")}if(this.updateWorkflowProgress(i,70),o.length>0&&await this.indexForSemanticSearch(o),this.updateWorkflowProgress(i,85),this.config.enableHypergraph&&this.hypergraph&&o.length>0)try{let l=await this.buildCodeIndexResultFromPaths(o);if(l.files.length>0){await this.hypergraph.buildFromIndexResult(l),ce.info(`Hypergraph rebuilt from ${l.files.length} indexed files`);try{let u=await this.hypergraph.synthesizeTestCoverage();(u.testsTagged>0||u.coversCreated>0)&&ce.info(`Test coverage synthesized: tests_tagged=${u.testsTagged} covers_created=${u.coversCreated}`)}catch(u){ce.warn(`Test coverage synthesis skipped: ${u instanceof Error?u.message:u}`)}}}catch(l){ce.warn(`Hypergraph rebuild skipped: ${l instanceof Error?l.message:l}`)}this.updateWorkflowProgress(i,100),this.completeWorkflow(i),this.config.publishEvents&&await this.publishKnowledgeGraphUpdated(s.value)}else this.failWorkflow(i,s.error.message);return await this.agentCoordinator.stop(n.value),s}catch(n){let s=y(n);return this.failWorkflow(i,s.message),g(s)}}async search(e){let r=w();try{this.startWorkflow(r,"search");let i=await this.spawnSearchAgent(r,e);if(i.success&&this.addAgentToWorkflow(r,i.value),this.config.enableSONA&&this.sonaEngine){let a=await this.adaptSearchPattern(e);a.success&&a.pattern&&ce.info(`Adapted search pattern with ${a.similarity.toFixed(3)} similarity`)}let n=[];this.config.enableGNN&&this.gnnIndex&&(n=await this.searchCodeWithGNN(e));let s=await this.semanticAnalyzer.search(e);return s.success?(n.length>0&&(s.value.results=this.mergeSearchResults(s.value.results,n)),this.completeWorkflow(r),this.config.publishEvents&&await this.publishSemanticSearchCompleted(e,s.value)):this.failWorkflow(r,s.error.message),i.success&&await this.agentCoordinator.stop(i.value),s}catch(i){let n=y(i);return this.failWorkflow(r,n.message),g(n)}}async analyzeImpact(e){let r=w();try{if(this.startWorkflow(r,"impact"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ce.warn("Topology degraded, using conservative impact analysis"),this.minCutMixin.shouldPauseOperations())return g(new Error("Impact analysis paused: topology is in critical state"));let i=await this.spawnImpactAnalyzerAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),g(i.error);this.addAgentToWorkflow(r,i.value),this.updateWorkflowProgress(r,20),this.config.enableGNN&&this.gnnIndex&&await this.enhanceImpactAnalysisWithGNN(e);let n=await this.impactAnalyzer.analyzeImpact(e);if(n.success){this.updateWorkflowProgress(r,80);let s=n.value;return this.config.enableHypergraph&&this.hypergraph&&(s=await this.enhanceImpactWithHypergraph(e,n.value)),this.updateWorkflowProgress(r,100),this.completeWorkflow(r),this.config.enableSONA&&this.sonaEngine&&await this.storeImpactPattern(e,s),this.config.publishEvents&&await this.publishImpactAnalysisCompleted(e,s),{success:!0,value:s}}else this.failWorkflow(r,n.error.message);return await this.agentCoordinator.stop(i.value),n}catch(i){let n=y(i);return this.failWorkflow(r,n.message),g(n)}}async mapDependencies(e){let r=w();try{this.startWorkflow(r,"dependency");let i=await this.knowledgeGraph.mapDependencies(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){let n=y(i);return this.failWorkflow(r,n.message),g(n)}}async queryKG(e){let r=w();try{this.startWorkflow(r,"query");let i=await this.knowledgeGraph.query(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){let n=y(i);return this.failWorkflow(r,n.message),g(n)}}async indexCodeEmbeddings(e){!this.gnnIndex||!this.rlInitialized||await $h(this.gnnIndex,this.fileReader,e)}async searchCodeWithGNN(e){return!this.gnnIndex||!this.rlInitialized?[]:Oh(this.gnnIndex,e.query)}async enhanceImpactAnalysisWithGNN(e){!this.gnnIndex||!this.rlInitialized||await Nh(this.gnnIndex,this.fileReader,e)}async adaptSearchPattern(e){if(!this.sonaEngine||!this.rlInitialized)return{success:!1,pattern:null,similarity:0};try{let r=Array.isArray(e.filters)?e.filters.find(s=>s.field==="language")?.value:void 0,i={id:`search-${e.type}`,features:[e.query.length,e.type==="semantic"?1:0,e.type==="exact"?1:0,r==="typescript"?1:0,r==="javascript"?1:0]},n=await this.sonaEngine.adaptPattern(i,"coverage-optimization","code-intelligence");return{success:n.success,pattern:n.pattern,similarity:n.similarity}}catch(r){return ce.error("Failed to adapt search pattern:",r instanceof Error?r:void 0),{success:!1,pattern:null,similarity:0}}}async storeImpactPattern(e,r){if(!(!this.sonaEngine||!this.rlInitialized))try{let i={id:`impact-${e.changedFiles.join(",")}`,features:[e.changedFiles.length,e.depth||1,r.directImpact.length,r.transitiveImpact.length,r.impactedTests.length,r.riskLevel==="high"?1:r.riskLevel==="medium"?.5:0]},n={type:"analyze-impact",value:r.riskLevel},s={reward:r.riskLevel==="high"?.8:r.riskLevel==="medium"?.5:.3,success:r.impactedTests.length>0,quality:(r.directImpact.length+r.transitiveImpact.length)/100},a=this.sonaEngine.createPattern(i,n,s,"coverage-optimization","code-intelligence",{changedFiles:e.changedFiles,impactCount:r.directImpact.length+r.transitiveImpact.length,testImpactCount:r.impactedTests.length});ce.info(`Stored impact pattern ${a.id}`)}catch(i){ce.error("Failed to store impact pattern:",i instanceof Error?i:void 0)}}mergeSearchResults(e,r){return _h(e,r)}hashCode(e){return Eo(e)}async spawnIndexerAgent(e,r){let i={name:`kg-indexer-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["indexing","ast-parsing","graph-building"],config:{workflowId:e,paths:r.paths,incremental:r.incremental}};return this.agentCoordinator.spawn(i)}async spawnSearchAgent(e,r){let i={name:`semantic-search-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["semantic-search","vector-similarity",r.type],config:{workflowId:e,query:r.query,type:r.type}};return this.agentCoordinator.spawn(i)}async spawnImpactAnalyzerAgent(e,r){let i={name:`impact-analyzer-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["impact-analysis","dependency-traversal","risk-assessment"],config:{workflowId:e,changedFiles:r.changedFiles,depth:r.depth}};return this.agentCoordinator.spawn(i)}async publishKnowledgeGraphUpdated(e){let r={nodes:e.nodesCreated,edges:e.edgesCreated,filesIndexed:e.filesIndexed,duration:e.duration},i=N(Lt.KnowledgeGraphUpdated,"code-intelligence",r);await this.eventBus.publish(i)}async publishImpactAnalysisCompleted(e,r){let i={analysisId:w(),changedFiles:e.changedFiles,impactedFiles:[...r.directImpact.map(s=>s.file),...r.transitiveImpact.map(s=>s.file)],impactedTests:r.impactedTests,riskLevel:r.riskLevel},n=N(Lt.ImpactAnalysisCompleted,"code-intelligence",i);await this.eventBus.publish(n)}async publishSemanticSearchCompleted(e,r){let i=N(Lt.SemanticSearchCompleted,"code-intelligence",{query:e.query,type:e.type,resultCount:r.total,searchTime:r.searchTime});await this.eventBus.publish(i)}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("source-control.FilesChanged",this.handleFilesChanged.bind(this))}async handleTestRunCompleted(e){let r=e.payload;await this.memory.set(`code-intelligence:test-correlation:${r.runId}`,r,{namespace:"code-intelligence",ttl:86400})}async handleFilesChanged(e){if(!this.config.enableIncrementalIndex)return;let r=e.payload;r.files&&r.files.length>0&&await this.memory.set(`code-intelligence:pending-index:${Date.now()}`,{files:r.files,timestamp:new Date().toISOString()},{namespace:"code-intelligence",ttl:3600})}async indexForSemanticSearch(e){let r=e.slice(0,100);for(let i of r)try{let n=await this.fileReader.readFile(i);n.success&&n.value&&await this.semanticAnalyzer.indexCode(i,n.value)}catch{}}async loadWorkflowState(){let e=await this.memory.get("code-intelligence:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("code-intelligence:coordinator:workflows",e,{namespace:"code-intelligence",persist:!0})}async generateC4Diagrams(e,r){let i=w();try{this.startWorkflow(i,"query");let n={projectPath:e,detectExternalSystems:r?.detectExternalSystems??!0,analyzeComponents:r?.analyzeComponents??!0,analyzeCoupling:r?.analyzeCoupling??!0,includeContext:r?.includeContext??!0,includeContainer:r?.includeContainer??!0,includeComponent:r?.includeComponent??!0,includeDependency:r?.includeDependency??!1,excludePatterns:r?.excludePatterns};this.updateWorkflowProgress(i,20);let s=await this.productFactorsBridge.requestC4Diagrams(n);return s.success?(this.updateWorkflowProgress(i,80),await this.storeC4DiagramsInMemory(e,s.value),this.updateWorkflowProgress(i,100),this.completeWorkflow(i),ce.info(`[CodeIntelligenceCoordinator] C4 diagrams generated for ${e}: ${s.value.components.length} components, ${s.value.externalSystems.length} external systems`)):this.failWorkflow(i,s.error.message),s}catch(n){let s=y(n);return this.failWorkflow(i,s.message),g(s)}}getProductFactorsBridge(){return this.productFactorsBridge}async storeC4DiagramsInMemory(e,r){let i=`c4-diagrams:latest:${this.hashCode(e)}`;await this.memory.set(i,r,{namespace:"code-intelligence",persist:!0,ttl:3600}),await this.memory.set(`c4-components:${this.hashCode(e)}`,r.components,{namespace:"code-intelligence",ttl:3600}),await this.memory.set(`c4-external-systems:${this.hashCode(e)}`,r.externalSystems,{namespace:"code-intelligence",ttl:3600})}async collectProjectMetrics(e){if(!this.config.enableMetricCollector||!this.metricCollector)return g(new Error("MetricCollector is not enabled"));try{ce.info(`Collecting real metrics for ${e}`);let r=await this.metricCollector.collectAll(e),i=r.toolsUsed.length>0?r.toolsUsed.join(", "):r.loc.source==="node-native"?"node-native":"fallback";if(ce.info(`[CodeIntelligence] Real metrics collected: ${r.loc.total} LOC, ${r.tests.total} tests, tools: ${i}`),r.loc.source==="node-native"&&ce.info("[CodeIntelligence] Using Node.js-native line counter (no cloc/tokei needed)"),await this.storeProjectMetricsInMemory(e,r),this.config.publishEvents){let n=N("code-intelligence.MetricsCollected","code-intelligence",{projectPath:e,loc:r.loc.total,tests:r.tests.total,toolsUsed:r.toolsUsed});await this.eventBus.publish(n)}return{success:!0,value:r}}catch(r){let i=y(r);return ce.error("Failed to collect metrics:"),g(i)}}async storeProjectMetricsInMemory(e,r){let i=`project-metrics:latest:${this.hashCode(e)}`;await this.memory.set(i,r,{namespace:"code-intelligence",persist:!0,ttl:300}),await this.memory.set(`loc-metrics:${this.hashCode(e)}`,r.loc,{namespace:"code-intelligence",ttl:300}),await this.memory.set(`test-metrics:${this.hashCode(e)}`,r.tests,{namespace:"code-intelligence",ttl:300})}getMetricCollector(){return this.metricCollector}getProjectRootFromPaths(e,r){return gh(e,{target:r})}isHypergraphEnabled(){return this.config.enableHypergraph&&this.hypergraph!==void 0}async findUntestedFunctions(){return this.hypergraph?Vh(this.hypergraph,this.eventBus,this.config.publishEvents):g(new Error("Hypergraph is not enabled or not initialized"))}async findImpactedTestsFromHypergraph(e){return this.hypergraph?zh(this.hypergraph,e,this.eventBus,this.config.publishEvents):g(new Error("Hypergraph is not enabled or not initialized"))}async findCoverageGapsFromHypergraph(e=50){return this.hypergraph?Bh(this.hypergraph,e,this.eventBus,this.config.publishEvents):g(new Error("Hypergraph is not enabled or not initialized"))}async buildHypergraphFromIndex(e){return this.hypergraph?qh(this.hypergraph,e,this.memory,this.eventBus,this.config.publishEvents):g(new Error("Hypergraph is not enabled or not initialized"))}getHypergraph(){return this.hypergraph}async enhanceImpactWithHypergraph(e,r){return this.hypergraph?Gh(this.hypergraph,e,r):r}async buildCodeIndexResultFromPaths(e){let{extractCodeIndex:r}=await import("./code-index-extractor-4GKKSETB.js");return r(e)}async verifyCodePatternDetection(e,r){return jh(e,r,this.consensusMixin,this.domainName)}async verifyImpactAnalysis(e,r){return Hh(e,r,this.consensusMixin,this.domainName)}async verifyDependencyMapping(e,r){return Wh(e,r,this.consensusMixin,this.domainName)}};k();var Ao=class extends te{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;knowledgeGraph=null;semanticAnalyzer=null;impactAnalyzer=null;pluginConfig;get name(){return"code-intelligence"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{index:this.index.bind(this),search:this.search.bind(this),analyzeImpact:this.analyzeImpact.bind(this),mapDependencies:this.mapDependencies.bind(this),getDependencies:this.mapDependencies.bind(this),queryKG:this.queryKG.bind(this),getMetrics:this.getMetrics.bind(this),getCoordinator:()=>this.coordinator,getKnowledgeGraph:()=>this.knowledgeGraph,getSemanticAnalyzer:()=>this.semanticAnalyzer,getImpactAnalyzer:()=>this.impactAnalyzer}}getTaskHandlers(){let e=new Map([["index",async r=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let i=r.paths;if(!i||i.length===0)return g(new Error("Invalid index payload: missing paths"));let n=r.language?[r.language]:r.languages;return this.coordinator.index({paths:i,languages:n,target:typeof r.target=="string"?r.target:void 0})}],["search",async r=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let i=r.query;return i?this.coordinator.search({query:i,type:r.type??"semantic",limit:r.limit}):g(new Error("Invalid search payload: missing query"))}],["analyze-impact",async r=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let i=r.changedFiles;return!i||i.length===0?g(new Error("Invalid analyze-impact payload: missing changedFiles")):this.coordinator.analyzeImpact({changedFiles:i})}],["query-dependencies",async r=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let i=r.file,s=r.files??(i?[i]:void 0);return!s||s.length===0?g(new Error("Invalid query-dependencies payload: missing file or files")):this.coordinator.mapDependencies({files:s,direction:r.direction??"both",depth:r.depth})}]]);return e.set("index-code",e.get("index")),e}async onInitialize(){this.knowledgeGraph=new _t({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.knowledgeGraph),this.semanticAnalyzer=new Fr(this.memory,this.pluginConfig.semanticAnalyzer),this.impactAnalyzer=new rn(this.memory,this.knowledgeGraph,this.pluginConfig.impactAnalyzer),this.coordinator=new ts(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.knowledgeGraph=null,this.semanticAnalyzer=null,this.impactAnalyzer=null}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestGenerated",this.handleTestGenerated.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("defect-intelligence.DefectPredicted",this.handleDefectPredicted.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"test-generation.TestGenerated":await this.handleTestGenerated(e);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;case"defect-intelligence.DefectPredicted":await this.handleDefectPredicted(e);break;default:break}}async index(e){this.ensureInitialized();try{let r=await this.coordinator.index(e);return r.success?this.trackSuccessfulOperation("index",r.value):this.trackFailedOperation("index",r.error),r}catch(r){return this.handleError(r)}}async search(e){this.ensureInitialized();try{let r=await this.coordinator.search(e);return r.success?this.trackSuccessfulOperation("search",r.value):this.trackFailedOperation("search",r.error),r}catch(r){return this.handleError(r)}}async analyzeImpact(e){this.ensureInitialized();try{let r=await this.coordinator.analyzeImpact(e);return r.success?this.trackSuccessfulOperation("impact",r.value):this.trackFailedOperation("impact",r.error),r}catch(r){return this.handleError(r)}}async mapDependencies(e){this.ensureInitialized();try{let r=await this.coordinator.mapDependencies(e);return r.success?this.trackSuccessfulOperation("dependency",r.value):this.trackFailedOperation("dependency",r.error),r}catch(r){return this.handleError(r)}}async queryKG(e){this.ensureInitialized();try{let r=await this.coordinator.queryKG(e);return r.success?this.trackSuccessfulOperation("query",r.value):this.trackFailedOperation("query",r.error),r}catch(r){return this.handleError(r)}}async getMetrics(){this.ensureInitialized();try{let e=this.getHealth();return{success:!0,value:{indexed:e.agents.total,queries:e.agents.idle,impacts:e.agents.active}}}catch(e){return this.handleError(e)}}async handleTestGenerated(e){let r=e.payload;await this.memory.set(`code-intelligence:test-mapping:${r.testId}`,{testFile:r.testFile,sourceFile:r.sourceFile,generatedAt:new Date().toISOString()},{namespace:"code-intelligence",ttl:86400*30})}async handleCoverageGap(e){if(!He(e.payload))return;let r=e.payload;await this.memory.set(`code-intelligence:coverage-gap:${r.gapId}`,r,{namespace:"code-intelligence",ttl:86400*7})}async handleDefectPredicted(e){let r=e.payload;await this.memory.set(`code-intelligence:defect-prediction:${r.predictionId}`,r,{namespace:"code-intelligence",ttl:86400*7})}ensureInitialized(){if(!this._initialized)throw new Error("CodeIntelligencePlugin is not initialized");if(!this.coordinator||!this.knowledgeGraph||!this.semanticAnalyzer||!this.impactAnalyzer)throw new Error("CodeIntelligencePlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,total:i.agents.total+1,idle:i.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,failed:i.agents.failed+1},errors:[...i.errors.slice(-9),r.message]})}};function nd(c,t,e,r,i){return new Ao(c,t,e,r,i)}mr();var sd=Ur;async function Uh(c,t=Ce()){return Im(c,{projectRoot:t,maxBytes:sd})}_();k();var xo={defaultRuleSets:["owasp-top-10","cwe-sans-25"],maxConcurrentScans:4,timeout:3e5,enableFalsePositiveDetection:!0,dastMaxDepth:5,dastActiveScanning:!1,enableLLMAnalysis:!0,llmModelTier:4,enableSemgrep:!0};import{createHash as Jh}from"node:crypto";import*as ut from"node:path";_();var ad=[{id:"sqli-string-concat",pattern:/query\s*\(\s*['"`].*\+.*['"`]\s*\)/g,category:"injection",severity:"critical",title:"SQL Injection via String Concatenation",description:"SQL query constructed using string concatenation with potentially untrusted input",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Use parameterized queries or prepared statements instead of string concatenation",fixExample:'db.query("SELECT * FROM users WHERE id = $1", [userId])'},{id:"sqli-template-literal",pattern:/execute\s*\(\s*`[^`]*\$\{[^}]+\}[^`]*`\s*\)/g,category:"injection",severity:"critical",title:"SQL Injection via Template Literal",description:"SQL query constructed using template literals with embedded expressions",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Use parameterized queries instead of template literals for SQL",fixExample:'db.execute("DELETE FROM users WHERE id = ?", [userId])'},{id:"sqli-raw-query",pattern:/\.raw\s*\(\s*['"`].*\+|\.raw\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"high",title:"SQL Injection via Raw Query",description:"Raw SQL query with potential user input interpolation",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Avoid raw queries with user input; use ORM methods or parameterized queries"},{id:"sqli-exec",pattern:/exec(?:ute)?(?:Sql|Query)?\s*\([^)]*\+[^)]*\)/gi,category:"injection",severity:"critical",title:"SQL Injection via Dynamic Execution",description:"Dynamic SQL execution with string concatenation detected",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Never concatenate user input into SQL queries"}],od=[{id:"xss-innerhtml",pattern:/\.innerHTML\s*=\s*[^'"`;\n]+/g,category:"xss",severity:"high",title:"XSS via innerHTML Assignment",description:"Direct innerHTML assignment with potentially unsanitized content",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Use textContent for text, or sanitize HTML with DOMPurify before innerHTML assignment",fixExample:"element.textContent = userInput; // or DOMPurify.sanitize(userInput)"},{id:"xss-document-write",pattern:/document\.write\s*\([^)]+\)/g,category:"xss",severity:"high",title:"XSS via document.write",description:"document.write() can execute scripts from untrusted data",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Avoid document.write(); use DOM manipulation methods instead",fixExample:"document.body.appendChild(document.createTextNode(text))"},{id:"xss-dangerously-set",pattern:/dangerouslySetInnerHTML\s*=\s*\{/g,category:"xss",severity:"medium",title:"React dangerouslySetInnerHTML Usage",description:"dangerouslySetInnerHTML bypasses React XSS protections",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Sanitize HTML content with DOMPurify before using dangerouslySetInnerHTML",fixExample:"dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(content) }}"},{id:"xss-eval",pattern:/eval\s*\([^)]+\)/g,category:"xss",severity:"critical",title:"Code Injection via eval()",description:"eval() executes arbitrary code and is a major security risk",owaspId:"A03:2021",cweId:"CWE-95",remediation:"Never use eval(); use JSON.parse() for JSON data or safer alternatives",fixExample:"JSON.parse(jsonString) // instead of eval(jsonString)"},{id:"xss-new-function",pattern:/new\s+Function\s*\([^)]+\)/g,category:"xss",severity:"critical",title:"Code Injection via Function Constructor",description:"Function constructor can execute arbitrary code like eval()",owaspId:"A03:2021",cweId:"CWE-95",remediation:"Avoid the Function constructor; use predefined functions instead"},{id:"xss-outerhtml",pattern:/\.outerHTML\s*=\s*[^'"`;\n]+/g,category:"xss",severity:"high",title:"XSS via outerHTML Assignment",description:"Direct outerHTML assignment with potentially unsanitized content",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Sanitize content before outerHTML assignment"}],cd=[{id:"secret-aws-access-key",pattern:/['"`]AKIA[0-9A-Z]{16}['"`]/g,category:"sensitive-data",severity:"critical",title:"AWS Access Key Detected",description:"Hardcoded AWS Access Key ID found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or AWS Secrets Manager for credentials",fixExample:"const accessKey = process.env.AWS_ACCESS_KEY_ID"},{id:"secret-aws-secret-key",pattern:/['"`][A-Za-z0-9/+=]{40}['"`]/g,category:"sensitive-data",severity:"critical",title:"Potential AWS Secret Key Detected",description:"Potential hardcoded AWS Secret Access Key found",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Store secrets in environment variables or secrets manager"},{id:"secret-openai-key",pattern:/['"`]sk-[a-zA-Z0-9]{48,}['"`]/g,category:"sensitive-data",severity:"critical",title:"OpenAI API Key Detected",description:"Hardcoded OpenAI API key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for API keys",fixExample:"const apiKey = process.env.OPENAI_API_KEY"},{id:"secret-generic-password",pattern:/password\s*[:=]\s*['"`][^'"`]{4,}['"`]/gi,category:"sensitive-data",severity:"high",title:"Hardcoded Password Detected",description:"Hardcoded password found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Never hardcode passwords; use environment variables or secrets manager",fixExample:"const password = process.env.DB_PASSWORD"},{id:"secret-api-key",pattern:/api[_-]?key\s*[:=]\s*['"`][a-zA-Z0-9_\-]{16,}['"`]/gi,category:"sensitive-data",severity:"high",title:"Hardcoded API Key Detected",description:"Hardcoded API key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for API keys",fixExample:"const apiKey = process.env.API_KEY"},{id:"secret-jwt",pattern:/['"`]eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+['"`]/g,category:"sensitive-data",severity:"high",title:"Hardcoded JWT Token Detected",description:"Hardcoded JWT token found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Generate JWT tokens dynamically; never hardcode them"},{id:"secret-private-key",pattern:/-----BEGIN\s+(RSA|EC|OPENSSH|DSA)?\s*PRIVATE\s+KEY-----/g,category:"sensitive-data",severity:"critical",title:"Private Key Detected",description:"Private key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Store private keys in secure key management systems, not in code"},{id:"secret-github-token",pattern:/['"`]ghp_[a-zA-Z0-9]{36}['"`]|['"`]github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59}['"`]/g,category:"sensitive-data",severity:"critical",title:"GitHub Token Detected",description:"Hardcoded GitHub personal access token found",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or GitHub Actions secrets"},{id:"secret-slack-token",pattern:/['"`]xox[baprs]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*['"`]/g,category:"sensitive-data",severity:"high",title:"Slack Token Detected",description:"Hardcoded Slack token found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for Slack tokens"},{id:"secret-generic-assignment",pattern:/\b\w*(?:SECRET|secret)(?:_KEY|_key|Key)?\s*[:=]\s*['"`][^'"`]{4,}['"`]/g,category:"sensitive-data",severity:"high",title:"Generic Secret Assignment Detected",description:"Hardcoded secret assignment (SECRET_KEY, JWT_SECRET, APP_SECRET, etc.) found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or a secrets manager instead of hardcoding secrets",fixExample:"const secretKey = process.env.SECRET_KEY"}],ld=[{id:"path-traversal-readfile",pattern:/(?:readFile|readFileSync)\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via File Read",description:"File read operation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate and sanitize file paths; use path.resolve() and check against base directory",fixExample:"const safePath = path.resolve(baseDir, path.basename(userInput))"},{id:"path-traversal-pattern",pattern:/\.\.\/.*\.\.\//g,category:"access-control",severity:"medium",title:"Path Traversal Pattern Detected",description:"Suspicious path traversal pattern (../) found in code",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate paths and ensure they resolve within expected directories"},{id:"path-traversal-writefile",pattern:/(?:writeFile|writeFileSync)\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via File Write",description:"File write operation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate file paths before writing; ensure path is within allowed directory"},{id:"path-traversal-createstream",pattern:/createReadStream\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via Stream",description:"Stream creation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate and sanitize file paths before creating streams"}],ud=[{id:"cmd-injection-exec",pattern:/exec\s*\([^)]*\+[^)]*\)|exec\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"critical",title:"Command Injection via exec()",description:"Shell command execution with unsanitized input",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Use execFile() with argument array instead of exec() with string concatenation",fixExample:'execFile("command", [arg1, arg2], callback)'},{id:"cmd-injection-spawn",pattern:/spawn\s*\(\s*[^,]+\+|spawn\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"critical",title:"Command Injection via spawn()",description:"Process spawn with potentially unsanitized command",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Use spawn with command and args array; validate inputs",fixExample:'spawn("command", [sanitizedArg1, sanitizedArg2])'},{id:"cmd-injection-shell-true",pattern:/spawn\s*\([^)]+,\s*\{[^}]*shell\s*:\s*true/g,category:"injection",severity:"high",title:"Dangerous Shell Option in spawn()",description:"spawn() with shell: true can enable command injection",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Avoid shell: true option; use direct command execution"}],dd=[{id:"misc-cors-wildcard",pattern:/cors\s*\(\s*\{[^}]*origin\s*:\s*['"]\*['"]/gi,category:"security-misconfiguration",severity:"medium",title:"Permissive CORS Configuration",description:"CORS allows all origins (*) which may expose sensitive data",owaspId:"A05:2021",cweId:"CWE-942",remediation:"Restrict CORS to specific trusted origins",fixExample:'cors({ origin: ["https://trusted-domain.com"] })'},{id:"misc-debug-enabled",pattern:/debug\s*[:=]\s*true|DEBUG\s*[:=]\s*['"]?true['"]?/gi,category:"security-misconfiguration",severity:"low",title:"Debug Mode Enabled",description:"Debug mode may expose sensitive information in production",owaspId:"A05:2021",cweId:"CWE-489",remediation:"Disable debug mode in production environments"},{id:"misc-ssl-disabled",pattern:/rejectUnauthorized\s*:\s*false|NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['"]?0['"]?/g,category:"security-misconfiguration",severity:"high",title:"TLS Certificate Validation Disabled",description:"Disabling TLS certificate validation exposes to MITM attacks",owaspId:"A05:2021",cweId:"CWE-295",remediation:"Always enable TLS certificate validation in production"},{id:"misc-helmet-missing",pattern:/app\.use\s*\(\s*express\s*\(\s*\)\s*\)/g,category:"security-misconfiguration",severity:"low",title:"Express App Without Security Headers",description:"Express app initialized without helmet or security headers",owaspId:"A05:2021",cweId:"CWE-693",remediation:"Use helmet middleware for security headers",fixExample:"app.use(helmet())"}],md=[{id:"deser-yaml-load",pattern:/yaml\.load\s*\([^)]+\)/g,category:"insecure-deserialization",severity:"high",title:"Unsafe YAML Deserialization",description:"yaml.load() can execute arbitrary code from untrusted YAML",owaspId:"A08:2021",cweId:"CWE-502",remediation:"Use yaml.safeLoad() or schema-constrained loading",fixExample:"yaml.load(content, { schema: yaml.SAFE_SCHEMA })"},{id:"deser-serialize-js",pattern:/serialize\s*\([^)]+\)|unserialize\s*\([^)]+\)/g,category:"insecure-deserialization",severity:"high",title:"Unsafe Serialization Function",description:"Node serialize/unserialize functions can execute arbitrary code",owaspId:"A08:2021",cweId:"CWE-502",remediation:"Use JSON.parse/stringify for serialization"}],pd=[{id:"auth-weak-jwt-secret",pattern:/jwt\.sign\s*\([^)]+,\s*['"][a-zA-Z0-9]{1,16}['"]/g,category:"broken-auth",severity:"high",title:"Weak JWT Secret",description:"JWT signed with a weak or short secret key",owaspId:"A07:2021",cweId:"CWE-327",remediation:"Use a strong, randomly generated secret of at least 256 bits"},{id:"auth-no-algorithm",pattern:/jwt\.verify\s*\([^)]+\)\s*(?!.*algorithm)/g,category:"broken-auth",severity:"medium",title:"JWT Without Algorithm Specification",description:"JWT verification without explicit algorithm can be exploited",owaspId:"A07:2021",cweId:"CWE-347",remediation:"Always specify the expected algorithm in JWT verification",fixExample:'jwt.verify(token, secret, { algorithms: ["HS256"] })'}],Po=[...ad,...od,...cd,...ld,...ud,...dd,...md,...pd],Ti=[{id:"owasp-top-10",name:"OWASP Top 10",description:"OWASP Top 10 most critical security risks",ruleCount:45,categories:["injection","broken-auth","sensitive-data","xxe","access-control","security-misconfiguration","xss","insecure-deserialization","vulnerable-components","insufficient-logging"]},{id:"cwe-sans-25",name:"CWE/SANS Top 25",description:"Most dangerous software errors",ruleCount:38,categories:["injection","xss","access-control","sensitive-data","broken-auth"]},{id:"nodejs-security",name:"Node.js Security",description:"Node.js specific security rules",ruleCount:25,categories:["injection","xss","sensitive-data","security-misconfiguration"]},{id:"typescript-security",name:"TypeScript Security",description:"TypeScript specific security rules",ruleCount:20,categories:["injection","xss","sensitive-data"]}];k();X();Pe();X();import{execFile as ZT}from"child_process";import{promisify as e0}from"util";import*as Kh from"path";var gd=e0(ZT),t0=["ERROR","WARNING","INFO","CRITICAL","HIGH","MEDIUM","LOW","EXPERIMENT","INVENTORY"];async function rs(){try{return await gd("semgrep",["--version"],{timeout:5e3}),!0}catch{return!1}}async function r0(){try{let{stdout:c}=await gd("semgrep",["--version"],{timeout:5e3});return c.trim()}catch{return null}}async function i0(c){let t={target:c.target||".",config:c.config||"auto",exclude:c.exclude||["node_modules",".git","dist","build","coverage"],maxFileSize:c.maxFileSize||5e6,timeout:c.timeout||300,verbose:c.verbose||!1};if(!await rs())return{success:!1,status:"unavailable",findings:[],errors:["Semgrep is unavailable."]};try{let r=["scan",`--config=${t.config}`,"--json",t.verbose?"--verbose":"--quiet",`--max-target-bytes=${t.maxFileSize}`];for(let o of t.exclude)r.push(`--exclude=${o}`);r.push(t.target);let i=(t.timeout??300)*1e3,{stdout:n,stderr:s}=await gd("semgrep",r,{timeout:i,maxBuffer:50*1024*1024,cwd:Kh.isAbsolute(t.target)?void 0:process.cwd()}),a=Qh(n);return s&&t.verbose&&(a.diagnostics=["Semgrep emitted diagnostic output."]),a.version=await r0()||void 0,a}catch(r){let i=r;if(typeof i.stdout=="string"&&i.stdout.length>0){let n=Qh(i.stdout);return i.code===1&&!i.killed&&!i.signal&&n.success&&n.findings.length>0?n:{...n,success:!1,status:"failed",errors:[...n.errors,"Semgrep process did not complete successfully."]}}return{success:!1,status:"failed",findings:[],errors:["Semgrep execution failed."]}}}function Qh(c){try{let t=D(c);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected a JSON object");let e=t.results??t.findings;if(!Array.isArray(e)||t.errors!==void 0&&!Array.isArray(t.errors))throw new Error("Missing or invalid result collection");let r=m=>!!m&&typeof m=="object"&&!Array.isArray(m),i=m=>m===void 0||typeof m=="string",n=m=>m===void 0||typeof m=="string"&&t0.includes(m),s=m=>m===void 0||r(m)&&["line","col"].every(p=>m[p]===void 0||typeof m[p]=="number"&&Number.isSafeInteger(m[p])&&m[p]>0),a=m=>m===void 0||r(m)&&["cwe","owasp","references"].every(p=>m[p]===void 0||Array.isArray(m[p])&&m[p].every(h=>typeof h=="string"))&&["category","description","fix","confidence"].every(p=>i(m[p])),o=m=>{if(!r(m))return!1;let p=m.check_id??m.rule_id;if(typeof m.path!="string"||m.path.length===0||typeof p!="string"||p.length===0||!s(m.start)||!s(m.end)||!i(m.message)||!n(m.severity)||!a(m.metadata))return!1;let h=m.extra;return h===void 0||r(h)&&["message","lines","fix"].every(v=>i(h[v]))&&n(h.severity)&&a(h.metadata)},l=e.filter(o),u=e.length-l.length,d=[];return t.errors?.length&&d.push(`Semgrep reported ${t.errors.length} analysis error(s).`),u&&d.push(`Semgrep returned ${u} malformed finding(s).`),{success:d.length===0,status:d.length===0?"completed":"partial",findings:l.map(m=>({check_id:m.check_id||m.rule_id||"unknown",path:m.path,start:{line:m.start?.line||1,col:m.start?.col||1},end:{line:m.end?.line||m.start?.line||1,col:m.end?.col||1},extra:{message:m.extra?.message||m.message||"Security issue detected",severity:m.extra?.severity||m.severity||"WARNING",lines:m.extra?.lines||"",metadata:{cwe:m.extra?.metadata?.cwe||m.metadata?.cwe,owasp:m.extra?.metadata?.owasp||m.metadata?.owasp,category:m.extra?.metadata?.category||m.metadata?.category,description:m.extra?.metadata?.description||m.metadata?.description,fix:m.extra?.metadata?.fix||m.extra?.fix,references:m.extra?.metadata?.references||m.metadata?.references,confidence:m.extra?.metadata?.confidence||m.metadata?.confidence}}})),errors:d}}catch{return{success:!1,status:"failed",findings:[],errors:["Invalid Semgrep output."]}}}async function ko(c,t,e){let r={"owasp-top-10":"p/owasp-top-ten","cwe-sans-25":"p/cwe-top-25","nodejs-security":"p/nodejs","typescript-security":"p/typescript","javascript-security":"p/javascript","react-security":"p/react","express-security":"p/express",secrets:"p/secrets","sql-injection":"p/sql-injection",xss:"p/xss","command-injection":"p/command-injection","path-traversal":"p/path-traversal"},i=t.map(n=>r[n]||`p/${n}`).join(",");return i0({...e,target:c,config:i||"auto"})}function n0(c){return{ERROR:"high",WARNING:"medium",INFO:"low",CRITICAL:"critical",HIGH:"high",MEDIUM:"medium",LOW:"low",EXPERIMENT:"low",INVENTORY:"low"}[c]||"medium"}function Do(c){return c.map(t=>({id:t.check_id,title:t.check_id.split(".").pop()||t.check_id,description:t.extra.message,severity:n0(t.extra.severity),file:t.path,line:t.start.line,column:t.start.col,snippet:t.extra.lines,cweId:t.extra.metadata?.cwe?.[0],owaspCategory:t.extra.metadata?.owasp?.[0],remediation:t.extra.metadata?.fix||"Review and fix the identified security issue",references:t.extra.metadata?.references||[]}))}var s0=x.create("security-compliance/sast-scanner"),Ei=class{config;memory;llmRouter;activeScans;constructor(t,e,r,i){this.config=t,this.memory=e,this.llmRouter=r,this.activeScans=i||new Map}async scanFiles(t){return this.scanWithRules(t,this.config.defaultRuleSets)}async scanWithRules(t,e){let r=w();try{if(t.length===0)return g(new Error("No files provided for scanning"));let i=Date.now(),n=Ti.filter(T=>e.includes(T.id));if(n.length===0)return g(new Error(`No valid rule sets found: ${e.join(", ")}`));if(e.filter(T=>!Ti.some(I=>I.id===T)).length>0)return g(new Error("Unknown rule sets requested; no scan executed."));this.activeScans.set(r,"running");let a=[...new Set(t.map(T=>ut.resolve(T.value)))],o=a.map(T=>he.create(T)),[l,u]=await Promise.all([this.runPatternScanning(o,n),this.runSemgrepScanning(o,e)]),d=this.mergeVulnerabilities(l.vulnerabilities,u.vulnerabilities),m=l.files.filter(T=>T.status==="analyzed"),p=m.reduce((T,I)=>T+I.analyzedLines,0),h=Date.now()-i,v=this.calculateSummary(d,m.length,h),b=this.getApplicablePatterns(n),C=m.length>0?[...new Set(b.map(T=>T.id))]:[],S={filesScanned:m.length,linesScanned:p,rulesApplied:C.length,rulesAppliedScope:"built-in-patterns"},R={id:"patterns",requested:!0,required:!0,scope:"requested-files",status:m.length===o.length?"completed":m.length>0?"partial":"failed",analyzedFiles:m.length,ruleIds:C,rulesetDigest:Jh("sha256").update(JSON.stringify(b.map(T=>({id:T.id,category:T.category,expression:T.pattern.source,flags:T.pattern.flags})))).digest("hex"),ruleCoverage:"known",errors:l.files.filter(T=>T.status==="unreadable").map(T=>T.reason||"File unreadable"),limitations:["Built-in pattern matching covers supported JavaScript and TypeScript inputs only."]},E={schemaVersion:1,completeness:m.length===o.length?"complete":m.length>0?"partial":"none",requestedFiles:o.length,requestedPaths:a,duplicateInputs:t.length-o.length,files:l.files,engines:[R,u.evidence],limitations:[...R.limitations,...u.evidence.limitations]};return await this.storeScanResults(r,"sast",d,v),this.activeScans.set(r,"completed"),f({scanId:r,vulnerabilities:d,summary:v,coverage:S,evidence:E})}catch(i){return this.activeScans.set(r,"failed"),g(y(i))}}async runPatternScanning(t,e){let r=[],i=[];for(let n of t){let s=await this.analyzeFile(n,e);r.push(...s.vulnerabilities),i.push(s.evidence)}return{vulnerabilities:r,files:i}}async runSemgrepScanning(t,e){let r=this.resolveTargetDirectory(t),i={id:"semgrep",requested:!!this.config.enableSemgrep,required:!1,status:"disabled",scope:"parent-directory",target:r,ruleCoverage:"unknown",errors:[],limitations:[]};if(!this.config.enableSemgrep)return{vulnerabilities:[],evidence:i};let n=["Optional Semgrep scans a parent directory; requested-file membership and executed-rule coverage are unverified."];try{if(!await rs())return{vulnerabilities:[],evidence:{...i,status:"unavailable",limitations:n,errors:["Semgrep is unavailable."]}};let s=await ko(r,e),a={...i,status:s.status||"unverified",version:s.version,errors:s.errors.length>0?[`Semgrep reported ${s.errors.length} execution error(s).`]:[],limitations:[...n,...s.diagnostics??[],...s.status?[]:["Legacy Semgrep adapter returned no execution disposition."]]};return{vulnerabilities:Do(s.findings).map(u=>({id:w(),cveId:void 0,title:u.title,description:`[semgrep] ${u.description}`,severity:u.severity,category:this.mapSemgrepCategory(u.owaspCategory),location:{file:u.file,line:u.line,column:u.column,snippet:u.snippet},remediation:{description:u.remediation,estimatedEffort:"moderate",automatable:!1},references:u.references})),evidence:a}}catch{return{vulnerabilities:[],evidence:{...i,status:"failed",limitations:n,errors:["Semgrep execution failed."]}}}}resolveTargetDirectory(t){if(t.length===0)return process.cwd();let e=ut.dirname(ut.resolve(t[0].value));for(let r of t.slice(1)){let i=ut.dirname(ut.resolve(r.value));for(;i!==e&&!i.startsWith(e.endsWith(ut.sep)?e:e+ut.sep);){let n=ut.dirname(e);if(n===e)break;e=n}}return e}mapSemgrepCategory(t){if(!t)return"injection";let e={A01:"access-control",A02:"sensitive-data",A03:"injection",A04:"insecure-deserialization",A05:"security-misconfiguration",A06:"vulnerable-components",A07:"broken-auth",A08:"insecure-deserialization",A09:"insufficient-logging",A10:"xxe"};for(let[r,i]of Object.entries(e))if(t.startsWith(r))return i;return"injection"}mergeVulnerabilities(t,e){if(e.length===0)return t;if(t.length===0)return e;let r=new Set(t.map(n=>`${n.location.file}:${n.location.line??0}:${n.category}`)),i=e.filter(n=>!r.has(`${n.location.file}:${n.location.line??0}:${n.category}`));return[...t,...i]}async getAvailableRuleSets(){let t=await this.memory.get("security:custom-rule-sets");return[...Ti,...t||[]]}async checkFalsePositive(t){try{if(!this.config.enableFalsePositiveDetection)return f({isFalsePositive:!1,confidence:0,reason:"False positive detection is disabled"});let e=await this.analyzeFalsePositive(t);return await this.memory.set(`security:fp-check:${t.id}`,{vulnerability:t,analysis:e},{namespace:"security-compliance",ttl:86400*30}),f(e)}catch(e){return g(y(e))}}getApplicablePatterns(t){let e=new Set(t.flatMap(r=>r.categories));return Po.filter(r=>e.has(r.category))}async analyzeFile(t,e){let r=[],i=t.value,n={path:i,engineId:"patterns",readLines:0,analyzedLines:0},s,a;try{let m=await Mm(i,{outsideRoot:"allow"});a=Jh("sha256").update(m).digest("hex"),s=m.toString("utf8")}catch(m){let p=m.code;return{vulnerabilities:[],evidence:{...n,status:"unreadable",reason:typeof p=="string"&&/^[A-Z0-9_]{1,32}$/.test(p)?p:"File unreadable"}}}let o=s.split(`
2875
+ `).length}findHighlights(t,e){let r=[],i=this.tokenize(e.toLowerCase()),n=this.tokenize(t.toLowerCase());for(let s of i){let a=n.find(o=>o.includes(s)||s.includes(o));a&&!r.includes(a)&&r.push(a)}return r}findSemanticHighlights(t,e){let r=this.extractConcepts(t),i=e.toLowerCase();return r.filter(n=>i.includes(n)||n.includes(i))}fileToKey(t){return t.replace(/[/\\]/g,":").replace(/\./g,"_")}hashCode(t){return IR("sha256").update(t,"utf8").digest("hex")}cacheEmbedding(t,e){if(this.embeddingCache.size>=this.config.cacheSize){let r=this.embeddingCache.keys().next().value;r&&this.embeddingCache.delete(r)}this.embeddingCache.set(t,e)}cacheAnalysis(t,e){if(this.analysisCache.size>=this.config.cacheSize){let r=this.analysisCache.keys().next().value;r&&this.analysisCache.delete(r)}this.analysisCache.set(t,e)}};import{existsSync as rr,readFileSync as yT,readdirSync as vT}from"fs";import{join as ir,extname as bT}from"path";var FR=Object.freeze(["package-lock.json","npm-shrinkwrap.json","yarn.lock","pnpm-lock.yaml","bun.lockb","bun.lock","deno.lock","poetry.lock","Pipfile.lock","uv.lock","pdm.lock","Cargo.lock","go.sum","Gemfile.lock","composer.lock","mix.lock","pubspec.lock","packages.lock.json","Package.resolved","flake.lock","gradle.lockfile"]),LR=Object.freeze([".claude"]),Lr={timeout:6e4,excludeDirs:["node_modules","dist","build","coverage",".nyc_output",".next",".nuxt",".output","__pycache__",".venv","venv",".tox",".mypy_cache",".pytest_cache",".eggs","*.egg-info","target",".gradle","vendor",".bundle",".git",".svn",".hg",".agentic-qe"],excludeFiles:[...FR],excludeRootDirs:[...LR],testPatterns:["**/*.test.ts","**/*.spec.ts","**/*.test.js","**/*.spec.js"],enableCache:!0,cacheTTL:3e5};import{existsSync as So,readdirSync as $R,readFileSync as OR,statSync as NR}from"fs";import{join as Ro,extname as Eh}from"path";X();Yr();async function Ku(c,t={}){let e={...Lr,...t},r=await zR(c,e);if(r)return r;let i=await qR(c,e);return i||WR(c,e)}async function Ju(){return Promise.all(["cloc","tokei"].map(async c=>{let t=await Nt(c,["--version"],{cwd:process.cwd(),timeout:5e3});return t.error||t.status!==0?{name:c,available:!1}:{name:c,available:!0,version:t.stdout.trim().split(`
2876
+ `)[0]}}))}function _R(c){return!c||c.length===0?null:`(^|[\\\\/])(${c.map(xh).join("|")})$`}function VR(c,t){if(!t||t.length===0)return null;let e="[\\\\/]",r=s=>s.split(/[\\/]+/).filter(Boolean).map(xh).join(e),i=r(c);return`^${/^[\\/]/.test(c)?e:""}${i}${e}(${t.map(r).join("|")})(${e}|$)`}function Ah(c,t){let e=t.excludeRootDirs??[];if(!e.includes(Kc))return e.filter(i=>So(Ro(c,i)));let r=e.filter(i=>i!==Kc&&So(Ro(c,i)));return[...Nm(c,t.excludeDirs),...r]}function xh(c){return c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function zR(c,t){try{let e=["--json",`--exclude-dir=${t.excludeDirs.join(",")}`],r=VR(c,Ah(c,t));r&&e.push("--fullpath",`--not-match-d=${r}`);let i=_R(t.excludeFiles);i&&e.push(`--not-match-f=${i}`),e.push(c);let n=await Nt("cloc",e,{cwd:process.cwd(),timeout:t.timeout,maxBuffer:10*1024*1024});return n.error||n.status!==0?null:BR(n.stdout,t.excludeDirs)}catch{return null}}function BR(c,t){let e=D(c),r={},i=0;for(let[n,s]of Object.entries(e)){if(n==="header"||n==="SUM")continue;let a=s;r[n]=a.code,i+=a.code}return{total:i,byLanguage:r,source:"cloc",excludedDirs:t}}async function qR(c,t){try{let e=["--output","json"];for(let i of t.excludeDirs)e.push("-e",i);for(let i of t.excludeFiles??[])e.push("-e",i);for(let i of Ah(c,t))e.push("-e",`/${i}`);e.push(".");let r=await Nt("tokei",e,{cwd:c,timeout:t.timeout,maxBuffer:10*1024*1024});return r.error||r.status!==0?null:GR(r.stdout,t.excludeDirs)}catch{return null}}function GR(c,t){let e=D(c),r={},i=0;for(let[n,s]of Object.entries(e)){if(n==="Total")continue;let a=s;r[n]=a.code,i+=a.code}return{total:i,byLanguage:r,source:"tokei",excludedDirs:t}}var jR={TypeScript:[".ts",".tsx"],JavaScript:[".js",".jsx",".mjs",".cjs"],Python:[".py",".pyw"],Rust:[".rs"],Go:[".go"],Java:[".java"],"C#":[".cs"],C:[".c",".h"],"C++":[".cpp",".hpp",".cc",".cxx"],Ruby:[".rb"],PHP:[".php"],Swift:[".swift"],Kotlin:[".kt",".kts"],Scala:[".scala"],Shell:[".sh",".bash",".zsh"],SQL:[".sql"],HTML:[".html",".htm"],CSS:[".css",".scss",".sass",".less"],JSON:[".json"],YAML:[".yaml",".yml"],Markdown:[".md",".markdown"],XML:[".xml"]};function HR(c){for(let[t,e]of Object.entries(jR))if(e.includes(c.toLowerCase()))return t;return null}function WR(c,t){let e={},r=0,i=new Set(t.excludeDirs),n=new Set(t.excludeFiles??[]),s=new Set(t.excludeRootDirs??[]),a=2*1024*1024;function o(l,u){if(!So(l)||u>20)return;let d;try{d=$R(l,{withFileTypes:!0})}catch{return}for(let m of d){let p=Ro(l,m.name);if(m.isDirectory()){if(i.has(m.name)||m.name.startsWith(".")||s.has(m.name)&&(l===c||So(Ro(l,Kr))))continue;o(p,u+1)}else if(m.isFile()){if(n.has(m.name))continue;let h=Eh(m.name),v=HR(h);if(v){try{if(NR(p).size>a)continue}catch{continue}let b=UR(p);e[v]=(e[v]||0)+b,r+=b}}}}return o(c,0),{total:r,byLanguage:e,source:"node-native",excludedDirs:t.excludeDirs}}function UR(c){try{let e=OR(c,"utf-8").split(`
2877
+ `),r=Eh(c).toLowerCase(),i=0,n=!1,s=QR(r),a=KR(r),o=JR(r);for(let l of e){let u=l.trim();if(u==="")continue;if(a&&n){o&&u.includes(o)&&(n=!1);continue}if(a&&u.startsWith(a)){o&&!u.includes(o)&&(n=!0);continue}let d=!1;for(let m of s)if(u.startsWith(m)){d=!0;break}d||i++}return i}catch{return 0}}function QR(c){switch(c){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":case".java":case".c":case".h":case".cpp":case".hpp":case".cc":case".cxx":case".cs":case".go":case".rs":case".swift":case".kt":case".kts":case".scala":case".php":return["//","/*"];case".py":case".pyw":case".rb":case".sh":case".bash":case".zsh":case".yaml":case".yml":return["#"];case".sql":return["--","/*"];case".html":case".htm":case".xml":return["<!--"];case".css":case".scss":case".sass":case".less":return["/*"];default:return["//"]}}function KR(c){switch(c){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":case".java":case".c":case".h":case".cpp":case".hpp":case".cc":case".cxx":case".cs":case".go":case".rs":case".swift":case".kt":case".kts":case".scala":case".php":case".css":case".scss":case".sass":case".less":case".sql":return"/*";case".py":case".pyw":return'"""';case".html":case".htm":case".xml":return"<!--";default:return null}}function JR(c){switch(c){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":case".java":case".c":case".h":case".cpp":case".hpp":case".cc":case".cxx":case".cs":case".go":case".rs":case".swift":case".kt":case".kts":case".scala":case".php":case".css":case".scss":case".sass":case".less":case".sql":return"*/";case".py":case".pyw":return'"""';case".html":case".htm":case".xml":return"-->";default:return null}}import{spawn as XR,spawnSync as ZR}from"child_process";import{createRequire as eT}from"module";import{existsSync as Ee,mkdtempSync as tT,readFileSync as tr,readdirSync as rT,rmSync as iT,statSync as nT}from"fs";import{tmpdir as sT}from"os";import{join as fe,extname as aT,resolve as oT}from"path";X();import{rmSync as YR}from"node:fs";var Ci=new Set,Ph=["SIGINT","SIGTERM","SIGHUP"];function kh(){process.removeListener("exit",Xu);for(let c of Ph)process.removeListener(c,Dh[c])}function Xu(){let c=[...Ci];Ci.clear();for(let t of c)try{t.stopTree()}catch{}for(let t of new Set(c.map(e=>e.directory)))try{YR(t,{recursive:!0,force:!0})}catch{}}function Yu(c){Xu(),kh(),process.listenerCount(c)===0&&process.kill(process.pid,c)}var Dh={SIGINT:()=>Yu("SIGINT"),SIGTERM:()=>Yu("SIGTERM"),SIGHUP:()=>Yu("SIGHUP")};function Ih(c,t){if(Ci.size===0){process.once("exit",Xu);for(let r of Ph)process.on(r,Dh[r])}let e={directory:c,stopTree:t};return Ci.add(e),()=>{Ci.delete(e),Ci.size===0&&kh()}}Yr();Xc();async function Zu(c,t={}){let e={...Lr,...t};switch(Mh(c)){case"vitest":return cT(c,e);case"jest":return lT(c,e);case"cargo":return uT(c,e);case"pytest":return dT(c,e);case"go":return mT(c,e);default:return $r(c,e)}}function Mh(c){let t=fe(c,"package.json");if(Ee(t))try{let e=D(tr(t,"utf-8")),r={...e.dependencies||{},...e.devDependencies||{}};if(r.vitest)return"vitest";if(r.jest)return"jest";let i=e.scripts?.test||"";if(i.includes("vitest"))return"vitest";if(i.includes("jest"))return"jest"}catch{}return Ee(fe(c,"Cargo.toml"))?"cargo":Ee(fe(c,"pyproject.toml"))||Ee(fe(c,"setup.py"))||Ee(fe(c,"pytest.ini"))||Ee(fe(c,"requirements.txt"))?"pytest":Ee(fe(c,"go.mod"))?"go":"fallback"}async function ed(c){let t=Xr("npx"),e=[["vitest",t,["vitest","--version"],c,1e4],["jest",t,["jest","--version"],c,1e4],["cargo",["cargo",[]],["--version"],process.cwd(),5e3],["pytest",["pytest",[]],["--version"],process.cwd(),5e3],["go",["go",[]],["version"],process.cwd(),5e3]];return Promise.all(e.map(async([r,i,n,s,a])=>{let o=await Zn(i,n,s,a);return o===null?{name:r,available:!1}:{name:r,available:!0,version:o.trim()}}))}async function Zn(c,t,e,r,i){if(!c)return null;let[n,s]=c,a=await Nt(n,[...s,...t],{cwd:e,timeout:r,maxBuffer:i});return a.error||a.status!==0?null:a.stdout}async function cT(c,t){let e;try{let r=!1;try{let d=eT(oT(c,"package.json")),m=D(tr(d.resolve("vitest/package.json"),"utf-8")),[p,h]=String(m.version).split(".").map(Number);r=p>4||p===4&&h>=1}catch{}e=tT(fe(sT(),"aqe-vitest-list-"));let i=d=>{try{if(nT(d).size>10*1024*1024)return;let m=D(tr(d,"utf-8"));if(Array.isArray(m)&&m.every(p=>p&&typeof p.name=="string"&&typeof p.file=="string"))return m.length;if(m&&typeof m.numTotalTests=="number")return m.numTotalTests}catch{}},n=async d=>{let m=fe(e,`${d}.json`),p=["vitest","list",`--json=${m}`];return d!=="legacy"&&p.push(d==="static"?"--static-parse":"--no-static-parse"),await new Promise(v=>{let b=process.platform==="win32",R=XR(b?`npx vitest list --json="%AQE_VITEST_LIST_JSON%"${d==="legacy"?"":d==="static"?" --static-parse":" --no-static-parse"}`:"npx",b?[]:p,{cwd:c,detached:!b,shell:b,env:{...process.env,AQE_VITEST_LIST_JSON:m},stdio:["ignore","pipe","pipe"]}),E=!1,T=0,I=()=>{if(R.pid)try{b?ZR("taskkill",["/PID",String(R.pid),"/T","/F"],{stdio:"ignore",timeout:5e3}):process.kill(-R.pid,"SIGKILL")}catch{}},O=Ih(e,I),q=setTimeout(()=>{E=!0,I()},Math.min(t.timeout,3e4)),j=$=>{T+=$.length,T>10*1024*1024&&(E=!0,I())};R.stdout?.on("data",j),R.stderr?.on("data",j),R.once("error",()=>{clearTimeout(q),I(),O(),v(!1)}),R.once("close",$=>{clearTimeout(q),I(),O(),v(!E&&$===0)})})?i(m):void 0};if(!r){let d=await n("legacy");return d===void 0?$r(c,t):To(d,"vitest",c)}let s=await n("static"),a=fe(e,"static.json"),o=0;if(s!==void 0){try{let d=D(tr(a,"utf-8"));Array.isArray(d)&&(o=new Set(d.map(m=>m.file)).size)}catch{}if(s>1e3||o>100)return To(s,"vitest",c)}let u=await n("collection")??s;return u===void 0?$r(c,t):To(u,"vitest",c)}catch{return $r(c,t)}finally{if(e)try{iT(e,{recursive:!0,force:!0})}catch{}}}async function lT(c,t){try{let e=await Zn(Xr("npx"),["jest","--listTests"],c,Math.min(t.timeout,3e4),10485760);if(e===null)return $r(c,t);let r=e.split(`
2878
+ `).map(i=>i.trim()).filter(i=>i.length>0&&Ee(i));if(r.length>0){let i=0;for(let n of r)i+=Fh(n);return To(i,"jest",c)}return $r(c,t)}catch{return $r(c,t)}}async function uT(c,t){try{let e=await Zn(["cargo",[]],["test","--","--list"],c,t.timeout);if(e===null)throw new Error("listing failed");let r=e.split(`
2879
+ `).filter(o=>o.endsWith(": test")),i=r.length,n=r.filter(o=>o.includes("e2e")).length,s=r.filter(o=>!o.includes("e2e")&&o.includes("integration")).length,a=i-s-n;return{total:i,unit:a,integration:s,e2e:n,source:"cargo"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"cargo"}}}async function dT(c,t){try{let e=await Zn(["pytest",[]],["--collect-only","-q"],c,t.timeout);if(e===null)throw new Error("listing failed");let r=e.split(`
2880
+ `).filter(o=>o.includes("::test_")||o.includes("::Test")),i=r.length,n=r.filter(o=>o.includes("e2e")||o.includes("end_to_end")).length,s=r.filter(o=>!o.includes("e2e")&&!o.includes("end_to_end")&&o.includes("integration")).length,a=i-s-n;return{total:i,unit:a,integration:s,e2e:n,source:"pytest"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"pytest"}}}async function mT(c,t){try{let e=await Zn(["go",[]],["test","-list",".*","./..."],c,t.timeout);if(e===null)throw new Error("listing failed");let r=e.split(`
2881
+ `).filter(o=>o.startsWith("Test")),i=r.length,n=r.filter(o=>o.includes("E2E")).length,s=r.filter(o=>!o.includes("E2E")&&o.includes("Integration")).length,a=i-s-n;return{total:i,unit:a,integration:s,e2e:n,source:"go"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"go"}}}function $r(c,t){let e=0,r=0,i=0,n=0;function s(a){if(!Ee(a))return;let o=rT(a,{withFileTypes:!0});for(let l of o){let u=fe(a,l.name);if(l.isDirectory()){if(t.excludeDirs.includes(l.name)||(t.excludeRootDirs??[]).includes(l.name)&&(a===c||Ee(fe(a,Kr))))continue;s(u)}else if(l.isFile()&&pT(l.name)){let d=aT(l.name).toLowerCase(),m=0;[".ts",".tsx",".js",".jsx",".mjs"].includes(d)?m=Fh(u):d===".py"?m=gT(u):d===".rs"?m=hT(u):d===".go"&&(m=fT(u)),e+=m;let p=u.toLowerCase();p.includes("e2e")||p.includes("end-to-end")?n+=m:p.includes("integration")?i+=m:r+=m}}}return s(c),{total:e,unit:r,integration:i,e2e:n,source:"fallback"}}function pT(c){let t=c.toLowerCase();return t.includes(".test.")||t.includes(".spec.")||t.includes("_test.")||t.startsWith("test_")||t.endsWith("_test.ts")||t.endsWith("_test.js")||t.endsWith("_test.py")||t.endsWith("_test.go")||t.endsWith("_test.rs")}function Fh(c){try{let t=tr(c,"utf-8"),e=t.match(/\bit\s*\(/g)||[],r=t.match(/\btest\s*\(/g)||[];return e.length+r.length}catch{return 0}}function gT(c){try{return(tr(c,"utf-8").match(/\bdef\s+test_\w+\s*\(/g)||[]).length}catch{return 0}}function hT(c){try{let t=tr(c,"utf-8"),e=t.match(/#\[test\]/g)||[],r=t.match(/#\[tokio::test\]/g)||[],i=t.match(/#\[async_std::test\]/g)||[];return e.length+r.length+i.length}catch{return 0}}function fT(c){try{return(tr(c,"utf-8").match(/\bfunc\s+Test\w+\s*\(/g)||[]).length}catch{return 0}}function To(c,t,e){let r=c,i=0,n=0;return(Ee(fe(e,"tests","integration"))||Ee(fe(e,"test","integration"))||Ee(fe(e,"__tests__","integration")))&&(i=Math.floor(c*.2),r-=i),(Ee(fe(e,"tests","e2e"))||Ee(fe(e,"test","e2e"))||Ee(fe(e,"e2e"))||Ee(fe(e,"cypress")))&&(n=Math.floor(c*.1),r-=n),{total:c,unit:Math.max(0,r),integration:i,e2e:n,source:t}}var td=class{config;cache=new Map;cacheHits=0;cacheMisses=0;constructor(t={}){this.config={...Lr,...t}}async collectAll(t){let e=`all:${t}`;if(this.config.enableCache){let u=this.getFromCache(e);if(u)return u}let[r,i,n]=await Promise.all([this.countLOC(t),this.countTests(t),this.countPatterns(t,this.detectLanguage(t))]),s=[];r.source!=="fallback"&&s.push(r.source),i.source!=="fallback"&&s.push(i.source);let a=r.source==="fallback"?"approximate":"accurate",o=i.source==="fallback"?"approximate":"accurate",l={loc:r,tests:i,patterns:n,collectedAt:new Date,toolsUsed:s,accuracy:{loc:a,tests:o,overall:a==="accurate"&&o==="accurate"?"accurate":"approximate"}};return this.config.enableCache&&this.setInCache(e,l),l}async countLOC(t){let e=`loc:${t}`;if(this.config.enableCache){let i=this.getFromCache(e);if(i)return i}let r=await Ku(t,this.config);return this.config.enableCache&&this.setInCache(e,r),r}async countTests(t){let e=`tests:${t}`;if(this.config.enableCache){let i=this.getFromCache(e);if(i)return i}let r=await Zu(t,this.config);return this.config.enableCache&&this.setInCache(e,r),r}async countPatterns(t,e){let r=`patterns:${t}:${e}`;if(this.config.enableCache){let n=this.getFromCache(r);if(n)return n}let i=this.countPatternsInternal(t,e);return this.config.enableCache&&this.setInCache(r,i),i}async checkTools(){let[t,e]=await Promise.all([Ju(),ed(process.cwd())]);return[...t,...e]}clearCache(){this.cache.clear(),this.cacheHits=0,this.cacheMisses=0}getCacheStats(){return{hits:this.cacheHits,misses:this.cacheMisses,size:this.cache.size}}getFromCache(t){let e=this.cache.get(t);return e&&Date.now()-e.timestamp<this.config.cacheTTL?(this.cacheHits++,e.data):(this.cacheMisses++,null)}setInCache(t,e){this.cache.set(t,{data:e,timestamp:Date.now()})}detectLanguage(t){return rr(ir(t,"Cargo.toml"))?"rust":rr(ir(t,"go.mod"))?"go":rr(ir(t,"pyproject.toml"))||rr(ir(t,"requirements.txt"))?"python":rr(ir(t,"package.json"))?rr(ir(t,"tsconfig.json"))?"typescript":"javascript":"unknown"}countPatternsInternal(t,e){let r={},i=0,n=0,s=0,a=0,o=this.getPatternsForLanguage(e),l=new Set(this.config.excludeDirs),u=new Set(this.config.excludeRootDirs??[]);function d(m){if(!rr(m))return;let p=vT(m,{withFileTypes:!0});for(let h of p){let v=ir(m,h.name);if(h.isDirectory()){if(l.has(h.name)||u.has(h.name)&&(m===t||rr(ir(m,Kr))))continue;d(v)}else if(h.isFile()){let b=bT(h.name).toLowerCase();if(wT(b,e)){let C=CT(v,o);(C.unwraps>0||C.unsafeBlocks>0||C.todoComments>0||C.consoleStatements>0)&&(r[v]=C,i+=C.unwraps,n+=C.unsafeBlocks,s+=C.todoComments,a+=C.consoleStatements)}}}}return d(t),{unwraps:i,unsafeBlocks:n,todoComments:s,consoleStatements:a,byFile:r}}getPatternsForLanguage(t){switch(t){case"rust":return{unwrap:/\.unwrap\s*\(/g,unsafe:/\bunsafe\s*\{/g,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(println!|print!|eprintln!|eprint!|dbg!)\s*\(/g};case"python":return{unwrap:null,unsafe:null,todo:/#\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(print)\s*\(/g};case"go":return{unwrap:null,unsafe:/\bunsafe\./g,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(fmt\.Print|fmt\.Printf|fmt\.Println|log\.Print|log\.Printf|log\.Println)\s*\(/g};default:return{unwrap:null,unsafe:null,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\bconsole\.(log|debug|info|warn|error)\s*\(/g}}}};function wT(c,t){switch(t){case"rust":return c===".rs";case"python":return[".py",".pyw"].includes(c);case"go":return c===".go";case"typescript":return[".ts",".tsx"].includes(c);case"javascript":return[".js",".jsx",".mjs",".cjs"].includes(c);default:return[".ts",".tsx",".js",".jsx",".py",".rs",".go"].includes(c)}}function CT(c,t){try{let e=yT(c,"utf-8");return{unwraps:t.unwrap?(e.match(t.unwrap)||[]).length:0,unsafeBlocks:t.unsafe?(e.match(t.unsafe)||[]).length:0,todoComments:(e.match(t.todo)||[]).length,consoleStatements:(e.match(t.console)||[]).length}}catch{return{unwraps:0,unsafeBlocks:0,todoComments:0,consoleStatements:0}}}function Lh(c={}){return new td(c)}_();k();ge();yr();k();yr();k();yr();k();yr();k();ge();yr();k();var o3=300*1e3;vt();vt();_();vt();var w3=x.create("temporal-compression");k();_();Wi();var E3=x.create("ruvector-server-client");yb();import{Buffer as LT}from"buffer";var M3=LT.from("COGCNTNR","ascii");vt();vt();var OT={capacity:1e4,minCoherenceThreshold:.3,highTierThreshold:.8,mediumTierThreshold:.5,highTierWeight:3,mediumTierWeight:1.5,lowTierWeight:1},rd=class{config;cusumDetector;buffer;totalSeen=0;totalAdmitted=0;totalRejected=0;totalEvicted=0;totalSampled=0;constructor(t){this.config={...OT,...t},this.cusumDetector=new _c({threshold:this.config.cusumConfig?.threshold??5,slack:this.config.cusumConfig?.slack??.5,resetOnAlarm:!1,warmupSamples:20}),this.buffer=[]}admit(t,e,r){this.totalSeen++;let i=this.getEffectiveThreshold();if(r<i)return this.totalRejected++,!1;let n=this.classifyTier(r),s={id:t,data:e,coherenceScore:r,tier:n,admittedAt:Date.now(),replayCount:0};if(this.buffer.length<this.config.capacity)return this.buffer.push(s),this.totalAdmitted++,!0;let a=Math.floor(Math.random()*this.totalAdmitted),o=this.getTierWeight(n),l=Math.floor(a/o);if(l<this.config.capacity){let u=this.selectEvictionTarget(l);return this.buffer[u]=s,this.totalEvicted++,this.totalAdmitted++,!0}return this.totalRejected++,!1}sample(t,e){if(this.buffer.length===0)return[];let r=e!==void 0?this.buffer.filter(a=>a.coherenceScore>=e):this.buffer;if(r.length===0)return[];if(t>=r.length){let a=[...r];for(let o of a)o.replayCount++;return this.totalSampled+=a.length,a}let i=r.map(a=>this.getTierWeight(a.tier)),n=[],s=new Set;for(;n.length<t&&s.size<r.length;){let a=0;for(let u=0;u<r.length;u++)s.has(u)||(a+=i[u]);if(a<=0)break;let o=Math.random()*a,l=-1;for(let u=0;u<r.length;u++)if(!s.has(u)&&(o-=i[u],o<=0)){l=u;break}if(l===-1){for(let u=0;u<r.length;u++)if(!s.has(u)){l=u;break}}l>=0&&(s.add(l),r[l].replayCount++,n.push(r[l]))}return this.totalSampled+=n.length,n}size(){return this.buffer.length}getStats(){let t={high:0,medium:0,low:0};for(let e of this.buffer)t[e.tier]++;return{size:this.buffer.length,capacity:this.config.capacity,totalAdmitted:this.totalAdmitted,totalRejected:this.totalRejected,totalEvicted:this.totalEvicted,tierCounts:t,totalSampled:this.totalSampled}}getByTier(t){return this.buffer.filter(e=>e.tier===t)}clear(){this.buffer.length=0,this.totalSeen=0,this.totalAdmitted=0,this.totalRejected=0,this.totalEvicted=0,this.totalSampled=0,this.cusumDetector.reset()}getCusumState(t){return this.cusumDetector.getState(t)}observeCoherence(t,e){return this.cusumDetector.update(t,e)}classifyTier(t){return t>=this.config.highTierThreshold?"high":t>=this.config.mediumTierThreshold?"medium":"low"}getTierWeight(t){switch(t){case"high":return this.config.highTierWeight;case"medium":return this.config.mediumTierWeight;case"low":return this.config.lowTierWeight}}getEffectiveThreshold(){let t=["retrieve","write","learn","act"],e=!1;for(let r of t)if(this.cusumDetector.getState(r).driftDetected){e=!0;break}return e?Math.min(this.config.minCoherenceThreshold*1.5,.9):this.config.minCoherenceThreshold}selectEvictionTarget(t){let e=Math.min(10,this.buffer.length),r=Math.max(0,t-Math.floor(e/2)),i=Math.min(this.buffer.length,r+e),n=t,s=this.buffer[t].coherenceScore;for(let a=r;a<i;a++)this.buffer[a].coherenceScore<s&&(s=this.buffer[a].coherenceScore,n=a);return n}};ge();var Si=x.create("code-intelligence/gnn");async function $h(c,t,e){try{for(let r of e)try{let i=await t.readFile(r);if(i.success&&i.value){let s={vector:await id(r,i.value),dimension:384,namespace:"code",text:i.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:r}};c.addEmbedding(s)}}catch(i){Si.error(`Failed to index ${r}:`,i instanceof Error?i:void 0)}Si.info(`Indexed ${e.length} code embeddings`)}catch(r){Si.error("Failed to index code embeddings:",r instanceof Error?r:void 0)}}async function id(c,t){let e=[],r=c.split(".").pop(),i=Eo(r||"");e.push(i%1e3/1e3),e.push(Math.min(1,t.length/1e4));let n=t.match(/function\s+\w+/g)||[],s=t.match(/class\s+\w+/g)||[];e.push(Math.min(1,(n.length+s.length)/50));let a=t.match(/import\s+.*from|require\s*\(/g)||[];e.push(Math.min(1,a.length/20));let o=t.match(/for\s*\(|while\s*\(/g)||[],l=t.match(/if\s*\(/g)||[];e.push(Math.min(1,(o.length+l.length)/30));let u=t.match(/\/\/.*|\/\*[\s\S]*?\*\//g)||[];e.push(Math.min(1,u.length/50));let d=Eo(t.slice(0,500));for(let m=e.length;m<384;m++)e.push(d*(m+1)%1e4/1e4);return e.slice(0,384)}async function Oh(c,t){try{let r={vector:await id("query",t),dimension:384,namespace:"code",text:t,timestamp:Date.now(),quantization:"none"};return c.search(r,{limit:10,namespace:"code"}).map(n=>({file:n.metadata?.path??`file-${n.id}`,similarity:1-n.distance}))}catch(e){return Si.error("Failed to search with GNN:",e instanceof Error?e:void 0),[]}}async function Nh(c,t,e){try{for(let r of e.changedFiles){let i=await t.readFile(r);if(i.success&&i.value){let s={vector:await id(r,i.value),dimension:384,namespace:"code",text:i.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:r}},a=c.search(s,{limit:5,namespace:"code"});Si.info(`Found ${a.length} semantically similar files to ${r}`)}}}catch(r){Si.error("Failed to enhance impact analysis:",r instanceof Error?r:void 0)}}function _h(c,t){let e=new Map,r=new Map;for(let i of c)e.set(i.file,i.score),r.set(i.file,i);for(let i of t){let n=e.get(i.file);n!==void 0?e.set(i.file,(n+i.similarity)/2):(e.set(i.file,i.similarity*.8),r.set(i.file,{file:i.file,snippet:"",score:i.similarity*.8,highlights:[]}))}return Array.from(r.values()).map(i=>({...i,score:e.get(i.file)??i.score})).sort((i,n)=>n.score-i.score).slice(0,20)}function Eo(c){let t=0;for(let e=0;e<c.length;e++)t=(t<<5)-t+c.charCodeAt(e),t=t|0;return Math.abs(t)}_();k();var pt=x.create("code-intelligence/hypergraph");async function Vh(c,t,e){try{let r=await c.findUntestedFunctions();if(pt.info(`[CodeIntelligence] Found ${r.length} untested functions via hypergraph`),e){let i=N("code-intelligence.UntestedFunctionsFound","code-intelligence",{count:r.length,functions:r.slice(0,10).map(n=>({name:n.name,file:n.filePath,complexity:n.complexity}))});await t.publish(i)}return{success:!0,value:r}}catch(r){let i=y(r);return pt.error("Failed to find untested functions:"),g(i)}}async function zh(c,t,e,r){if(t.length===0)return{success:!0,value:[]};try{let i=await c.findImpactedTests(t);if(pt.info(`[CodeIntelligence] Found ${i.length} impacted tests for ${t.length} changed files via hypergraph`),r){let n=N("code-intelligence.ImpactedTestsFound","code-intelligence",{changedFiles:t,testCount:i.length,tests:i.slice(0,10).map(s=>({name:s.name,file:s.filePath}))});await e.publish(n)}return{success:!0,value:i}}catch(i){let n=y(i);return pt.error("Failed to find impacted tests:"),g(n)}}async function Bh(c,t,e,r){try{let i=await c.findCoverageGaps(t);if(pt.info(`[CodeIntelligence] Found ${i.length} coverage gaps (functions with <=${t}% coverage) via hypergraph`),r){let n=N("code-intelligence.CoverageGapsFound","code-intelligence",{maxCoverage:t,gapCount:i.length,gaps:i.slice(0,10).map(s=>({name:s.name,file:s.filePath,coverage:s.coverage,complexity:s.complexity}))});await e.publish(n)}return{success:!0,value:i}}catch(i){let n=y(i);return pt.error("Failed to find coverage gaps:"),g(n)}}async function qh(c,t,e,r,i){try{pt.info(`[CodeIntelligence] Building hypergraph from ${t.files.length} indexed files`);let n=await c.buildFromIndexResult(t);if(pt.info(`[CodeIntelligence] Hypergraph built: ${n.nodesCreated} nodes created, ${n.nodesUpdated} nodes updated, ${n.edgesCreated} edges created (${n.durationMs}ms)`),await e.set("hypergraph:build:latest",{timestamp:new Date().toISOString(),...n},{namespace:"code-intelligence",persist:!0}),i){let s=N("code-intelligence.HypergraphBuilt","code-intelligence",{nodesCreated:n.nodesCreated,nodesUpdated:n.nodesUpdated,edgesCreated:n.edgesCreated,durationMs:n.durationMs,errorCount:n.errors.length});await r.publish(s)}return{success:!0,value:n}}catch(n){let s=y(n);return pt.error("Failed to build hypergraph:"),g(s)}}async function Gh(c,t,e){try{let r=await c.findImpactedTests(t.changedFiles),i=new Set([...e.impactedTests,...r.map(a=>a.filePath||a.name)]),n=e.riskLevel;if(r.length>e.impactedTests.length){let a=e.directImpact.length+e.transitiveImpact.length;a>10&&i.size>20?n="critical":a>5&&i.size>10&&(n="high")}let s=[...e.recommendations];return r.length>0&&s.push(`Hypergraph analysis found ${r.length} additional test(s) to run`),{...e,impactedTests:Array.from(i),riskLevel:n,recommendations:s}}catch(r){return pt.error("Failed to enhance impact with hypergraph:",r instanceof Error?r:void 0),e}}_();var Ri=x.create("code-intelligence/consensus");async function jh(c,t,e,r){let i=U({id:w(),type:"code-pattern-detection",confidence:t,description:`Verify code pattern: ${c.name} (${c.type}) at ${c.location}`,payload:c,detectedBy:"code-intelligence-coordinator",severity:t>.9?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Ri.info(`Code pattern '${c.name}' verified by consensus`),!0):(Ri.warn(`Code pattern '${c.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Hh(c,t,e,r){let i=U({id:w(),type:"impact-analysis",confidence:t,description:`Verify impact analysis: ${c.changedFiles.length} files, risk=${c.riskLevel}, ${c.impactedTests.length} tests`,payload:c,detectedBy:"code-intelligence-coordinator",severity:c.riskLevel==="critical"||c.riskLevel==="high"?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Ri.info(`Impact analysis verified by consensus (risk=${c.riskLevel})`),!0):(Ri.warn(`Impact analysis NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Wh(c,t,e,r){let i=U({id:w(),type:"dependency-mapping",confidence:t,description:`Verify dependency: ${c.source} -> ${c.targets.length} targets (${c.type})`,payload:c,detectedBy:"code-intelligence-coordinator",severity:t>.85?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Ri.info("Dependency mapping verified by consensus"),!0):(Ri.warn(`Dependency mapping NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}var ZT={maxConcurrentWorkflows:5,defaultTimeout:12e4,publishEvents:!0,enableIncrementalIndex:!0,enableGNN:!0,enableSONA:!0,enableMetricCollector:!0,enableHypergraph:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},ce=x.create("code-intelligence"),ts=class extends ie{constructor(e,r,i,n={},s){let a={...ZT,...n};super(e,"code-intelligence",a,{verifyFindingTypes:["code-pattern-detection","impact-analysis","dependency-mapping"]});this.memory=r;this.agentCoordinator=i;this.knowledgeGraph=new _t({memory:r,llmRouter:s}),this.semanticAnalyzer=new Fr(r),this.impactAnalyzer=new rn(r,this.knowledgeGraph),this.fileReader=new it({projectRoot:Ce()}),this.productFactorsBridge=new Co(e,r,{publishEvents:this.config.publishEvents,relationshipResolver:Th(o=>new _t({memory:r,llmRouter:s},{basePath:o}))})}memory;agentCoordinator;knowledgeGraph;semanticAnalyzer;impactAnalyzer;fileReader;gnnIndex;sonaEngine;rlInitialized=!1;metricCollector;hypergraph;hypergraphDb;productFactorsBridge;async onInitialize(){this.subscribeToEvents(),await this.loadWorkflowState(),(this.config.enableGNN||this.config.enableSONA)&&await this.initializeRLIntegrations(),this.config.enableMetricCollector&&(this.metricCollector=Lh({enableCache:!0,cacheTTL:3e5}),ce.info("MetricCollector initialized for real code metrics")),this.config.enableHypergraph&&await this.initializeHypergraph(),await this.productFactorsBridge.initialize()}async initializeHypergraph(){try{let{openDatabase:e}=await import("./safe-db-QXDZ6QY3.js"),r=await import("fs"),i=await import("path"),{findProjectRoot:n}=await import("./unified-memory-FL26RTV3.js"),s=n(),a=process.env.AQE_MEMORY_BACKEND==="memory",o=a?":memory:":this.config.hypergraphDbPath||i.join(s,".agentic-qe","memory.db");if(!a){let l=i.dirname(o);r.existsSync(l)||r.mkdirSync(l,{recursive:!0})}this.hypergraphDb=e(o),this.hypergraph=await Ns({db:this.hypergraphDb,maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:this.config.enableGNN}),ce.info(`Hypergraph Engine initialized at ${o}`)}catch(e){let r=e instanceof Error?e.message:String(e);if(ce.warn(`Hypergraph Engine initialization failed (feature degraded): ${r}`),this.hypergraph=void 0,this.hypergraphDb=void 0,this.config.publishEvents){let i=N("code-intelligence.HypergraphDegraded","code-intelligence",{reason:r});this.eventBus.publish(i).catch(()=>{})}}}async initializeRLIntegrations(){try{if(this.config.enableGNN&&(Wc(),this.gnnIndex=Ds.getInstance("code-intelligence",{M:16,efConstruction:200,efSearch:50,dimension:384,metric:"cosine"}),this.gnnIndex.initializeIndex("code"),this.gnnIndex.initializeIndex("test")),this.config.enableSONA)try{this.sonaEngine=await De({domain:"code-intelligence",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.6}),ce.info("PersistentSONAEngine initialized for code pattern learning")}catch(e){ce.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),this.sonaEngine=void 0}this.rlInitialized=!0}catch(e){throw ce.error("Failed to initialize RL integrations:",e instanceof Error?e:void 0),e}}async onDispose(){if(await this.saveWorkflowState(),this.gnnIndex&&Ds.closeInstance("code-intelligence"),this.sonaEngine)try{await this.sonaEngine.close(),this.sonaEngine=void 0}catch(e){ce.error("Error closing SONA engine:",e instanceof Error?e:void 0)}if(this.hypergraphDb){try{this.hypergraphDb.close()}catch(e){ce.error("Error closing hypergraph database:",e instanceof Error?e:void 0)}this.hypergraphDb=void 0}this.hypergraph=void 0,await this.productFactorsBridge.dispose()}getActiveWorkflows(){return super.getActiveWorkflows()}async index(e){let r=Wm(e.paths,"paths","Invalid index payload",Number.POSITIVE_INFINITY);if(!r.success)return r;let i=w();try{if(this.startWorkflow(i,"index"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ce.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return g(new Error("Indexing paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return g(new Error("Agent limit reached, cannot spawn indexing agents"));let n=await this.spawnIndexerAgent(i,e);if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);this.addAgentToWorkflow(i,n.value),this.updateWorkflowProgress(i,10);let s=await this.knowledgeGraph.index(e);if(s.success&&s.value.filesIndexed===0&&e.paths.length>0){let a=Um(e.paths.length,s.value.skipped??[],s.value.errors);return this.failWorkflow(i,a.message),await this.agentCoordinator.stop(n.value),g(a)}if(s.success){this.updateWorkflowProgress(i,40);let a=new Set([...(s.value.skipped??[]).map(l=>l.path),...s.value.errors.map(l=>l.file)]),o=e.paths.filter(l=>!a.has(l));if(this.config.enableGNN&&this.gnnIndex&&o.length>0&&await this.indexCodeEmbeddings(o),this.updateWorkflowProgress(i,60),this.config.enableMetricCollector&&this.metricCollector&&o.length>0){let l=this.getProjectRootFromPaths(o,e.target);l?await this.collectProjectMetrics(l):ce.debug("Skipping project metrics: no project root resolved (filesystem root or no paths)")}if(this.updateWorkflowProgress(i,70),o.length>0&&await this.indexForSemanticSearch(o),this.updateWorkflowProgress(i,85),this.config.enableHypergraph&&this.hypergraph&&o.length>0)try{let l=await this.buildCodeIndexResultFromPaths(o);if(l.files.length>0){await this.hypergraph.buildFromIndexResult(l),ce.info(`Hypergraph rebuilt from ${l.files.length} indexed files`);try{let u=await this.hypergraph.synthesizeTestCoverage();(u.testsTagged>0||u.coversCreated>0)&&ce.info(`Test coverage synthesized: tests_tagged=${u.testsTagged} covers_created=${u.coversCreated}`)}catch(u){ce.warn(`Test coverage synthesis skipped: ${u instanceof Error?u.message:u}`)}}}catch(l){ce.warn(`Hypergraph rebuild skipped: ${l instanceof Error?l.message:l}`)}this.updateWorkflowProgress(i,100),this.completeWorkflow(i),this.config.publishEvents&&await this.publishKnowledgeGraphUpdated(s.value)}else this.failWorkflow(i,s.error.message);return await this.agentCoordinator.stop(n.value),s}catch(n){let s=y(n);return this.failWorkflow(i,s.message),g(s)}}async search(e){let r=w();try{this.startWorkflow(r,"search");let i=await this.spawnSearchAgent(r,e);if(i.success&&this.addAgentToWorkflow(r,i.value),this.config.enableSONA&&this.sonaEngine){let a=await this.adaptSearchPattern(e);a.success&&a.pattern&&ce.info(`Adapted search pattern with ${a.similarity.toFixed(3)} similarity`)}let n=[];this.config.enableGNN&&this.gnnIndex&&(n=await this.searchCodeWithGNN(e));let s=await this.semanticAnalyzer.search(e);return s.success?(n.length>0&&(s.value.results=this.mergeSearchResults(s.value.results,n)),this.completeWorkflow(r),this.config.publishEvents&&await this.publishSemanticSearchCompleted(e,s.value)):this.failWorkflow(r,s.error.message),i.success&&await this.agentCoordinator.stop(i.value),s}catch(i){let n=y(i);return this.failWorkflow(r,n.message),g(n)}}async analyzeImpact(e){let r=w();try{if(this.startWorkflow(r,"impact"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ce.warn("Topology degraded, using conservative impact analysis"),this.minCutMixin.shouldPauseOperations())return g(new Error("Impact analysis paused: topology is in critical state"));let i=await this.spawnImpactAnalyzerAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),g(i.error);this.addAgentToWorkflow(r,i.value),this.updateWorkflowProgress(r,20),this.config.enableGNN&&this.gnnIndex&&await this.enhanceImpactAnalysisWithGNN(e);let n=await this.impactAnalyzer.analyzeImpact(e);if(n.success){this.updateWorkflowProgress(r,80);let s=n.value;return this.config.enableHypergraph&&this.hypergraph&&(s=await this.enhanceImpactWithHypergraph(e,n.value)),this.updateWorkflowProgress(r,100),this.completeWorkflow(r),this.config.enableSONA&&this.sonaEngine&&await this.storeImpactPattern(e,s),this.config.publishEvents&&await this.publishImpactAnalysisCompleted(e,s),{success:!0,value:s}}else this.failWorkflow(r,n.error.message);return await this.agentCoordinator.stop(i.value),n}catch(i){let n=y(i);return this.failWorkflow(r,n.message),g(n)}}async mapDependencies(e){let r=w();try{this.startWorkflow(r,"dependency");let i=await this.knowledgeGraph.mapDependencies(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){let n=y(i);return this.failWorkflow(r,n.message),g(n)}}async queryKG(e){let r=w();try{this.startWorkflow(r,"query");let i=await this.knowledgeGraph.query(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){let n=y(i);return this.failWorkflow(r,n.message),g(n)}}async indexCodeEmbeddings(e){!this.gnnIndex||!this.rlInitialized||await $h(this.gnnIndex,this.fileReader,e)}async searchCodeWithGNN(e){return!this.gnnIndex||!this.rlInitialized?[]:Oh(this.gnnIndex,e.query)}async enhanceImpactAnalysisWithGNN(e){!this.gnnIndex||!this.rlInitialized||await Nh(this.gnnIndex,this.fileReader,e)}async adaptSearchPattern(e){if(!this.sonaEngine||!this.rlInitialized)return{success:!1,pattern:null,similarity:0};try{let r=Array.isArray(e.filters)?e.filters.find(s=>s.field==="language")?.value:void 0,i={id:`search-${e.type}`,features:[e.query.length,e.type==="semantic"?1:0,e.type==="exact"?1:0,r==="typescript"?1:0,r==="javascript"?1:0]},n=await this.sonaEngine.adaptPattern(i,"coverage-optimization","code-intelligence");return{success:n.success,pattern:n.pattern,similarity:n.similarity}}catch(r){return ce.error("Failed to adapt search pattern:",r instanceof Error?r:void 0),{success:!1,pattern:null,similarity:0}}}async storeImpactPattern(e,r){if(!(!this.sonaEngine||!this.rlInitialized))try{let i={id:`impact-${e.changedFiles.join(",")}`,features:[e.changedFiles.length,e.depth||1,r.directImpact.length,r.transitiveImpact.length,r.impactedTests.length,r.riskLevel==="high"?1:r.riskLevel==="medium"?.5:0]},n={type:"analyze-impact",value:r.riskLevel},s={reward:r.riskLevel==="high"?.8:r.riskLevel==="medium"?.5:.3,success:r.impactedTests.length>0,quality:(r.directImpact.length+r.transitiveImpact.length)/100},a=this.sonaEngine.createPattern(i,n,s,"coverage-optimization","code-intelligence",{changedFiles:e.changedFiles,impactCount:r.directImpact.length+r.transitiveImpact.length,testImpactCount:r.impactedTests.length});ce.info(`Stored impact pattern ${a.id}`)}catch(i){ce.error("Failed to store impact pattern:",i instanceof Error?i:void 0)}}mergeSearchResults(e,r){return _h(e,r)}hashCode(e){return Eo(e)}async spawnIndexerAgent(e,r){let i={name:`kg-indexer-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["indexing","ast-parsing","graph-building"],config:{workflowId:e,paths:r.paths,incremental:r.incremental}};return this.agentCoordinator.spawn(i)}async spawnSearchAgent(e,r){let i={name:`semantic-search-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["semantic-search","vector-similarity",r.type],config:{workflowId:e,query:r.query,type:r.type}};return this.agentCoordinator.spawn(i)}async spawnImpactAnalyzerAgent(e,r){let i={name:`impact-analyzer-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["impact-analysis","dependency-traversal","risk-assessment"],config:{workflowId:e,changedFiles:r.changedFiles,depth:r.depth}};return this.agentCoordinator.spawn(i)}async publishKnowledgeGraphUpdated(e){let r={nodes:e.nodesCreated,edges:e.edgesCreated,filesIndexed:e.filesIndexed,duration:e.duration},i=N(Lt.KnowledgeGraphUpdated,"code-intelligence",r);await this.eventBus.publish(i)}async publishImpactAnalysisCompleted(e,r){let i={analysisId:w(),changedFiles:e.changedFiles,impactedFiles:[...r.directImpact.map(s=>s.file),...r.transitiveImpact.map(s=>s.file)],impactedTests:r.impactedTests,riskLevel:r.riskLevel},n=N(Lt.ImpactAnalysisCompleted,"code-intelligence",i);await this.eventBus.publish(n)}async publishSemanticSearchCompleted(e,r){let i=N(Lt.SemanticSearchCompleted,"code-intelligence",{query:e.query,type:e.type,resultCount:r.total,searchTime:r.searchTime});await this.eventBus.publish(i)}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("source-control.FilesChanged",this.handleFilesChanged.bind(this))}async handleTestRunCompleted(e){let r=e.payload;await this.memory.set(`code-intelligence:test-correlation:${r.runId}`,r,{namespace:"code-intelligence",ttl:86400})}async handleFilesChanged(e){if(!this.config.enableIncrementalIndex)return;let r=e.payload;r.files&&r.files.length>0&&await this.memory.set(`code-intelligence:pending-index:${Date.now()}`,{files:r.files,timestamp:new Date().toISOString()},{namespace:"code-intelligence",ttl:3600})}async indexForSemanticSearch(e){let r=e.slice(0,100);for(let i of r)try{let n=await this.fileReader.readFile(i);n.success&&n.value&&await this.semanticAnalyzer.indexCode(i,n.value)}catch{}}async loadWorkflowState(){let e=await this.memory.get("code-intelligence:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("code-intelligence:coordinator:workflows",e,{namespace:"code-intelligence",persist:!0})}async generateC4Diagrams(e,r){let i=w();try{this.startWorkflow(i,"query");let n={projectPath:e,detectExternalSystems:r?.detectExternalSystems??!0,analyzeComponents:r?.analyzeComponents??!0,analyzeCoupling:r?.analyzeCoupling??!0,includeContext:r?.includeContext??!0,includeContainer:r?.includeContainer??!0,includeComponent:r?.includeComponent??!0,includeDependency:r?.includeDependency??!1,excludePatterns:r?.excludePatterns};this.updateWorkflowProgress(i,20);let s=await this.productFactorsBridge.requestC4Diagrams(n);return s.success?(this.updateWorkflowProgress(i,80),await this.storeC4DiagramsInMemory(e,s.value),this.updateWorkflowProgress(i,100),this.completeWorkflow(i),ce.info(`[CodeIntelligenceCoordinator] C4 diagrams generated for ${e}: ${s.value.components.length} components, ${s.value.externalSystems.length} external systems`)):this.failWorkflow(i,s.error.message),s}catch(n){let s=y(n);return this.failWorkflow(i,s.message),g(s)}}getProductFactorsBridge(){return this.productFactorsBridge}async storeC4DiagramsInMemory(e,r){let i=`c4-diagrams:latest:${this.hashCode(e)}`;await this.memory.set(i,r,{namespace:"code-intelligence",persist:!0,ttl:3600}),await this.memory.set(`c4-components:${this.hashCode(e)}`,r.components,{namespace:"code-intelligence",ttl:3600}),await this.memory.set(`c4-external-systems:${this.hashCode(e)}`,r.externalSystems,{namespace:"code-intelligence",ttl:3600})}async collectProjectMetrics(e){if(!this.config.enableMetricCollector||!this.metricCollector)return g(new Error("MetricCollector is not enabled"));try{ce.info(`Collecting real metrics for ${e}`);let r=await this.metricCollector.collectAll(e),i=r.toolsUsed.length>0?r.toolsUsed.join(", "):r.loc.source==="node-native"?"node-native":"fallback";if(ce.info(`[CodeIntelligence] Real metrics collected: ${r.loc.total} LOC, ${r.tests.total} tests, tools: ${i}`),r.loc.source==="node-native"&&ce.info("[CodeIntelligence] Using Node.js-native line counter (no cloc/tokei needed)"),await this.storeProjectMetricsInMemory(e,r),this.config.publishEvents){let n=N("code-intelligence.MetricsCollected","code-intelligence",{projectPath:e,loc:r.loc.total,tests:r.tests.total,toolsUsed:r.toolsUsed});await this.eventBus.publish(n)}return{success:!0,value:r}}catch(r){let i=y(r);return ce.error("Failed to collect metrics:"),g(i)}}async storeProjectMetricsInMemory(e,r){let i=`project-metrics:latest:${this.hashCode(e)}`;await this.memory.set(i,r,{namespace:"code-intelligence",persist:!0,ttl:300}),await this.memory.set(`loc-metrics:${this.hashCode(e)}`,r.loc,{namespace:"code-intelligence",ttl:300}),await this.memory.set(`test-metrics:${this.hashCode(e)}`,r.tests,{namespace:"code-intelligence",ttl:300})}getMetricCollector(){return this.metricCollector}getProjectRootFromPaths(e,r){return gh(e,{target:r})}isHypergraphEnabled(){return this.config.enableHypergraph&&this.hypergraph!==void 0}async findUntestedFunctions(){return this.hypergraph?Vh(this.hypergraph,this.eventBus,this.config.publishEvents):g(new Error("Hypergraph is not enabled or not initialized"))}async findImpactedTestsFromHypergraph(e){return this.hypergraph?zh(this.hypergraph,e,this.eventBus,this.config.publishEvents):g(new Error("Hypergraph is not enabled or not initialized"))}async findCoverageGapsFromHypergraph(e=50){return this.hypergraph?Bh(this.hypergraph,e,this.eventBus,this.config.publishEvents):g(new Error("Hypergraph is not enabled or not initialized"))}async buildHypergraphFromIndex(e){return this.hypergraph?qh(this.hypergraph,e,this.memory,this.eventBus,this.config.publishEvents):g(new Error("Hypergraph is not enabled or not initialized"))}getHypergraph(){return this.hypergraph}async enhanceImpactWithHypergraph(e,r){return this.hypergraph?Gh(this.hypergraph,e,r):r}async buildCodeIndexResultFromPaths(e){let{extractCodeIndex:r}=await import("./code-index-extractor-GWJKZ2IQ.js");return r(e)}async verifyCodePatternDetection(e,r){return jh(e,r,this.consensusMixin,this.domainName)}async verifyImpactAnalysis(e,r){return Hh(e,r,this.consensusMixin,this.domainName)}async verifyDependencyMapping(e,r){return Wh(e,r,this.consensusMixin,this.domainName)}};k();var Ao=class extends te{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;knowledgeGraph=null;semanticAnalyzer=null;impactAnalyzer=null;pluginConfig;get name(){return"code-intelligence"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{index:this.index.bind(this),search:this.search.bind(this),analyzeImpact:this.analyzeImpact.bind(this),mapDependencies:this.mapDependencies.bind(this),getDependencies:this.mapDependencies.bind(this),queryKG:this.queryKG.bind(this),getMetrics:this.getMetrics.bind(this),getCoordinator:()=>this.coordinator,getKnowledgeGraph:()=>this.knowledgeGraph,getSemanticAnalyzer:()=>this.semanticAnalyzer,getImpactAnalyzer:()=>this.impactAnalyzer}}getTaskHandlers(){let e=new Map([["index",async r=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let i=r.paths;if(!i||i.length===0)return g(new Error("Invalid index payload: missing paths"));let n=r.language?[r.language]:r.languages;return this.coordinator.index({paths:i,languages:n,target:typeof r.target=="string"?r.target:void 0})}],["search",async r=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let i=r.query;return i?this.coordinator.search({query:i,type:r.type??"semantic",limit:r.limit}):g(new Error("Invalid search payload: missing query"))}],["analyze-impact",async r=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let i=r.changedFiles;return!i||i.length===0?g(new Error("Invalid analyze-impact payload: missing changedFiles")):this.coordinator.analyzeImpact({changedFiles:i})}],["query-dependencies",async r=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let i=r.file,s=r.files??(i?[i]:void 0);return!s||s.length===0?g(new Error("Invalid query-dependencies payload: missing file or files")):this.coordinator.mapDependencies({files:s,direction:r.direction??"both",depth:r.depth})}]]);return e.set("index-code",e.get("index")),e}async onInitialize(){this.knowledgeGraph=new _t({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.knowledgeGraph),this.semanticAnalyzer=new Fr(this.memory,this.pluginConfig.semanticAnalyzer),this.impactAnalyzer=new rn(this.memory,this.knowledgeGraph,this.pluginConfig.impactAnalyzer),this.coordinator=new ts(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.knowledgeGraph=null,this.semanticAnalyzer=null,this.impactAnalyzer=null}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestGenerated",this.handleTestGenerated.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("defect-intelligence.DefectPredicted",this.handleDefectPredicted.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"test-generation.TestGenerated":await this.handleTestGenerated(e);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;case"defect-intelligence.DefectPredicted":await this.handleDefectPredicted(e);break;default:break}}async index(e){this.ensureInitialized();try{let r=await this.coordinator.index(e);return r.success?this.trackSuccessfulOperation("index",r.value):this.trackFailedOperation("index",r.error),r}catch(r){return this.handleError(r)}}async search(e){this.ensureInitialized();try{let r=await this.coordinator.search(e);return r.success?this.trackSuccessfulOperation("search",r.value):this.trackFailedOperation("search",r.error),r}catch(r){return this.handleError(r)}}async analyzeImpact(e){this.ensureInitialized();try{let r=await this.coordinator.analyzeImpact(e);return r.success?this.trackSuccessfulOperation("impact",r.value):this.trackFailedOperation("impact",r.error),r}catch(r){return this.handleError(r)}}async mapDependencies(e){this.ensureInitialized();try{let r=await this.coordinator.mapDependencies(e);return r.success?this.trackSuccessfulOperation("dependency",r.value):this.trackFailedOperation("dependency",r.error),r}catch(r){return this.handleError(r)}}async queryKG(e){this.ensureInitialized();try{let r=await this.coordinator.queryKG(e);return r.success?this.trackSuccessfulOperation("query",r.value):this.trackFailedOperation("query",r.error),r}catch(r){return this.handleError(r)}}async getMetrics(){this.ensureInitialized();try{let e=this.getHealth();return{success:!0,value:{indexed:e.agents.total,queries:e.agents.idle,impacts:e.agents.active}}}catch(e){return this.handleError(e)}}async handleTestGenerated(e){let r=e.payload;await this.memory.set(`code-intelligence:test-mapping:${r.testId}`,{testFile:r.testFile,sourceFile:r.sourceFile,generatedAt:new Date().toISOString()},{namespace:"code-intelligence",ttl:86400*30})}async handleCoverageGap(e){if(!He(e.payload))return;let r=e.payload;await this.memory.set(`code-intelligence:coverage-gap:${r.gapId}`,r,{namespace:"code-intelligence",ttl:86400*7})}async handleDefectPredicted(e){let r=e.payload;await this.memory.set(`code-intelligence:defect-prediction:${r.predictionId}`,r,{namespace:"code-intelligence",ttl:86400*7})}ensureInitialized(){if(!this._initialized)throw new Error("CodeIntelligencePlugin is not initialized");if(!this.coordinator||!this.knowledgeGraph||!this.semanticAnalyzer||!this.impactAnalyzer)throw new Error("CodeIntelligencePlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,total:i.agents.total+1,idle:i.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,failed:i.agents.failed+1},errors:[...i.errors.slice(-9),r.message]})}};function nd(c,t,e,r,i){return new Ao(c,t,e,r,i)}mr();var sd=Ur;async function Uh(c,t=Ce()){return Im(c,{projectRoot:t,maxBytes:sd})}_();k();var xo={defaultRuleSets:["owasp-top-10","cwe-sans-25"],maxConcurrentScans:4,timeout:3e5,enableFalsePositiveDetection:!0,dastMaxDepth:5,dastActiveScanning:!1,enableLLMAnalysis:!0,llmModelTier:4,enableSemgrep:!0};import{createHash as Jh}from"node:crypto";import*as ut from"node:path";_();var ad=[{id:"sqli-string-concat",pattern:/query\s*\(\s*['"`].*\+.*['"`]\s*\)/g,category:"injection",severity:"critical",title:"SQL Injection via String Concatenation",description:"SQL query constructed using string concatenation with potentially untrusted input",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Use parameterized queries or prepared statements instead of string concatenation",fixExample:'db.query("SELECT * FROM users WHERE id = $1", [userId])'},{id:"sqli-template-literal",pattern:/execute\s*\(\s*`[^`]*\$\{[^}]+\}[^`]*`\s*\)/g,category:"injection",severity:"critical",title:"SQL Injection via Template Literal",description:"SQL query constructed using template literals with embedded expressions",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Use parameterized queries instead of template literals for SQL",fixExample:'db.execute("DELETE FROM users WHERE id = ?", [userId])'},{id:"sqli-raw-query",pattern:/\.raw\s*\(\s*['"`].*\+|\.raw\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"high",title:"SQL Injection via Raw Query",description:"Raw SQL query with potential user input interpolation",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Avoid raw queries with user input; use ORM methods or parameterized queries"},{id:"sqli-exec",pattern:/exec(?:ute)?(?:Sql|Query)?\s*\([^)]*\+[^)]*\)/gi,category:"injection",severity:"critical",title:"SQL Injection via Dynamic Execution",description:"Dynamic SQL execution with string concatenation detected",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Never concatenate user input into SQL queries"}],od=[{id:"xss-innerhtml",pattern:/\.innerHTML\s*=\s*[^'"`;\n]+/g,category:"xss",severity:"high",title:"XSS via innerHTML Assignment",description:"Direct innerHTML assignment with potentially unsanitized content",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Use textContent for text, or sanitize HTML with DOMPurify before innerHTML assignment",fixExample:"element.textContent = userInput; // or DOMPurify.sanitize(userInput)"},{id:"xss-document-write",pattern:/document\.write\s*\([^)]+\)/g,category:"xss",severity:"high",title:"XSS via document.write",description:"document.write() can execute scripts from untrusted data",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Avoid document.write(); use DOM manipulation methods instead",fixExample:"document.body.appendChild(document.createTextNode(text))"},{id:"xss-dangerously-set",pattern:/dangerouslySetInnerHTML\s*=\s*\{/g,category:"xss",severity:"medium",title:"React dangerouslySetInnerHTML Usage",description:"dangerouslySetInnerHTML bypasses React XSS protections",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Sanitize HTML content with DOMPurify before using dangerouslySetInnerHTML",fixExample:"dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(content) }}"},{id:"xss-eval",pattern:/eval\s*\([^)]+\)/g,category:"xss",severity:"critical",title:"Code Injection via eval()",description:"eval() executes arbitrary code and is a major security risk",owaspId:"A03:2021",cweId:"CWE-95",remediation:"Never use eval(); use JSON.parse() for JSON data or safer alternatives",fixExample:"JSON.parse(jsonString) // instead of eval(jsonString)"},{id:"xss-new-function",pattern:/new\s+Function\s*\([^)]+\)/g,category:"xss",severity:"critical",title:"Code Injection via Function Constructor",description:"Function constructor can execute arbitrary code like eval()",owaspId:"A03:2021",cweId:"CWE-95",remediation:"Avoid the Function constructor; use predefined functions instead"},{id:"xss-outerhtml",pattern:/\.outerHTML\s*=\s*[^'"`;\n]+/g,category:"xss",severity:"high",title:"XSS via outerHTML Assignment",description:"Direct outerHTML assignment with potentially unsanitized content",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Sanitize content before outerHTML assignment"}],cd=[{id:"secret-aws-access-key",pattern:/['"`]AKIA[0-9A-Z]{16}['"`]/g,category:"sensitive-data",severity:"critical",title:"AWS Access Key Detected",description:"Hardcoded AWS Access Key ID found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or AWS Secrets Manager for credentials",fixExample:"const accessKey = process.env.AWS_ACCESS_KEY_ID"},{id:"secret-aws-secret-key",pattern:/['"`][A-Za-z0-9/+=]{40}['"`]/g,category:"sensitive-data",severity:"critical",title:"Potential AWS Secret Key Detected",description:"Potential hardcoded AWS Secret Access Key found",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Store secrets in environment variables or secrets manager"},{id:"secret-openai-key",pattern:/['"`]sk-[a-zA-Z0-9]{48,}['"`]/g,category:"sensitive-data",severity:"critical",title:"OpenAI API Key Detected",description:"Hardcoded OpenAI API key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for API keys",fixExample:"const apiKey = process.env.OPENAI_API_KEY"},{id:"secret-generic-password",pattern:/password\s*[:=]\s*['"`][^'"`]{4,}['"`]/gi,category:"sensitive-data",severity:"high",title:"Hardcoded Password Detected",description:"Hardcoded password found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Never hardcode passwords; use environment variables or secrets manager",fixExample:"const password = process.env.DB_PASSWORD"},{id:"secret-api-key",pattern:/api[_-]?key\s*[:=]\s*['"`][a-zA-Z0-9_\-]{16,}['"`]/gi,category:"sensitive-data",severity:"high",title:"Hardcoded API Key Detected",description:"Hardcoded API key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for API keys",fixExample:"const apiKey = process.env.API_KEY"},{id:"secret-jwt",pattern:/['"`]eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+['"`]/g,category:"sensitive-data",severity:"high",title:"Hardcoded JWT Token Detected",description:"Hardcoded JWT token found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Generate JWT tokens dynamically; never hardcode them"},{id:"secret-private-key",pattern:/-----BEGIN\s+(RSA|EC|OPENSSH|DSA)?\s*PRIVATE\s+KEY-----/g,category:"sensitive-data",severity:"critical",title:"Private Key Detected",description:"Private key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Store private keys in secure key management systems, not in code"},{id:"secret-github-token",pattern:/['"`]ghp_[a-zA-Z0-9]{36}['"`]|['"`]github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59}['"`]/g,category:"sensitive-data",severity:"critical",title:"GitHub Token Detected",description:"Hardcoded GitHub personal access token found",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or GitHub Actions secrets"},{id:"secret-slack-token",pattern:/['"`]xox[baprs]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*['"`]/g,category:"sensitive-data",severity:"high",title:"Slack Token Detected",description:"Hardcoded Slack token found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for Slack tokens"},{id:"secret-generic-assignment",pattern:/\b\w*(?:SECRET|secret)(?:_KEY|_key|Key)?\s*[:=]\s*['"`][^'"`]{4,}['"`]/g,category:"sensitive-data",severity:"high",title:"Generic Secret Assignment Detected",description:"Hardcoded secret assignment (SECRET_KEY, JWT_SECRET, APP_SECRET, etc.) found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or a secrets manager instead of hardcoding secrets",fixExample:"const secretKey = process.env.SECRET_KEY"}],ld=[{id:"path-traversal-readfile",pattern:/(?:readFile|readFileSync)\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via File Read",description:"File read operation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate and sanitize file paths; use path.resolve() and check against base directory",fixExample:"const safePath = path.resolve(baseDir, path.basename(userInput))"},{id:"path-traversal-pattern",pattern:/\.\.\/.*\.\.\//g,category:"access-control",severity:"medium",title:"Path Traversal Pattern Detected",description:"Suspicious path traversal pattern (../) found in code",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate paths and ensure they resolve within expected directories"},{id:"path-traversal-writefile",pattern:/(?:writeFile|writeFileSync)\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via File Write",description:"File write operation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate file paths before writing; ensure path is within allowed directory"},{id:"path-traversal-createstream",pattern:/createReadStream\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via Stream",description:"Stream creation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate and sanitize file paths before creating streams"}],ud=[{id:"cmd-injection-exec",pattern:/exec\s*\([^)]*\+[^)]*\)|exec\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"critical",title:"Command Injection via exec()",description:"Shell command execution with unsanitized input",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Use execFile() with argument array instead of exec() with string concatenation",fixExample:'execFile("command", [arg1, arg2], callback)'},{id:"cmd-injection-spawn",pattern:/spawn\s*\(\s*[^,]+\+|spawn\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"critical",title:"Command Injection via spawn()",description:"Process spawn with potentially unsanitized command",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Use spawn with command and args array; validate inputs",fixExample:'spawn("command", [sanitizedArg1, sanitizedArg2])'},{id:"cmd-injection-shell-true",pattern:/spawn\s*\([^)]+,\s*\{[^}]*shell\s*:\s*true/g,category:"injection",severity:"high",title:"Dangerous Shell Option in spawn()",description:"spawn() with shell: true can enable command injection",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Avoid shell: true option; use direct command execution"}],dd=[{id:"misc-cors-wildcard",pattern:/cors\s*\(\s*\{[^}]*origin\s*:\s*['"]\*['"]/gi,category:"security-misconfiguration",severity:"medium",title:"Permissive CORS Configuration",description:"CORS allows all origins (*) which may expose sensitive data",owaspId:"A05:2021",cweId:"CWE-942",remediation:"Restrict CORS to specific trusted origins",fixExample:'cors({ origin: ["https://trusted-domain.com"] })'},{id:"misc-debug-enabled",pattern:/debug\s*[:=]\s*true|DEBUG\s*[:=]\s*['"]?true['"]?/gi,category:"security-misconfiguration",severity:"low",title:"Debug Mode Enabled",description:"Debug mode may expose sensitive information in production",owaspId:"A05:2021",cweId:"CWE-489",remediation:"Disable debug mode in production environments"},{id:"misc-ssl-disabled",pattern:/rejectUnauthorized\s*:\s*false|NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['"]?0['"]?/g,category:"security-misconfiguration",severity:"high",title:"TLS Certificate Validation Disabled",description:"Disabling TLS certificate validation exposes to MITM attacks",owaspId:"A05:2021",cweId:"CWE-295",remediation:"Always enable TLS certificate validation in production"},{id:"misc-helmet-missing",pattern:/app\.use\s*\(\s*express\s*\(\s*\)\s*\)/g,category:"security-misconfiguration",severity:"low",title:"Express App Without Security Headers",description:"Express app initialized without helmet or security headers",owaspId:"A05:2021",cweId:"CWE-693",remediation:"Use helmet middleware for security headers",fixExample:"app.use(helmet())"}],md=[{id:"deser-yaml-load",pattern:/yaml\.load\s*\([^)]+\)/g,category:"insecure-deserialization",severity:"high",title:"Unsafe YAML Deserialization",description:"yaml.load() can execute arbitrary code from untrusted YAML",owaspId:"A08:2021",cweId:"CWE-502",remediation:"Use yaml.safeLoad() or schema-constrained loading",fixExample:"yaml.load(content, { schema: yaml.SAFE_SCHEMA })"},{id:"deser-serialize-js",pattern:/serialize\s*\([^)]+\)|unserialize\s*\([^)]+\)/g,category:"insecure-deserialization",severity:"high",title:"Unsafe Serialization Function",description:"Node serialize/unserialize functions can execute arbitrary code",owaspId:"A08:2021",cweId:"CWE-502",remediation:"Use JSON.parse/stringify for serialization"}],pd=[{id:"auth-weak-jwt-secret",pattern:/jwt\.sign\s*\([^)]+,\s*['"][a-zA-Z0-9]{1,16}['"]/g,category:"broken-auth",severity:"high",title:"Weak JWT Secret",description:"JWT signed with a weak or short secret key",owaspId:"A07:2021",cweId:"CWE-327",remediation:"Use a strong, randomly generated secret of at least 256 bits"},{id:"auth-no-algorithm",pattern:/jwt\.verify\s*\([^)]+\)\s*(?!.*algorithm)/g,category:"broken-auth",severity:"medium",title:"JWT Without Algorithm Specification",description:"JWT verification without explicit algorithm can be exploited",owaspId:"A07:2021",cweId:"CWE-347",remediation:"Always specify the expected algorithm in JWT verification",fixExample:'jwt.verify(token, secret, { algorithms: ["HS256"] })'}],Po=[...ad,...od,...cd,...ld,...ud,...dd,...md,...pd],Ti=[{id:"owasp-top-10",name:"OWASP Top 10",description:"OWASP Top 10 most critical security risks",ruleCount:45,categories:["injection","broken-auth","sensitive-data","xxe","access-control","security-misconfiguration","xss","insecure-deserialization","vulnerable-components","insufficient-logging"]},{id:"cwe-sans-25",name:"CWE/SANS Top 25",description:"Most dangerous software errors",ruleCount:38,categories:["injection","xss","access-control","sensitive-data","broken-auth"]},{id:"nodejs-security",name:"Node.js Security",description:"Node.js specific security rules",ruleCount:25,categories:["injection","xss","sensitive-data","security-misconfiguration"]},{id:"typescript-security",name:"TypeScript Security",description:"TypeScript specific security rules",ruleCount:20,categories:["injection","xss","sensitive-data"]}];k();X();Pe();X();import{execFile as e0}from"child_process";import{promisify as t0}from"util";import*as Kh from"path";var gd=t0(e0),r0=["ERROR","WARNING","INFO","CRITICAL","HIGH","MEDIUM","LOW","EXPERIMENT","INVENTORY"];async function rs(){try{return await gd("semgrep",["--version"],{timeout:5e3}),!0}catch{return!1}}async function i0(){try{let{stdout:c}=await gd("semgrep",["--version"],{timeout:5e3});return c.trim()}catch{return null}}async function n0(c){let t={target:c.target||".",config:c.config||"auto",exclude:c.exclude||["node_modules",".git","dist","build","coverage"],maxFileSize:c.maxFileSize||5e6,timeout:c.timeout||300,verbose:c.verbose||!1};if(!await rs())return{success:!1,status:"unavailable",findings:[],errors:["Semgrep is unavailable."]};try{let r=["scan",`--config=${t.config}`,"--json",t.verbose?"--verbose":"--quiet",`--max-target-bytes=${t.maxFileSize}`];for(let o of t.exclude)r.push(`--exclude=${o}`);r.push(t.target);let i=(t.timeout??300)*1e3,{stdout:n,stderr:s}=await gd("semgrep",r,{timeout:i,maxBuffer:50*1024*1024,cwd:Kh.isAbsolute(t.target)?void 0:process.cwd()}),a=Qh(n);return s&&t.verbose&&(a.diagnostics=["Semgrep emitted diagnostic output."]),a.version=await i0()||void 0,a}catch(r){let i=r;if(typeof i.stdout=="string"&&i.stdout.length>0){let n=Qh(i.stdout);return i.code===1&&!i.killed&&!i.signal&&n.success&&n.findings.length>0?n:{...n,success:!1,status:"failed",errors:[...n.errors,"Semgrep process did not complete successfully."]}}return{success:!1,status:"failed",findings:[],errors:["Semgrep execution failed."]}}}function Qh(c){try{let t=D(c);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected a JSON object");let e=t.results??t.findings;if(!Array.isArray(e)||t.errors!==void 0&&!Array.isArray(t.errors))throw new Error("Missing or invalid result collection");let r=m=>!!m&&typeof m=="object"&&!Array.isArray(m),i=m=>m===void 0||typeof m=="string",n=m=>m===void 0||typeof m=="string"&&r0.includes(m),s=m=>m===void 0||r(m)&&["line","col"].every(p=>m[p]===void 0||typeof m[p]=="number"&&Number.isSafeInteger(m[p])&&m[p]>0),a=m=>m===void 0||r(m)&&["cwe","owasp","references"].every(p=>m[p]===void 0||Array.isArray(m[p])&&m[p].every(h=>typeof h=="string"))&&["category","description","fix","confidence"].every(p=>i(m[p])),o=m=>{if(!r(m))return!1;let p=m.check_id??m.rule_id;if(typeof m.path!="string"||m.path.length===0||typeof p!="string"||p.length===0||!s(m.start)||!s(m.end)||!i(m.message)||!n(m.severity)||!a(m.metadata))return!1;let h=m.extra;return h===void 0||r(h)&&["message","lines","fix"].every(v=>i(h[v]))&&n(h.severity)&&a(h.metadata)},l=e.filter(o),u=e.length-l.length,d=[];return t.errors?.length&&d.push(`Semgrep reported ${t.errors.length} analysis error(s).`),u&&d.push(`Semgrep returned ${u} malformed finding(s).`),{success:d.length===0,status:d.length===0?"completed":"partial",findings:l.map(m=>({check_id:m.check_id||m.rule_id||"unknown",path:m.path,start:{line:m.start?.line||1,col:m.start?.col||1},end:{line:m.end?.line||m.start?.line||1,col:m.end?.col||1},extra:{message:m.extra?.message||m.message||"Security issue detected",severity:m.extra?.severity||m.severity||"WARNING",lines:m.extra?.lines||"",metadata:{cwe:m.extra?.metadata?.cwe||m.metadata?.cwe,owasp:m.extra?.metadata?.owasp||m.metadata?.owasp,category:m.extra?.metadata?.category||m.metadata?.category,description:m.extra?.metadata?.description||m.metadata?.description,fix:m.extra?.metadata?.fix||m.extra?.fix,references:m.extra?.metadata?.references||m.metadata?.references,confidence:m.extra?.metadata?.confidence||m.metadata?.confidence}}})),errors:d}}catch{return{success:!1,status:"failed",findings:[],errors:["Invalid Semgrep output."]}}}async function ko(c,t,e){let r={"owasp-top-10":"p/owasp-top-ten","cwe-sans-25":"p/cwe-top-25","nodejs-security":"p/nodejs","typescript-security":"p/typescript","javascript-security":"p/javascript","react-security":"p/react","express-security":"p/express",secrets:"p/secrets","sql-injection":"p/sql-injection",xss:"p/xss","command-injection":"p/command-injection","path-traversal":"p/path-traversal"},i=t.map(n=>r[n]||`p/${n}`).join(",");return n0({...e,target:c,config:i||"auto"})}function s0(c){return{ERROR:"high",WARNING:"medium",INFO:"low",CRITICAL:"critical",HIGH:"high",MEDIUM:"medium",LOW:"low",EXPERIMENT:"low",INVENTORY:"low"}[c]||"medium"}function Do(c){return c.map(t=>({id:t.check_id,title:t.check_id.split(".").pop()||t.check_id,description:t.extra.message,severity:s0(t.extra.severity),file:t.path,line:t.start.line,column:t.start.col,snippet:t.extra.lines,cweId:t.extra.metadata?.cwe?.[0],owaspCategory:t.extra.metadata?.owasp?.[0],remediation:t.extra.metadata?.fix||"Review and fix the identified security issue",references:t.extra.metadata?.references||[]}))}var a0=x.create("security-compliance/sast-scanner"),Ei=class{config;memory;llmRouter;activeScans;constructor(t,e,r,i){this.config=t,this.memory=e,this.llmRouter=r,this.activeScans=i||new Map}async scanFiles(t){return this.scanWithRules(t,this.config.defaultRuleSets)}async scanWithRules(t,e){let r=w();try{if(t.length===0)return g(new Error("No files provided for scanning"));let i=Date.now(),n=Ti.filter(T=>e.includes(T.id));if(n.length===0)return g(new Error(`No valid rule sets found: ${e.join(", ")}`));if(e.filter(T=>!Ti.some(I=>I.id===T)).length>0)return g(new Error("Unknown rule sets requested; no scan executed."));this.activeScans.set(r,"running");let a=[...new Set(t.map(T=>ut.resolve(T.value)))],o=a.map(T=>he.create(T)),[l,u]=await Promise.all([this.runPatternScanning(o,n),this.runSemgrepScanning(o,e)]),d=this.mergeVulnerabilities(l.vulnerabilities,u.vulnerabilities),m=l.files.filter(T=>T.status==="analyzed"),p=m.reduce((T,I)=>T+I.analyzedLines,0),h=Date.now()-i,v=this.calculateSummary(d,m.length,h),b=this.getApplicablePatterns(n),C=m.length>0?[...new Set(b.map(T=>T.id))]:[],S={filesScanned:m.length,linesScanned:p,rulesApplied:C.length,rulesAppliedScope:"built-in-patterns"},R={id:"patterns",requested:!0,required:!0,scope:"requested-files",status:m.length===o.length?"completed":m.length>0?"partial":"failed",analyzedFiles:m.length,ruleIds:C,rulesetDigest:Jh("sha256").update(JSON.stringify(b.map(T=>({id:T.id,category:T.category,expression:T.pattern.source,flags:T.pattern.flags})))).digest("hex"),ruleCoverage:"known",errors:l.files.filter(T=>T.status==="unreadable").map(T=>T.reason||"File unreadable"),limitations:["Built-in pattern matching covers supported JavaScript and TypeScript inputs only."]},E={schemaVersion:1,completeness:m.length===o.length?"complete":m.length>0?"partial":"none",requestedFiles:o.length,requestedPaths:a,duplicateInputs:t.length-o.length,files:l.files,engines:[R,u.evidence],limitations:[...R.limitations,...u.evidence.limitations]};return await this.storeScanResults(r,"sast",d,v),this.activeScans.set(r,"completed"),f({scanId:r,vulnerabilities:d,summary:v,coverage:S,evidence:E})}catch(i){return this.activeScans.set(r,"failed"),g(y(i))}}async runPatternScanning(t,e){let r=[],i=[];for(let n of t){let s=await this.analyzeFile(n,e);r.push(...s.vulnerabilities),i.push(s.evidence)}return{vulnerabilities:r,files:i}}async runSemgrepScanning(t,e){let r=this.resolveTargetDirectory(t),i={id:"semgrep",requested:!!this.config.enableSemgrep,required:!1,status:"disabled",scope:"parent-directory",target:r,ruleCoverage:"unknown",errors:[],limitations:[]};if(!this.config.enableSemgrep)return{vulnerabilities:[],evidence:i};let n=["Optional Semgrep scans a parent directory; requested-file membership and executed-rule coverage are unverified."];try{if(!await rs())return{vulnerabilities:[],evidence:{...i,status:"unavailable",limitations:n,errors:["Semgrep is unavailable."]}};let s=await ko(r,e),a={...i,status:s.status||"unverified",version:s.version,errors:s.errors.length>0?[`Semgrep reported ${s.errors.length} execution error(s).`]:[],limitations:[...n,...s.diagnostics??[],...s.status?[]:["Legacy Semgrep adapter returned no execution disposition."]]};return{vulnerabilities:Do(s.findings).map(u=>({id:w(),cveId:void 0,title:u.title,description:`[semgrep] ${u.description}`,severity:u.severity,category:this.mapSemgrepCategory(u.owaspCategory),location:{file:u.file,line:u.line,column:u.column,snippet:u.snippet},remediation:{description:u.remediation,estimatedEffort:"moderate",automatable:!1},references:u.references})),evidence:a}}catch{return{vulnerabilities:[],evidence:{...i,status:"failed",limitations:n,errors:["Semgrep execution failed."]}}}}resolveTargetDirectory(t){if(t.length===0)return process.cwd();let e=ut.dirname(ut.resolve(t[0].value));for(let r of t.slice(1)){let i=ut.dirname(ut.resolve(r.value));for(;i!==e&&!i.startsWith(e.endsWith(ut.sep)?e:e+ut.sep);){let n=ut.dirname(e);if(n===e)break;e=n}}return e}mapSemgrepCategory(t){if(!t)return"injection";let e={A01:"access-control",A02:"sensitive-data",A03:"injection",A04:"insecure-deserialization",A05:"security-misconfiguration",A06:"vulnerable-components",A07:"broken-auth",A08:"insecure-deserialization",A09:"insufficient-logging",A10:"xxe"};for(let[r,i]of Object.entries(e))if(t.startsWith(r))return i;return"injection"}mergeVulnerabilities(t,e){if(e.length===0)return t;if(t.length===0)return e;let r=new Set(t.map(n=>`${n.location.file}:${n.location.line??0}:${n.category}`)),i=e.filter(n=>!r.has(`${n.location.file}:${n.location.line??0}:${n.category}`));return[...t,...i]}async getAvailableRuleSets(){let t=await this.memory.get("security:custom-rule-sets");return[...Ti,...t||[]]}async checkFalsePositive(t){try{if(!this.config.enableFalsePositiveDetection)return f({isFalsePositive:!1,confidence:0,reason:"False positive detection is disabled"});let e=await this.analyzeFalsePositive(t);return await this.memory.set(`security:fp-check:${t.id}`,{vulnerability:t,analysis:e},{namespace:"security-compliance",ttl:86400*30}),f(e)}catch(e){return g(y(e))}}getApplicablePatterns(t){let e=new Set(t.flatMap(r=>r.categories));return Po.filter(r=>e.has(r.category))}async analyzeFile(t,e){let r=[],i=t.value,n={path:i,engineId:"patterns",readLines:0,analyzedLines:0},s,a;try{let m=await Mm(i,{outsideRoot:"allow"});a=Jh("sha256").update(m).digest("hex"),s=m.toString("utf8")}catch(m){let p=m.code;return{vulnerabilities:[],evidence:{...n,status:"unreadable",reason:typeof p=="string"&&/^[A-Z0-9_]{1,32}$/.test(p)?p:"File unreadable"}}}let o=s.split(`
2882
2882
  `),l={...n,sourceDigest:a,readLines:o.length};if(!["ts","tsx","js","jsx","mjs","cjs"].includes(t.extension))return{vulnerabilities:[],evidence:{...l,status:"unsupported",reason:"Unsupported language for built-in SAST patterns"}};let d=this.getApplicablePatterns(e);for(let m of d){let p=this.findPatternMatches(s,o,m);for(let h of p)this.isInComment(s,h.index)||this.isInDocumentation(h.snippet)||this.hasNosecAnnotation(o,h.line)||r.push(this.createVulnerabilityFromPattern(m,i,h))}return{vulnerabilities:r,evidence:{...l,status:"analyzed",analyzedLines:o.length}}}findPatternMatches(t,e,r){let i=[],n=new RegExp(r.pattern.source,r.pattern.flags),s;for(;(s=n.exec(t))!==null;){let a=s.index,{line:o,column:l}=this.getLineAndColumn(t,a),u=[],d=Math.max(0,o-2),m=Math.min(e.length-1,o+1);for(let h=d;h<=m;h++)u.push(e[h]);let p=u.join(`
2883
2883
  `);i.push({index:a,line:o+1,column:l+1,snippet:p})}return i}getLineAndColumn(t,e){let i=t.substring(0,e).split(`
2884
2884
  `),n=i.length-1,s=i[i.length-1].length;return{line:n,column:s}}isInComment(t,e){let r=t.substring(0,e),i=r.lastIndexOf(`
@@ -2896,7 +2896,7 @@ Code context:
2896
2896
  ${e}
2897
2897
  \`\`\`
2898
2898
 
2899
- Provide detailed remediation advice specific to this code.`}],model:r,maxTokens:1500,temperature:.2,agentType:"qe-security-scanner"});if(i.content)try{let n=i.content.match(/\{[\s\S]*\}/);if(n){let s=D(n[0]);return{description:s.description||t.remediation?.description||"Review and fix the vulnerability",fixExample:s.fixExample||t.remediation?.fixExample,estimatedEffort:s.estimatedEffort||t.remediation?.estimatedEffort||"moderate",automatable:s.automatable??t.remediation?.automatable??!1,llmEnhanced:!0}}}catch{}}catch{s0.warn("LLM analysis failed:")}return this.getDefaultRemediation(t)}getDefaultRemediation(t){return t.remediation||{description:"Review and fix the vulnerability following security best practices",estimatedEffort:"moderate",automatable:!1}}};k();Wi();k();async function Io(c,t,e,r,i){for(let n of r){let s=new URLSearchParams(t.search);s.set(e,n.payload);let a=`${t.origin}${t.pathname}?${s.toString()}`,o=await fetch(a,{method:"GET",headers:{"User-Agent":"AgenticQE-DAST-Scanner/3.0"},signal:AbortSignal.timeout(5e3)});if(o.ok){let l=await o.text(),u=n.payload.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;"),d=l.includes(n.payload),m=l.includes(u);if(d&&!m){i.push({id:w(),title:`Reflected XSS: ${n.name}`,description:`Parameter '${e}' reflects unsanitized input`,severity:"critical",category:"xss",location:{file:c,snippet:`Parameter: ${e}, Payload: ${n.payload.substring(0,30)}...`},remediation:{description:"HTML-encode all user input before rendering",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-community/attacks/xss/"]});break}}}}async function Mo(c,t,e,r,i){let n=[/SQL syntax.*MySQL/i,/Warning.*mysql/i,/PostgreSQL.*ERROR/i,/ORA-\d{5}/i,/SQLite.*error/i,/SQLITE_ERROR/i,/unclosed quotation mark/i,/quoted string not properly terminated/i];for(let s of r){let a=new URLSearchParams(t.search);a.set(e,s.payload);let o=`${t.origin}${t.pathname}?${a.toString()}`,u=await(await fetch(o,{method:"GET",headers:{"User-Agent":"AgenticQE-DAST-Scanner/3.0"},signal:AbortSignal.timeout(5e3)})).text();for(let d of n)if(d.test(u)){i.push({id:w(),title:`SQL Injection: ${s.name}`,description:`Parameter '${e}' appears vulnerable to SQL injection`,severity:"critical",category:"injection",location:{file:c,snippet:`Parameter: ${e}`},remediation:{description:"Use parameterized queries or prepared statements",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-community/attacks/SQL_Injection"]});break}}}async function Fo(c,t,e,r,i){let n=["/admin","/dashboard","/api/users","/api/admin","/settings","/profile"];for(let s of n){if(e>=r*15)break;let a=new URL(s,c.origin).toString(),o=await fetch(a,{method:"GET",headers:{...t},signal:AbortSignal.timeout(5e3)});if(o.ok){e++;let l=await fetch(a,{method:"GET",signal:AbortSignal.timeout(5e3)});if(l.ok&&l.status===200){let u=await o.text(),d=await l.text();u.length>100&&d.length>100&&Math.abs(u.length-d.length)<u.length*.1&&i.push({id:w(),title:"Missing Authentication on Protected Endpoint",description:`Endpoint ${s} is accessible without authentication`,severity:"high",category:"broken-auth",location:{file:a},remediation:{description:"Implement proper authentication checks",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]})}}}return e}async function Lo(c,t,e,r,i){let n=["/api/users/1","/api/users/2","/api/orders/1","/profile/1"];for(let s of n.slice(0,2)){if(e>=r*15)break;let a=new URL(s,c.origin).toString(),o=await fetch(a,{method:"GET",headers:{...t},signal:AbortSignal.timeout(5e3)});if(o.ok){e++;let l=await o.text();(l.includes("email")||l.includes("password")||l.includes("phone"))&&i.push({id:w(),title:"Potential Insecure Direct Object Reference (IDOR)",description:`Endpoint ${s} may expose other users' data`,severity:"high",category:"access-control",location:{file:a},remediation:{description:"Implement proper authorization checks for resource access",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/05-Authorization_Testing/04-Testing_for_Insecure_Direct_Object_References"]})}}return e}function $o(c){switch(c.type){case"basic":if(!c.username||!c.password)return{valid:!1,reason:"Basic auth requires username and password"};break;case"bearer":case"oauth":if(!c.token)return{valid:!1,reason:"Bearer/OAuth auth requires token"};break;case"cookie":if(!c.token)return{valid:!1,reason:"Cookie auth requires session cookie"};break}return{valid:!0}}function Oo(c){let t={};switch(c.type){case"basic":if(c.username&&c.password){let e=Buffer.from(`${c.username}:${c.password}`).toString("base64");t.Authorization=`Basic ${e}`}break;case"bearer":case"oauth":c.token&&(t.Authorization=`Bearer ${c.token}`);break;case"cookie":c.token&&(t.Cookie=c.token);break}return t}function No(c,t,e,r=!1){let i=[{header:"strict-transport-security",title:"Missing HSTS Header",severity:"medium",remediation:"Add Strict-Transport-Security header"},{header:"x-content-type-options",title:"Missing X-Content-Type-Options",severity:"low",remediation:"Add X-Content-Type-Options: nosniff"},{header:"x-frame-options",title:"Missing X-Frame-Options",severity:"medium",remediation:"Add X-Frame-Options: DENY or SAMEORIGIN"},{header:"content-security-policy",title:"Missing Content-Security-Policy",severity:"medium",remediation:"Implement a Content-Security-Policy"}];r||i.push({header:"referrer-policy",title:"Missing Referrer-Policy",severity:"low",remediation:"Add Referrer-Policy header"},{header:"permissions-policy",title:"Missing Permissions-Policy",severity:"low",remediation:"Add Permissions-Policy header"});for(let n of i)c.get(n.header)||e.push({id:w(),title:n.title,description:`Security header ${n.header} is not present in the response`,severity:n.severity,category:"security-misconfiguration",location:{file:t,snippet:`Missing: ${n.header}`},remediation:{description:n.remediation,estimatedEffort:"minor",automatable:!0},references:["https://owasp.org/www-project-secure-headers/"]})}function _o(c,t,e,r=!1){let i=c.get("set-cookie");if(!i)return;let n=i.toLowerCase(),s=r?"high":"medium";n.includes("secure")||e.push({id:w(),title:r?"Session Cookie Missing Secure Flag":"Cookie Missing Secure Flag",description:r?"Authenticated session cookie is not marked as Secure":"Cookie is set without the Secure attribute",severity:s,category:"sensitive-data",location:{file:t,snippet:"Set-Cookie header without Secure flag"},remediation:{description:"Add Secure flag to all cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/controls/SecureCookieAttribute"]}),n.includes("httponly")||e.push({id:w(),title:r?"Session Cookie Missing HttpOnly Flag":"Cookie Missing HttpOnly Flag",description:r?"Session cookie is accessible to JavaScript":"Cookie is accessible to client-side JavaScript",severity:s,category:"sensitive-data",location:{file:t,snippet:"Set-Cookie header without HttpOnly flag"},remediation:{description:"Add HttpOnly flag to session cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/HttpOnly"]})}function hd(c,t,e){let r=c.get("server")||c.get("x-powered-by");r&&/\d+\.\d+/.test(r)&&e.push({id:w(),title:"Server Version Disclosure",description:`Server version information exposed: ${r}`,severity:"low",category:"security-misconfiguration",location:{file:t,snippet:`Server: ${r}`},remediation:{description:"Remove or obfuscate server version headers",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]})}async function fd(c,t,e,r){let i=[{path:"/.git/config",name:"Git Configuration"},{path:"/.env",name:"Environment File"},{path:"/robots.txt",name:"Robots.txt"},{path:"/sitemap.xml",name:"Sitemap"},{path:"/.htaccess",name:"htaccess File"},{path:"/web.config",name:"IIS Configuration"}];for(let n of i){if(t>=e*10)break;let s=new URL(n.path,c.origin).toString(),a=await fetch(s,{method:"GET",signal:AbortSignal.timeout(5e3)});if(a.ok){t++;let o=await a.text();o.length>20&&!o.toLowerCase().includes("not found")&&!o.toLowerCase().includes("404")&&(n.path.includes(".git")||n.path.includes(".env")||n.path.includes(".htaccess")||n.path.includes("web.config"))&&r.push({id:w(),title:`Sensitive File Exposed: ${n.name}`,description:`${n.name} is publicly accessible`,severity:n.path.includes(".git")||n.path.includes(".env")?"high":"medium",category:"sensitive-data",location:{file:s},remediation:{description:`Restrict access to ${n.path}`,estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]})}}return t}async function yd(c,t){let r=(await fetch(c,{method:"OPTIONS",headers:{Origin:"https://evil-attacker.com","Access-Control-Request-Method":"GET"},signal:AbortSignal.timeout(5e3)})).headers.get("access-control-allow-origin");(r==="*"||r==="https://evil-attacker.com")&&t.push({id:w(),title:"Overly Permissive CORS Policy",description:r==="*"?"CORS allows all origins":"CORS reflects arbitrary origin",severity:"medium",category:"access-control",location:{file:c,snippet:`Access-Control-Allow-Origin: ${r}`},remediation:{description:"Restrict CORS to specific trusted origins",estimatedEffort:"minor",automatable:!1},references:["https://owasp.org/www-community/attacks/CORS_OriginHeaderScrutiny"]})}async function vd(c,t,e,r,i){let n=e,s=r*5,a=/href=["']([^"']+)["']/gi,o=new Set,l;for(;(l=a.exec(c))!==null;){let d=l[1];try{let m=new URL(d,t.origin);m.origin===t.origin&&!o.has(m.pathname)&&o.add(m.pathname)}catch{}}let u=Array.from(o).slice(0,Math.min(10,s-n));for(let d of u){if(n>=s)break;let m=new URL(d,t.origin).toString(),p=await fetch(m,{method:"GET",headers:{"User-Agent":"AgenticQE-DAST-Scanner/3.0"},signal:AbortSignal.timeout(5e3),redirect:"follow"});if(n++,p.ok){(d.includes("password")||d.includes("token")||d.includes("api_key"))&&i.push({id:w(),title:"Sensitive Data in URL Path",description:`URL path may contain sensitive parameter names: ${d}`,severity:"medium",category:"sensitive-data",location:{file:m},remediation:{description:"Avoid sensitive data in URL paths",estimatedEffort:"minor",automatable:!1},references:["https://owasp.org/www-community/vulnerabilities/Information_exposure_through_query_strings_in_url"]});let h=await p.text();(h.includes("Index of /")||h.includes("Directory listing for"))&&i.push({id:w(),title:"Directory Listing Enabled",description:`Directory listing is enabled at: ${m}`,severity:"medium",category:"security-misconfiguration",location:{file:m},remediation:{description:"Disable directory listing in server configuration",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]})}}return n}function bd(c,t,e){let r=/<form[^>]*>([\s\S]*?)<\/form>/gi,i,n=0;for(;(i=r.exec(c))!==null&&n<10;){n++;let s=i[0],a=i[1],o=/name=["']?csrf/i.test(a)||/name=["']?_token/i.test(a)||/name=["']?authenticity_token/i.test(a)||/name=["']?__RequestVerificationToken/i.test(a);/method=["']?post/i.test(s)&&!o&&e.push({id:w(),title:"Missing CSRF Token",description:`POST form #${n} does not appear to have CSRF protection`,severity:"medium",category:"broken-auth",location:{file:t,snippet:`Form #${n}`},remediation:{description:"Add CSRF token to all state-changing forms",estimatedEffort:"minor",automatable:!1},references:["https://owasp.org/www-community/attacks/csrf"]}),/type=["']?password/i.test(a)&&(/autocomplete=["']?(off|new-password)/i.test(a)||/autocomplete=["']?(off|new-password)/i.test(s)||e.push({id:w(),title:"Password Field Allows Autocomplete",description:`Form #${n} has password field that may be cached by browser`,severity:"low",category:"sensitive-data",location:{file:t,snippet:`Form #${n}`},remediation:{description:'Add autocomplete="new-password" to password fields',estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]}));let u=/action=["']?([^"'\s>]+)/i.exec(s);if(u){let d=u[1];d.startsWith("http://")&&!d.includes("localhost")&&!d.includes("127.0.0.1")&&e.push({id:w(),title:"Form Submits to Insecure HTTP",description:`Form #${n} submits data over insecure HTTP: ${d}`,severity:"high",category:"sensitive-data",location:{file:t,snippet:`Action: ${d}`},remediation:{description:"Change form action to use HTTPS",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]})}}}function Vo(c,t,e){let r={critical:0,high:0,medium:0,low:0,informational:0,totalFiles:t,scanDurationMs:e};for(let i of c)r[i.severity]++;return r}async function zo(c,t,e,r,i){await c.set(`security:scan:${t}`,{scanId:t,scanType:e,vulnerabilities:r,summary:i,timestamp:new Date().toISOString()},{namespace:"security-compliance",ttl:86400*7})}function Yh(c){if(c instanceof Error&&"code"in c&&["DAST_AUTHENTICATION_FAILED","DAST_TARGET_UNAVAILABLE"].includes(String(c.code)))return c;let t=c instanceof Error&&/timeout|abort/i.test(c.message);return Object.assign(new Error(t?"DAST target request timeout; dynamic analysis is incomplete":"DAST target request failed; dynamic analysis is incomplete"),{code:t?"DAST_REQUEST_TIMEOUT":"DAST_REQUEST_FAILED"})}var Ai=class{config;memory;activeScans;constructor(t,e,r){this.config=t,this.memory=e,this.activeScans=r||new Map}async scanUrl(t,e){let r=w();try{this.activeScans.set(r,"running");let i=Date.now(),n={maxDepth:e?.maxDepth??this.config.dastMaxDepth,activeScanning:e?.activeScanning??this.config.dastActiveScanning,timeout:e?.timeout??this.config.timeout,excludePatterns:e?.excludePatterns??[]},s=await this.performDynamicScan(t,n),a=Date.now()-i,o=Vo(s.vulnerabilities,1,a);return await zo(this.memory,r,"dast",s.vulnerabilities,o),this.activeScans.set(r,"completed"),f({scanId:r,targetUrl:t,vulnerabilities:s.vulnerabilities,summary:o,crawledUrls:s.crawledUrls})}catch(i){return this.activeScans.set(r,"failed"),g(y(i))}}async scanAuthenticated(t,e,r){let i=w();try{this.activeScans.set(i,"running");let n=Date.now(),s=$o(e);if(!s.valid)throw new Error(s.reason);let a={maxDepth:r?.maxDepth??this.config.dastMaxDepth,activeScanning:r?.activeScanning??this.config.dastActiveScanning,timeout:r?.timeout??this.config.timeout,excludePatterns:r?.excludePatterns??[]},o=await this.performAuthenticatedScan(t,e,a),l=Date.now()-n,u=Vo(o.vulnerabilities,1,l);return await zo(this.memory,i,"dast-auth",o.vulnerabilities,u),this.activeScans.set(i,"completed"),f({scanId:i,targetUrl:t,vulnerabilities:o.vulnerabilities,summary:u,crawledUrls:o.crawledUrls})}catch(n){return this.activeScans.set(i,"failed"),g(y(n))}}async getScanStatus(t){return this.activeScans.get(t)??"pending"}async performDynamicScan(t,e){let r=[],i=0;try{let n;try{n=new URL(t)}catch{return r.push(this.createInvalidUrlVuln(t)),{vulnerabilities:r,crawledUrls:0}}let s=e.timeout??this.config.timeout,a=e.maxDepth??this.config.dastMaxDepth,o=Math.min(s,3e4);try{let l=await et(t,{method:"GET",headers:{"User-Agent":"AgenticQE-DAST-Scanner/3.0",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"},redirect:"follow"},o,()=>new Error(`DAST request timeout after ${o}ms: ${t}`));if(l.status===401||l.status===403||l.status>=500)throw await l.body?.cancel().catch(()=>{}),Object.assign(new Error(`DAST ${l.status<500?"authentication rejected":"target unavailable"} (HTTP ${l.status}); dynamic analysis is incomplete`),{code:l.status<500?"DAST_AUTHENTICATION_FAILED":"DAST_TARGET_UNAVAILABLE"});if(i++,No(l.headers,t,r),n.protocol==="http:"&&r.push(this.createInsecureProtocolVuln(t)),_o(l.headers,t,r),hd(l.headers,t,r),e.activeScanning??this.config.dastActiveScanning){let u=await l.text();i=await fd(n,i,a,r),await yd(t,r),i=await vd(u,n,i,a,r),n.search&&await this.testInjectionVulnerabilities(t,n,r),bd(u,t,r)}else await l.body?.cancel().catch(()=>{})}catch(l){throw Yh(l)}}catch(n){throw y(n)}return{vulnerabilities:r,crawledUrls:i}}async performAuthenticatedScan(t,e,r){let i=[],n=0;try{let s=Oo(e),a;try{a=new URL(t)}catch{return i.push(this.createInvalidUrlVuln(t)),{vulnerabilities:i,crawledUrls:0}}let o=r.timeout??this.config.timeout,l=r.maxDepth??this.config.dastMaxDepth,u=Math.min(o,3e4);try{let d=await et(t,{method:"GET",headers:{"User-Agent":"AgenticQE-DAST-Scanner/3.0",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",...s},redirect:"follow"},u,()=>new Error(`DAST request timeout after ${u}ms: ${t}`));if(await d.body?.cancel().catch(()=>{}),d.status===401||d.status===403||d.status>=500)throw await d.body?.cancel().catch(()=>{}),Object.assign(new Error(`DAST ${d.status<500?"authentication rejected":"target unavailable"} (HTTP ${d.status}); dynamic analysis is incomplete`),{code:d.status<500?"DAST_AUTHENTICATION_FAILED":"DAST_TARGET_UNAVAILABLE"});n++,No(d.headers,t,i,!0),(a.search.includes("token=")||a.search.includes("session=")||a.search.includes("auth="))&&i.push(this.createTokenInUrlVuln(t,a.search)),(r.activeScanning??this.config.dastActiveScanning)&&(n=await Fo(a,s,n,l,i),n=await Lo(a,s,n,l,i)),_o(d.headers,t,i,!0)}catch(d){throw Yh(d)}}catch(s){throw y(s)}return{vulnerabilities:i,crawledUrls:n}}createInvalidUrlVuln(t){return{id:w(),title:"Invalid Target URL",description:"The provided target URL is not valid",severity:"informational",category:"security-misconfiguration",location:{file:t},remediation:{description:"Provide a valid URL",estimatedEffort:"trivial",automatable:!1},references:[]}}createInsecureProtocolVuln(t){return{id:w(),title:"Insecure HTTP Protocol",description:"Application is accessible over unencrypted HTTP",severity:"high",category:"sensitive-data",location:{file:t},remediation:{description:"Redirect all HTTP traffic to HTTPS",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]}}createTokenInUrlVuln(t,e){return{id:w(),title:"Session Token in URL",description:"Authentication token appears in URL query string",severity:"high",category:"sensitive-data",location:{file:t,snippet:e.substring(0,50)},remediation:{description:"Send tokens in headers or request body, not URL",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-community/vulnerabilities/Information_exposure_through_query_strings_in_url"]}}async testInjectionVulnerabilities(t,e,r){let i=new URLSearchParams(e.search),n=Array.from(i.keys()),s=[{payload:"<script>alert(1)</script>",name:"Basic XSS"},{payload:'"><img src=x onerror=alert(1)>',name:"Attribute Injection"},{payload:"'-alert(1)-'",name:"JavaScript Injection"}],a=[{payload:"' OR '1'='1",name:"SQL OR Injection"},{payload:"1; DROP TABLE test--",name:"SQL Statement Injection"},{payload:"1' AND '1'='1",name:"SQL AND Injection"}];for(let o of n.slice(0,3))await Io(t,e,o,s,r),await Mo(t,e,o,a,r)}};import{isIP as af}from"node:net";k();Wi();var a0=3e4,o0=4,c0=3,l0=1e3,u0=5,d0=3e4,wd=class{circuits=new Map;getCircuitKey(t){try{return new URL(t).origin}catch{return t}}getState(t){let e=this.getCircuitKey(t);return this.circuits.has(e)||this.circuits.set(e,{failures:0,lastFailure:null,state:"closed"}),this.circuits.get(e)}recordSuccess(t){let e=this.getCircuitKey(t);this.circuits.set(e,{failures:0,lastFailure:null,state:"closed"})}recordFailure(t){let e=this.getCircuitKey(t),i=this.getState(t).failures+1;this.circuits.set(e,{failures:i,lastFailure:Date.now(),state:i>=u0?"open":"closed"})}canRequest(t){let e=this.getState(t);if(e.state==="closed")return!0;if(e.state==="open"){if((e.lastFailure?Date.now()-e.lastFailure:1/0)>=d0){let i=this.getCircuitKey(t);return this.circuits.set(i,{...e,state:"half-open"}),!0}return!1}return!1}reset(t){if(t){let e=this.getCircuitKey(t);this.circuits.delete(e)}else this.circuits.clear()}},gt=class{circuitBreaker;constructor(){this.circuitBreaker=new wd}async get(t,e){return this.request(t,{method:"GET"},e)}async post(t,e,r){return this.request(t,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}},r)}async put(t,e,r){return this.request(t,{method:"PUT",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}},r)}async patch(t,e,r){return this.request(t,{method:"PATCH",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}},r)}async delete(t,e){return this.request(t,{method:"DELETE"},e)}async healthCheck(t){let e=await this.get(t,{timeout:5e3,retries:1,circuitBreaker:!1});return e.success?e.value.ok:!1}getCircuitState(t){return this.circuitBreaker.getState(t)}resetCircuit(t){this.circuitBreaker.reset(t)}async request(t,e,r){let i=r?.timeout??a0,n=r?.maxDurationMs??i*o0,s=r?.retries??c0,a=r?.retryDelay??l0,o=r?.circuitBreaker??!0,l={...e.headers,...r?.headers},u={startTime:Date.now(),endTime:0,duration:0,retryCount:0};if(o&&!this.circuitBreaker.canRequest(t))return u.endTime=Date.now(),u.duration=u.endTime-u.startTime,g({message:"Circuit breaker is open",code:"CIRCUIT_OPEN",timing:u});let d=null;for(let m=0;m<=s;m++){u.retryCount=m;try{let p=await this.fetchWithTimeout(t,{...e,headers:l},i,n);return u.endTime=Date.now(),u.duration=u.endTime-u.startTime,o&&this.circuitBreaker.recordSuccess(t),f(p)}catch(p){if(d=y(p),o&&this.circuitBreaker.recordFailure(t),m<s){let h=a*Math.pow(2,m);await this.sleep(h)}}}return u.endTime=Date.now(),u.duration=u.endTime-u.startTime,g({message:d?.message||"Request failed",code:this.getErrorCode(d),cause:d??void 0,timing:u})}async fetchWithTimeout(t,e,r,i){return et(t,e,r,()=>Object.assign(new Error(`Request timeout (idle ${r}ms, cap ${i}ms): ${t}`),{name:"TimeoutError"}),"idle",i)}getErrorCode(t){if(!t)return"UNKNOWN_ERROR";let e=new Set,r=t;for(;typeof r=="object"&&r!==null&&!e.has(r);){e.add(r);let i=r;if(i.name==="AbortError"||i.name==="TimeoutError")return"TIMEOUT";let n=typeof i.message=="string"?i.message:"";if(i.code==="ECONNREFUSED"||n.includes("ECONNREFUSED"))return"CONNECTION_REFUSED";if(i.code==="ENOTFOUND"||n.includes("ENOTFOUND"))return"DNS_ERROR";if(i.code==="ETIMEDOUT"||n.includes("ETIMEDOUT"))return"NETWORK_TIMEOUT";r=i.cause}return"REQUEST_FAILED"}sleep(t){return new Promise(e=>setTimeout(e,t))}};function is(){return new gt}hr();var Ke=class c extends Error{lookup;constructor(t,e){super(t),this.name="OSVLookupError",this.lookup=e}static fromLookup(t){let e=[...new Set(t.unchecked.map(r=>r.reason))].slice(0,3).join("; ");return new c(`OSV advisories could not be checked for ${t.unchecked.length} of ${t.packagesRequested} package(s): ${e}`,t)}},nr=c=>`${c.ecosystem}:${c.name}@${c.version??""}`;function ef(c,t=5){return c.length<=t?c.join(", "):`${c.slice(0,t).join(", ")} and ${c.length-t} more`}function xi(c){let t=/^=?v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/.exec(c.trim());return t?t[1]:null}function Bo(c){let t=c.trim(),e=/^npm:((?:@[^/@\s]+\/)?[^@\s]+)(?:@(.*))?$/.exec(t);return e?{kind:"alias",name:e[1],spec:e[2]??""}:/^(workspace:|link:|portal:)/.test(t)?{kind:"local"}:/^file:/.test(t)?/\.(tgz|tar\.gz|tar)$/i.test(t)?{kind:"remote"}:{kind:"local"}:/^(\.{0,2}\/|~\/)/.test(t)?/\.(tgz|tar\.gz|tar)$/i.test(t)?{kind:"remote"}:{kind:"local"}:/^(patch:|exec:|git\+|git:|github:|gitlab:|bitbucket:|https?:)/.test(t)?{kind:"remote"}:/^[^\s@/:]+\/[^\s@/:]+(#.*)?$/.test(t)?{kind:"remote"}:{kind:"registry",spec:t}}function tf(c){return c.length===0||c.length>m0||!g0(c)?!1:!/(^|\.)[xX*](\.|$)/.test(c)}var m0=256,p0=/^\d+(?:\.\d+)*$/,Xh=/^[0-9A-Za-z][0-9A-Za-z.+-]*$/;function g0(c){let t=c.indexOf("_");if(t>=0)return p0.test(c.slice(0,t))&&Xh.test(c.slice(t+1));let e=0;for(;e<c.length&&c.charCodeAt(e)>=48&&c.charCodeAt(e)<=57;)e++;if(e===0)return!1;let r=c.slice(e);if(r===""||e>=2&&h0.test(r))return!0;let i=r[0]==="-"||r[0]==="+"||r[0]===".";return Xh.test(i?r.slice(1):r)}var h0=/^[0-9A-Za-z.+-]*$/,Or=c=>!!c&&typeof c=="object"&&!Array.isArray(c);function rf(c,t){return!Or(c)||!Array.isArray(c.results)||c.results.length!==t?null:c.results.map(e=>{if(!Or(e))return{reason:"malformed OSV result entry"};if(typeof e.next_page_token=="string"&&e.next_page_token)return{reason:"OSV advisory list was truncated (paginated) and not fully retrieved"};if(e.vulns===void 0)return{ids:[]};if(!Array.isArray(e.vulns))return{reason:"malformed OSV result entry"};let r=[];for(let i of e.vulns){if(!Or(i)||typeof i.id!="string"||!i.id)return{reason:"malformed OSV advisory reference"};r.push(i.id)}return{ids:r}})}function Cd(c){return Or(c)&&typeof c.id=="string"&&Array.isArray(c.affected)}function nf(c){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(c.trim());return t?{nums:[Number(t[1]),Number(t[2]),Number(t[3])],pre:t[4]?t[4].split("."):[]}:null}function Zh(c,t){for(let e=0;e<3;e++)if(c.nums[e]!==t.nums[e])return c.nums[e]<t.nums[e]?-1:1;if(c.pre.length===0||t.pre.length===0)return c.pre.length===t.pre.length?0:c.pre.length===0?1:-1;for(let e=0;e<Math.max(c.pre.length,t.pre.length);e++){let r=c.pre[e],i=t.pre[e];if(r===void 0||i===void 0)return r===void 0?-1:1;if(r===i)continue;let n=/^\d+$/.test(r),s=/^\d+$/.test(i);return n&&s?Number(r)<Number(i)?-1:1:n!==s?n?-1:1:r<i?-1:1}return 0}function f0(c,t){let e=[];for(let n of t){let s=n.introduced!==void 0?"introduced":n.fixed!==void 0?"fixed":n.last_affected!==void 0?"last_affected":null;if(!s)continue;let a=n[s];if(s==="introduced"&&a==="0"){e.push({at:null,kind:s});continue}let o=nf(a);if(!o)return null;e.push({at:o,kind:s})}let r=n=>n==="introduced"?1:0;e.sort((n,s)=>!n.at||!s.at?n.at===s.at?0:n.at?1:-1:Zh(n.at,s.at)||r(n.kind)-r(s.kind));let i=!1;for(let{at:n,kind:s}of e){if(!n){i=!0;continue}let a=Zh(c,n);s==="introduced"&&a>=0?i=!0:(s==="fixed"&&a>=0||s==="last_affected"&&a>0)&&(i=!1)}return i}function sf(c,t){let e=c.affected;if(!Array.isArray(e))return!0;let r=e.filter(n=>Or(n)&&Or(n.package)&&n.package.name===t.name&&n.package.ecosystem===t.ecosystem);if(r.length===0)return!0;let i=nf(t.version);for(let n of r){if(Array.isArray(n.versions)&&n.versions.includes(t.version))return!0;let s=Array.isArray(n.ranges)?n.ranges.filter(Or):[];if(s.length===0&&!Array.isArray(n.versions))return!0;for(let a of s)if(a.type!=="SEMVER"||!i||!Array.isArray(a.events)||f0(i,a.events)!==!1)return!0}return!1}function qo(c,t){return t===c?"complete":t===0?"failed":"incomplete"}var y0="https://api.osv.dev";function v0(c){let t=c.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"?!0:af(t)===4?t.startsWith("127."):af(t)===6&&(t==="::1"||t==="0:0:0:0:0:0:0:1")}function Sd(c=process.env){let t=c.AQE_OSV_API_URL?.trim();if(!t)return y0;if(t.length>of)throw new Error(`AQE_OSV_API_URL is longer than ${of} characters (expected https://host)`);let e;try{e=new URL(t)}catch{throw new Error(`AQE_OSV_API_URL is not a URL: "${t.slice(0,200)}" (expected https://host)`)}let r=v0(e.hostname);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&r))throw new Error(`AQE_OSV_API_URL must use https (http only for localhost/loopback): "${t.slice(0,200)}"`);let i=t;for(;i.endsWith("/");)i=i.slice(0,-1);return i}var of=2048,Nr=class{config;configuredBaseUrl;endpoint=null;http;detailCache=new Map;constructor(t={}){this.configuredBaseUrl=t.baseUrl,this.config={timeout:t.timeout??3e4,retries:t.retries??2,batchSize:Math.max(1,Math.min(1e3,t.batchSize??500)),detailConcurrency:Math.max(1,t.detailConcurrency??8),enableCache:t.enableCache??!0,cacheTtl:t.cacheTtl??3600*1e3},this.http=new gt}get baseUrl(){let t=this.resolveEndpoint();return"url"in t?t.url:null}resolveEndpoint(){if(!this.endpoint)try{this.endpoint={url:this.configuredBaseUrl!==void 0?Sd({AQE_OSV_API_URL:this.configuredBaseUrl}):Sd()}}catch(t){this.endpoint={reason:t instanceof Error?t.message:String(t)}}return this.endpoint}get base(){let t=this.resolveEndpoint();if("reason"in t)throw new Ke(t.reason);return t.url}async lookupBatch(t){let e=new Map,r=[],i=[],n=[],s=0,a=this.resolveEndpoint();if("reason"in a)return{status:qo(t.length,0),results:e,packagesRequested:t.length,packagesChecked:0,unchecked:t.map(d=>({...d,reason:a.reason})),errors:[a.reason]};for(let d of t)d.version&&tf(d.version)?n.push(d):r.push({...d,reason:d.version?`version "${d.version}" is a range or tag, not a concrete version (no lockfile resolution)`:"no version declared; advisories cannot be matched"});let o=[];for(let d=0;d<n.length;d+=this.config.batchSize){let m=n.slice(d,d+this.config.batchSize),p=await this.postBatch(m);if("reason"in p){i.push(`querybatch for ${m.length} package(s) failed: ${p.reason}`);for(let h of m)r.push({...h,reason:p.reason});continue}p.entries.forEach((h,v)=>{"reason"in h?r.push({...m[v],reason:h.reason}):o.push({pkg:m[v],ids:h.ids})})}let l=await this.fetchDetails([...new Set(o.flatMap(d=>d.ids))]);for(let{pkg:d,ids:m}of o){let p=m.filter(v=>"reason"in l.get(v));if(p.length>0){let v=l.get(p[0]).reason;r.push({...d,reason:`advisory details unavailable for ${ef(p)}: ${v}`});continue}let h=m.map(v=>l.get(v).vuln).filter(v=>sf(v,{name:d.name,ecosystem:d.ecosystem,version:d.version}));e.set(nr(d),this.parseVulnerabilities(h).map(v=>({...v,affectedPackage:d.name}))),s++}let u=[...l.values()].filter(d=>"reason"in d);return u.length>0&&i.push(`${u.length} advisory detail request(s) failed: ${u[0].reason}`),{status:qo(t.length,s),results:e,packagesRequested:t.length,packagesChecked:s,unchecked:r,errors:i}}async lookupNpmDependencies(t,e={}){let r=[],i=[];for(let[a,o]of Object.entries(t)){let l=Bo(o);if(l.kind==="local"||l.kind==="remote"){i.push({name:a,ecosystem:"npm",version:o,reason:l.kind==="local"?`local package ("${o}"); not an OSV subject`:`not a registry dependency ("${o}": git/URL/tarball source); OSV advisories cannot be matched`});continue}let u=l.kind==="alias"?l.name:a,d=gr(e,a),p=(d!==void 0?xi(d):null)??xi(l.spec);p?r.push({name:u,ecosystem:"npm",version:p}):i.push({name:a,ecosystem:"npm",version:o,reason:`version range "${o}", no lockfile resolution`})}let n=await this.lookupBatch(r),s=r.length+i.length;return{...n,status:qo(s,n.packagesChecked),packagesRequested:s,unchecked:[...i,...n.unchecked]}}async queryPackage(t,e,r){let i=await this.http.post(`${this.base}/v1/query`,{package:{name:t,ecosystem:e},...r&&{version:r}},this.requestOptions()),n=await this.readJson(i);if("reason"in n)throw new Ke(`OSV query for ${e}:${t} failed: ${n.reason}`);let s=n.value?.vulns;if(s===void 0&&n.value&&typeof n.value=="object")return[];if(!Array.isArray(s)||!s.every(Cd))throw new Ke(`OSV query for ${e}:${t} failed: malformed response`);return this.parseVulnerabilities(s)}async queryBatch(t){let e=await this.lookupBatch(t);if(e.status!=="complete")throw Ke.fromLookup(e);return e.results}async queryByCVE(t){this.base;let e=await this.fetchDetail(t);if("vuln"in e)return this.parseVulnerabilities([e.vuln]);if(e.reason==="HTTP 404")return[];throw new Ke(`OSV lookup for ${t} failed: ${e.reason}`)}async scanNpmDependencies(t){let e=await this.lookupNpmDependencies(t);if(e.status!=="complete")throw Ke.fromLookup(e);return[...e.results.values()].flat()}async scanPythonRequirements(t){let e=t.split(`
2899
+ Provide detailed remediation advice specific to this code.`}],model:r,maxTokens:1500,temperature:.2,agentType:"qe-security-scanner"});if(i.content)try{let n=i.content.match(/\{[\s\S]*\}/);if(n){let s=D(n[0]);return{description:s.description||t.remediation?.description||"Review and fix the vulnerability",fixExample:s.fixExample||t.remediation?.fixExample,estimatedEffort:s.estimatedEffort||t.remediation?.estimatedEffort||"moderate",automatable:s.automatable??t.remediation?.automatable??!1,llmEnhanced:!0}}}catch{}}catch{a0.warn("LLM analysis failed:")}return this.getDefaultRemediation(t)}getDefaultRemediation(t){return t.remediation||{description:"Review and fix the vulnerability following security best practices",estimatedEffort:"moderate",automatable:!1}}};k();Wi();k();async function Io(c,t,e,r,i){for(let n of r){let s=new URLSearchParams(t.search);s.set(e,n.payload);let a=`${t.origin}${t.pathname}?${s.toString()}`,o=await fetch(a,{method:"GET",headers:{"User-Agent":"AgenticQE-DAST-Scanner/3.0"},signal:AbortSignal.timeout(5e3)});if(o.ok){let l=await o.text(),u=n.payload.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;"),d=l.includes(n.payload),m=l.includes(u);if(d&&!m){i.push({id:w(),title:`Reflected XSS: ${n.name}`,description:`Parameter '${e}' reflects unsanitized input`,severity:"critical",category:"xss",location:{file:c,snippet:`Parameter: ${e}, Payload: ${n.payload.substring(0,30)}...`},remediation:{description:"HTML-encode all user input before rendering",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-community/attacks/xss/"]});break}}}}async function Mo(c,t,e,r,i){let n=[/SQL syntax.*MySQL/i,/Warning.*mysql/i,/PostgreSQL.*ERROR/i,/ORA-\d{5}/i,/SQLite.*error/i,/SQLITE_ERROR/i,/unclosed quotation mark/i,/quoted string not properly terminated/i];for(let s of r){let a=new URLSearchParams(t.search);a.set(e,s.payload);let o=`${t.origin}${t.pathname}?${a.toString()}`,u=await(await fetch(o,{method:"GET",headers:{"User-Agent":"AgenticQE-DAST-Scanner/3.0"},signal:AbortSignal.timeout(5e3)})).text();for(let d of n)if(d.test(u)){i.push({id:w(),title:`SQL Injection: ${s.name}`,description:`Parameter '${e}' appears vulnerable to SQL injection`,severity:"critical",category:"injection",location:{file:c,snippet:`Parameter: ${e}`},remediation:{description:"Use parameterized queries or prepared statements",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-community/attacks/SQL_Injection"]});break}}}async function Fo(c,t,e,r,i){let n=["/admin","/dashboard","/api/users","/api/admin","/settings","/profile"];for(let s of n){if(e>=r*15)break;let a=new URL(s,c.origin).toString(),o=await fetch(a,{method:"GET",headers:{...t},signal:AbortSignal.timeout(5e3)});if(o.ok){e++;let l=await fetch(a,{method:"GET",signal:AbortSignal.timeout(5e3)});if(l.ok&&l.status===200){let u=await o.text(),d=await l.text();u.length>100&&d.length>100&&Math.abs(u.length-d.length)<u.length*.1&&i.push({id:w(),title:"Missing Authentication on Protected Endpoint",description:`Endpoint ${s} is accessible without authentication`,severity:"high",category:"broken-auth",location:{file:a},remediation:{description:"Implement proper authentication checks",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]})}}}return e}async function Lo(c,t,e,r,i){let n=["/api/users/1","/api/users/2","/api/orders/1","/profile/1"];for(let s of n.slice(0,2)){if(e>=r*15)break;let a=new URL(s,c.origin).toString(),o=await fetch(a,{method:"GET",headers:{...t},signal:AbortSignal.timeout(5e3)});if(o.ok){e++;let l=await o.text();(l.includes("email")||l.includes("password")||l.includes("phone"))&&i.push({id:w(),title:"Potential Insecure Direct Object Reference (IDOR)",description:`Endpoint ${s} may expose other users' data`,severity:"high",category:"access-control",location:{file:a},remediation:{description:"Implement proper authorization checks for resource access",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/05-Authorization_Testing/04-Testing_for_Insecure_Direct_Object_References"]})}}return e}function $o(c){switch(c.type){case"basic":if(!c.username||!c.password)return{valid:!1,reason:"Basic auth requires username and password"};break;case"bearer":case"oauth":if(!c.token)return{valid:!1,reason:"Bearer/OAuth auth requires token"};break;case"cookie":if(!c.token)return{valid:!1,reason:"Cookie auth requires session cookie"};break}return{valid:!0}}function Oo(c){let t={};switch(c.type){case"basic":if(c.username&&c.password){let e=Buffer.from(`${c.username}:${c.password}`).toString("base64");t.Authorization=`Basic ${e}`}break;case"bearer":case"oauth":c.token&&(t.Authorization=`Bearer ${c.token}`);break;case"cookie":c.token&&(t.Cookie=c.token);break}return t}function No(c,t,e,r=!1){let i=[{header:"strict-transport-security",title:"Missing HSTS Header",severity:"medium",remediation:"Add Strict-Transport-Security header"},{header:"x-content-type-options",title:"Missing X-Content-Type-Options",severity:"low",remediation:"Add X-Content-Type-Options: nosniff"},{header:"x-frame-options",title:"Missing X-Frame-Options",severity:"medium",remediation:"Add X-Frame-Options: DENY or SAMEORIGIN"},{header:"content-security-policy",title:"Missing Content-Security-Policy",severity:"medium",remediation:"Implement a Content-Security-Policy"}];r||i.push({header:"referrer-policy",title:"Missing Referrer-Policy",severity:"low",remediation:"Add Referrer-Policy header"},{header:"permissions-policy",title:"Missing Permissions-Policy",severity:"low",remediation:"Add Permissions-Policy header"});for(let n of i)c.get(n.header)||e.push({id:w(),title:n.title,description:`Security header ${n.header} is not present in the response`,severity:n.severity,category:"security-misconfiguration",location:{file:t,snippet:`Missing: ${n.header}`},remediation:{description:n.remediation,estimatedEffort:"minor",automatable:!0},references:["https://owasp.org/www-project-secure-headers/"]})}function _o(c,t,e,r=!1){let i=c.get("set-cookie");if(!i)return;let n=i.toLowerCase(),s=r?"high":"medium";n.includes("secure")||e.push({id:w(),title:r?"Session Cookie Missing Secure Flag":"Cookie Missing Secure Flag",description:r?"Authenticated session cookie is not marked as Secure":"Cookie is set without the Secure attribute",severity:s,category:"sensitive-data",location:{file:t,snippet:"Set-Cookie header without Secure flag"},remediation:{description:"Add Secure flag to all cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/controls/SecureCookieAttribute"]}),n.includes("httponly")||e.push({id:w(),title:r?"Session Cookie Missing HttpOnly Flag":"Cookie Missing HttpOnly Flag",description:r?"Session cookie is accessible to JavaScript":"Cookie is accessible to client-side JavaScript",severity:s,category:"sensitive-data",location:{file:t,snippet:"Set-Cookie header without HttpOnly flag"},remediation:{description:"Add HttpOnly flag to session cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/HttpOnly"]})}function hd(c,t,e){let r=c.get("server")||c.get("x-powered-by");r&&/\d+\.\d+/.test(r)&&e.push({id:w(),title:"Server Version Disclosure",description:`Server version information exposed: ${r}`,severity:"low",category:"security-misconfiguration",location:{file:t,snippet:`Server: ${r}`},remediation:{description:"Remove or obfuscate server version headers",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]})}async function fd(c,t,e,r){let i=[{path:"/.git/config",name:"Git Configuration"},{path:"/.env",name:"Environment File"},{path:"/robots.txt",name:"Robots.txt"},{path:"/sitemap.xml",name:"Sitemap"},{path:"/.htaccess",name:"htaccess File"},{path:"/web.config",name:"IIS Configuration"}];for(let n of i){if(t>=e*10)break;let s=new URL(n.path,c.origin).toString(),a=await fetch(s,{method:"GET",signal:AbortSignal.timeout(5e3)});if(a.ok){t++;let o=await a.text();o.length>20&&!o.toLowerCase().includes("not found")&&!o.toLowerCase().includes("404")&&(n.path.includes(".git")||n.path.includes(".env")||n.path.includes(".htaccess")||n.path.includes("web.config"))&&r.push({id:w(),title:`Sensitive File Exposed: ${n.name}`,description:`${n.name} is publicly accessible`,severity:n.path.includes(".git")||n.path.includes(".env")?"high":"medium",category:"sensitive-data",location:{file:s},remediation:{description:`Restrict access to ${n.path}`,estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]})}}return t}async function yd(c,t){let r=(await fetch(c,{method:"OPTIONS",headers:{Origin:"https://evil-attacker.com","Access-Control-Request-Method":"GET"},signal:AbortSignal.timeout(5e3)})).headers.get("access-control-allow-origin");(r==="*"||r==="https://evil-attacker.com")&&t.push({id:w(),title:"Overly Permissive CORS Policy",description:r==="*"?"CORS allows all origins":"CORS reflects arbitrary origin",severity:"medium",category:"access-control",location:{file:c,snippet:`Access-Control-Allow-Origin: ${r}`},remediation:{description:"Restrict CORS to specific trusted origins",estimatedEffort:"minor",automatable:!1},references:["https://owasp.org/www-community/attacks/CORS_OriginHeaderScrutiny"]})}async function vd(c,t,e,r,i){let n=e,s=r*5,a=/href=["']([^"']+)["']/gi,o=new Set,l;for(;(l=a.exec(c))!==null;){let d=l[1];try{let m=new URL(d,t.origin);m.origin===t.origin&&!o.has(m.pathname)&&o.add(m.pathname)}catch{}}let u=Array.from(o).slice(0,Math.min(10,s-n));for(let d of u){if(n>=s)break;let m=new URL(d,t.origin).toString(),p=await fetch(m,{method:"GET",headers:{"User-Agent":"AgenticQE-DAST-Scanner/3.0"},signal:AbortSignal.timeout(5e3),redirect:"follow"});if(n++,p.ok){(d.includes("password")||d.includes("token")||d.includes("api_key"))&&i.push({id:w(),title:"Sensitive Data in URL Path",description:`URL path may contain sensitive parameter names: ${d}`,severity:"medium",category:"sensitive-data",location:{file:m},remediation:{description:"Avoid sensitive data in URL paths",estimatedEffort:"minor",automatable:!1},references:["https://owasp.org/www-community/vulnerabilities/Information_exposure_through_query_strings_in_url"]});let h=await p.text();(h.includes("Index of /")||h.includes("Directory listing for"))&&i.push({id:w(),title:"Directory Listing Enabled",description:`Directory listing is enabled at: ${m}`,severity:"medium",category:"security-misconfiguration",location:{file:m},remediation:{description:"Disable directory listing in server configuration",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]})}}return n}function bd(c,t,e){let r=/<form[^>]*>([\s\S]*?)<\/form>/gi,i,n=0;for(;(i=r.exec(c))!==null&&n<10;){n++;let s=i[0],a=i[1],o=/name=["']?csrf/i.test(a)||/name=["']?_token/i.test(a)||/name=["']?authenticity_token/i.test(a)||/name=["']?__RequestVerificationToken/i.test(a);/method=["']?post/i.test(s)&&!o&&e.push({id:w(),title:"Missing CSRF Token",description:`POST form #${n} does not appear to have CSRF protection`,severity:"medium",category:"broken-auth",location:{file:t,snippet:`Form #${n}`},remediation:{description:"Add CSRF token to all state-changing forms",estimatedEffort:"minor",automatable:!1},references:["https://owasp.org/www-community/attacks/csrf"]}),/type=["']?password/i.test(a)&&(/autocomplete=["']?(off|new-password)/i.test(a)||/autocomplete=["']?(off|new-password)/i.test(s)||e.push({id:w(),title:"Password Field Allows Autocomplete",description:`Form #${n} has password field that may be cached by browser`,severity:"low",category:"sensitive-data",location:{file:t,snippet:`Form #${n}`},remediation:{description:'Add autocomplete="new-password" to password fields',estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]}));let u=/action=["']?([^"'\s>]+)/i.exec(s);if(u){let d=u[1];d.startsWith("http://")&&!d.includes("localhost")&&!d.includes("127.0.0.1")&&e.push({id:w(),title:"Form Submits to Insecure HTTP",description:`Form #${n} submits data over insecure HTTP: ${d}`,severity:"high",category:"sensitive-data",location:{file:t,snippet:`Action: ${d}`},remediation:{description:"Change form action to use HTTPS",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]})}}}function Vo(c,t,e){let r={critical:0,high:0,medium:0,low:0,informational:0,totalFiles:t,scanDurationMs:e};for(let i of c)r[i.severity]++;return r}async function zo(c,t,e,r,i){await c.set(`security:scan:${t}`,{scanId:t,scanType:e,vulnerabilities:r,summary:i,timestamp:new Date().toISOString()},{namespace:"security-compliance",ttl:86400*7})}function Yh(c){if(c instanceof Error&&"code"in c&&["DAST_AUTHENTICATION_FAILED","DAST_TARGET_UNAVAILABLE"].includes(String(c.code)))return c;let t=c instanceof Error&&/timeout|abort/i.test(c.message);return Object.assign(new Error(t?"DAST target request timeout; dynamic analysis is incomplete":"DAST target request failed; dynamic analysis is incomplete"),{code:t?"DAST_REQUEST_TIMEOUT":"DAST_REQUEST_FAILED"})}var Ai=class{config;memory;activeScans;constructor(t,e,r){this.config=t,this.memory=e,this.activeScans=r||new Map}async scanUrl(t,e){let r=w();try{this.activeScans.set(r,"running");let i=Date.now(),n={maxDepth:e?.maxDepth??this.config.dastMaxDepth,activeScanning:e?.activeScanning??this.config.dastActiveScanning,timeout:e?.timeout??this.config.timeout,excludePatterns:e?.excludePatterns??[]},s=await this.performDynamicScan(t,n),a=Date.now()-i,o=Vo(s.vulnerabilities,1,a);return await zo(this.memory,r,"dast",s.vulnerabilities,o),this.activeScans.set(r,"completed"),f({scanId:r,targetUrl:t,vulnerabilities:s.vulnerabilities,summary:o,crawledUrls:s.crawledUrls})}catch(i){return this.activeScans.set(r,"failed"),g(y(i))}}async scanAuthenticated(t,e,r){let i=w();try{this.activeScans.set(i,"running");let n=Date.now(),s=$o(e);if(!s.valid)throw new Error(s.reason);let a={maxDepth:r?.maxDepth??this.config.dastMaxDepth,activeScanning:r?.activeScanning??this.config.dastActiveScanning,timeout:r?.timeout??this.config.timeout,excludePatterns:r?.excludePatterns??[]},o=await this.performAuthenticatedScan(t,e,a),l=Date.now()-n,u=Vo(o.vulnerabilities,1,l);return await zo(this.memory,i,"dast-auth",o.vulnerabilities,u),this.activeScans.set(i,"completed"),f({scanId:i,targetUrl:t,vulnerabilities:o.vulnerabilities,summary:u,crawledUrls:o.crawledUrls})}catch(n){return this.activeScans.set(i,"failed"),g(y(n))}}async getScanStatus(t){return this.activeScans.get(t)??"pending"}async performDynamicScan(t,e){let r=[],i=0;try{let n;try{n=new URL(t)}catch{return r.push(this.createInvalidUrlVuln(t)),{vulnerabilities:r,crawledUrls:0}}let s=e.timeout??this.config.timeout,a=e.maxDepth??this.config.dastMaxDepth,o=Math.min(s,3e4);try{let l=await et(t,{method:"GET",headers:{"User-Agent":"AgenticQE-DAST-Scanner/3.0",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"},redirect:"follow"},o,()=>new Error(`DAST request timeout after ${o}ms: ${t}`));if(l.status===401||l.status===403||l.status>=500)throw await l.body?.cancel().catch(()=>{}),Object.assign(new Error(`DAST ${l.status<500?"authentication rejected":"target unavailable"} (HTTP ${l.status}); dynamic analysis is incomplete`),{code:l.status<500?"DAST_AUTHENTICATION_FAILED":"DAST_TARGET_UNAVAILABLE"});if(i++,No(l.headers,t,r),n.protocol==="http:"&&r.push(this.createInsecureProtocolVuln(t)),_o(l.headers,t,r),hd(l.headers,t,r),e.activeScanning??this.config.dastActiveScanning){let u=await l.text();i=await fd(n,i,a,r),await yd(t,r),i=await vd(u,n,i,a,r),n.search&&await this.testInjectionVulnerabilities(t,n,r),bd(u,t,r)}else await l.body?.cancel().catch(()=>{})}catch(l){throw Yh(l)}}catch(n){throw y(n)}return{vulnerabilities:r,crawledUrls:i}}async performAuthenticatedScan(t,e,r){let i=[],n=0;try{let s=Oo(e),a;try{a=new URL(t)}catch{return i.push(this.createInvalidUrlVuln(t)),{vulnerabilities:i,crawledUrls:0}}let o=r.timeout??this.config.timeout,l=r.maxDepth??this.config.dastMaxDepth,u=Math.min(o,3e4);try{let d=await et(t,{method:"GET",headers:{"User-Agent":"AgenticQE-DAST-Scanner/3.0",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",...s},redirect:"follow"},u,()=>new Error(`DAST request timeout after ${u}ms: ${t}`));if(await d.body?.cancel().catch(()=>{}),d.status===401||d.status===403||d.status>=500)throw await d.body?.cancel().catch(()=>{}),Object.assign(new Error(`DAST ${d.status<500?"authentication rejected":"target unavailable"} (HTTP ${d.status}); dynamic analysis is incomplete`),{code:d.status<500?"DAST_AUTHENTICATION_FAILED":"DAST_TARGET_UNAVAILABLE"});n++,No(d.headers,t,i,!0),(a.search.includes("token=")||a.search.includes("session=")||a.search.includes("auth="))&&i.push(this.createTokenInUrlVuln(t,a.search)),(r.activeScanning??this.config.dastActiveScanning)&&(n=await Fo(a,s,n,l,i),n=await Lo(a,s,n,l,i)),_o(d.headers,t,i,!0)}catch(d){throw Yh(d)}}catch(s){throw y(s)}return{vulnerabilities:i,crawledUrls:n}}createInvalidUrlVuln(t){return{id:w(),title:"Invalid Target URL",description:"The provided target URL is not valid",severity:"informational",category:"security-misconfiguration",location:{file:t},remediation:{description:"Provide a valid URL",estimatedEffort:"trivial",automatable:!1},references:[]}}createInsecureProtocolVuln(t){return{id:w(),title:"Insecure HTTP Protocol",description:"Application is accessible over unencrypted HTTP",severity:"high",category:"sensitive-data",location:{file:t},remediation:{description:"Redirect all HTTP traffic to HTTPS",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]}}createTokenInUrlVuln(t,e){return{id:w(),title:"Session Token in URL",description:"Authentication token appears in URL query string",severity:"high",category:"sensitive-data",location:{file:t,snippet:e.substring(0,50)},remediation:{description:"Send tokens in headers or request body, not URL",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-community/vulnerabilities/Information_exposure_through_query_strings_in_url"]}}async testInjectionVulnerabilities(t,e,r){let i=new URLSearchParams(e.search),n=Array.from(i.keys()),s=[{payload:"<script>alert(1)</script>",name:"Basic XSS"},{payload:'"><img src=x onerror=alert(1)>',name:"Attribute Injection"},{payload:"'-alert(1)-'",name:"JavaScript Injection"}],a=[{payload:"' OR '1'='1",name:"SQL OR Injection"},{payload:"1; DROP TABLE test--",name:"SQL Statement Injection"},{payload:"1' AND '1'='1",name:"SQL AND Injection"}];for(let o of n.slice(0,3))await Io(t,e,o,s,r),await Mo(t,e,o,a,r)}};import{isIP as af}from"node:net";k();Wi();var o0=3e4,c0=4,l0=3,u0=1e3,d0=5,m0=3e4,wd=class{circuits=new Map;getCircuitKey(t){try{return new URL(t).origin}catch{return t}}getState(t){let e=this.getCircuitKey(t);return this.circuits.has(e)||this.circuits.set(e,{failures:0,lastFailure:null,state:"closed"}),this.circuits.get(e)}recordSuccess(t){let e=this.getCircuitKey(t);this.circuits.set(e,{failures:0,lastFailure:null,state:"closed"})}recordFailure(t){let e=this.getCircuitKey(t),i=this.getState(t).failures+1;this.circuits.set(e,{failures:i,lastFailure:Date.now(),state:i>=d0?"open":"closed"})}canRequest(t){let e=this.getState(t);if(e.state==="closed")return!0;if(e.state==="open"){if((e.lastFailure?Date.now()-e.lastFailure:1/0)>=m0){let i=this.getCircuitKey(t);return this.circuits.set(i,{...e,state:"half-open"}),!0}return!1}return!1}reset(t){if(t){let e=this.getCircuitKey(t);this.circuits.delete(e)}else this.circuits.clear()}},gt=class{circuitBreaker;constructor(){this.circuitBreaker=new wd}async get(t,e){return this.request(t,{method:"GET"},e)}async post(t,e,r){return this.request(t,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}},r)}async put(t,e,r){return this.request(t,{method:"PUT",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}},r)}async patch(t,e,r){return this.request(t,{method:"PATCH",body:JSON.stringify(e),headers:{"Content-Type":"application/json"}},r)}async delete(t,e){return this.request(t,{method:"DELETE"},e)}async healthCheck(t){let e=await this.get(t,{timeout:5e3,retries:1,circuitBreaker:!1});return e.success?e.value.ok:!1}getCircuitState(t){return this.circuitBreaker.getState(t)}resetCircuit(t){this.circuitBreaker.reset(t)}async request(t,e,r){let i=r?.timeout??o0,n=r?.maxDurationMs??i*c0,s=r?.retries??l0,a=r?.retryDelay??u0,o=r?.circuitBreaker??!0,l={...e.headers,...r?.headers},u={startTime:Date.now(),endTime:0,duration:0,retryCount:0};if(o&&!this.circuitBreaker.canRequest(t))return u.endTime=Date.now(),u.duration=u.endTime-u.startTime,g({message:"Circuit breaker is open",code:"CIRCUIT_OPEN",timing:u});let d=null;for(let m=0;m<=s;m++){u.retryCount=m;try{let p=await this.fetchWithTimeout(t,{...e,headers:l},i,n);return u.endTime=Date.now(),u.duration=u.endTime-u.startTime,o&&this.circuitBreaker.recordSuccess(t),f(p)}catch(p){if(d=y(p),o&&this.circuitBreaker.recordFailure(t),m<s){let h=a*Math.pow(2,m);await this.sleep(h)}}}return u.endTime=Date.now(),u.duration=u.endTime-u.startTime,g({message:d?.message||"Request failed",code:this.getErrorCode(d),cause:d??void 0,timing:u})}async fetchWithTimeout(t,e,r,i){return et(t,e,r,()=>Object.assign(new Error(`Request timeout (idle ${r}ms, cap ${i}ms): ${t}`),{name:"TimeoutError"}),"idle",i)}getErrorCode(t){if(!t)return"UNKNOWN_ERROR";let e=new Set,r=t;for(;typeof r=="object"&&r!==null&&!e.has(r);){e.add(r);let i=r;if(i.name==="AbortError"||i.name==="TimeoutError")return"TIMEOUT";let n=typeof i.message=="string"?i.message:"";if(i.code==="ECONNREFUSED"||n.includes("ECONNREFUSED"))return"CONNECTION_REFUSED";if(i.code==="ENOTFOUND"||n.includes("ENOTFOUND"))return"DNS_ERROR";if(i.code==="ETIMEDOUT"||n.includes("ETIMEDOUT"))return"NETWORK_TIMEOUT";r=i.cause}return"REQUEST_FAILED"}sleep(t){return new Promise(e=>setTimeout(e,t))}};function is(){return new gt}hr();var Ke=class c extends Error{lookup;constructor(t,e){super(t),this.name="OSVLookupError",this.lookup=e}static fromLookup(t){let e=[...new Set(t.unchecked.map(r=>r.reason))].slice(0,3).join("; ");return new c(`OSV advisories could not be checked for ${t.unchecked.length} of ${t.packagesRequested} package(s): ${e}`,t)}},nr=c=>`${c.ecosystem}:${c.name}@${c.version??""}`;function ef(c,t=5){return c.length<=t?c.join(", "):`${c.slice(0,t).join(", ")} and ${c.length-t} more`}function xi(c){let t=/^=?v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/.exec(c.trim());return t?t[1]:null}function Bo(c){let t=c.trim(),e=/^npm:((?:@[^/@\s]+\/)?[^@\s]+)(?:@(.*))?$/.exec(t);return e?{kind:"alias",name:e[1],spec:e[2]??""}:/^(workspace:|link:|portal:)/.test(t)?{kind:"local"}:/^file:/.test(t)?/\.(tgz|tar\.gz|tar)$/i.test(t)?{kind:"remote"}:{kind:"local"}:/^(\.{0,2}\/|~\/)/.test(t)?/\.(tgz|tar\.gz|tar)$/i.test(t)?{kind:"remote"}:{kind:"local"}:/^(patch:|exec:|git\+|git:|github:|gitlab:|bitbucket:|https?:)/.test(t)?{kind:"remote"}:/^[^\s@/:]+\/[^\s@/:]+(#.*)?$/.test(t)?{kind:"remote"}:{kind:"registry",spec:t}}function tf(c){return c.length===0||c.length>p0||!h0(c)?!1:!/(^|\.)[xX*](\.|$)/.test(c)}var p0=256,g0=/^\d+(?:\.\d+)*$/,Xh=/^[0-9A-Za-z][0-9A-Za-z.+-]*$/;function h0(c){let t=c.indexOf("_");if(t>=0)return g0.test(c.slice(0,t))&&Xh.test(c.slice(t+1));let e=0;for(;e<c.length&&c.charCodeAt(e)>=48&&c.charCodeAt(e)<=57;)e++;if(e===0)return!1;let r=c.slice(e);if(r===""||e>=2&&f0.test(r))return!0;let i=r[0]==="-"||r[0]==="+"||r[0]===".";return Xh.test(i?r.slice(1):r)}var f0=/^[0-9A-Za-z.+-]*$/,Or=c=>!!c&&typeof c=="object"&&!Array.isArray(c);function rf(c,t){return!Or(c)||!Array.isArray(c.results)||c.results.length!==t?null:c.results.map(e=>{if(!Or(e))return{reason:"malformed OSV result entry"};if(typeof e.next_page_token=="string"&&e.next_page_token)return{reason:"OSV advisory list was truncated (paginated) and not fully retrieved"};if(e.vulns===void 0)return{ids:[]};if(!Array.isArray(e.vulns))return{reason:"malformed OSV result entry"};let r=[];for(let i of e.vulns){if(!Or(i)||typeof i.id!="string"||!i.id)return{reason:"malformed OSV advisory reference"};r.push(i.id)}return{ids:r}})}function Cd(c){return Or(c)&&typeof c.id=="string"&&Array.isArray(c.affected)}function nf(c){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(c.trim());return t?{nums:[Number(t[1]),Number(t[2]),Number(t[3])],pre:t[4]?t[4].split("."):[]}:null}function Zh(c,t){for(let e=0;e<3;e++)if(c.nums[e]!==t.nums[e])return c.nums[e]<t.nums[e]?-1:1;if(c.pre.length===0||t.pre.length===0)return c.pre.length===t.pre.length?0:c.pre.length===0?1:-1;for(let e=0;e<Math.max(c.pre.length,t.pre.length);e++){let r=c.pre[e],i=t.pre[e];if(r===void 0||i===void 0)return r===void 0?-1:1;if(r===i)continue;let n=/^\d+$/.test(r),s=/^\d+$/.test(i);return n&&s?Number(r)<Number(i)?-1:1:n!==s?n?-1:1:r<i?-1:1}return 0}function y0(c,t){let e=[];for(let n of t){let s=n.introduced!==void 0?"introduced":n.fixed!==void 0?"fixed":n.last_affected!==void 0?"last_affected":null;if(!s)continue;let a=n[s];if(s==="introduced"&&a==="0"){e.push({at:null,kind:s});continue}let o=nf(a);if(!o)return null;e.push({at:o,kind:s})}let r=n=>n==="introduced"?1:0;e.sort((n,s)=>!n.at||!s.at?n.at===s.at?0:n.at?1:-1:Zh(n.at,s.at)||r(n.kind)-r(s.kind));let i=!1;for(let{at:n,kind:s}of e){if(!n){i=!0;continue}let a=Zh(c,n);s==="introduced"&&a>=0?i=!0:(s==="fixed"&&a>=0||s==="last_affected"&&a>0)&&(i=!1)}return i}function sf(c,t){let e=c.affected;if(!Array.isArray(e))return!0;let r=e.filter(n=>Or(n)&&Or(n.package)&&n.package.name===t.name&&n.package.ecosystem===t.ecosystem);if(r.length===0)return!0;let i=nf(t.version);for(let n of r){if(Array.isArray(n.versions)&&n.versions.includes(t.version))return!0;let s=Array.isArray(n.ranges)?n.ranges.filter(Or):[];if(s.length===0&&!Array.isArray(n.versions))return!0;for(let a of s)if(a.type!=="SEMVER"||!i||!Array.isArray(a.events)||y0(i,a.events)!==!1)return!0}return!1}function qo(c,t){return t===c?"complete":t===0?"failed":"incomplete"}var v0="https://api.osv.dev";function b0(c){let t=c.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"?!0:af(t)===4?t.startsWith("127."):af(t)===6&&(t==="::1"||t==="0:0:0:0:0:0:0:1")}function Sd(c=process.env){let t=c.AQE_OSV_API_URL?.trim();if(!t)return v0;if(t.length>of)throw new Error(`AQE_OSV_API_URL is longer than ${of} characters (expected https://host)`);let e;try{e=new URL(t)}catch{throw new Error(`AQE_OSV_API_URL is not a URL: "${t.slice(0,200)}" (expected https://host)`)}let r=b0(e.hostname);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&r))throw new Error(`AQE_OSV_API_URL must use https (http only for localhost/loopback): "${t.slice(0,200)}"`);let i=t;for(;i.endsWith("/");)i=i.slice(0,-1);return i}var of=2048,Nr=class{config;configuredBaseUrl;endpoint=null;http;detailCache=new Map;constructor(t={}){this.configuredBaseUrl=t.baseUrl,this.config={timeout:t.timeout??3e4,retries:t.retries??2,batchSize:Math.max(1,Math.min(1e3,t.batchSize??500)),detailConcurrency:Math.max(1,t.detailConcurrency??8),enableCache:t.enableCache??!0,cacheTtl:t.cacheTtl??3600*1e3},this.http=new gt}get baseUrl(){let t=this.resolveEndpoint();return"url"in t?t.url:null}resolveEndpoint(){if(!this.endpoint)try{this.endpoint={url:this.configuredBaseUrl!==void 0?Sd({AQE_OSV_API_URL:this.configuredBaseUrl}):Sd()}}catch(t){this.endpoint={reason:t instanceof Error?t.message:String(t)}}return this.endpoint}get base(){let t=this.resolveEndpoint();if("reason"in t)throw new Ke(t.reason);return t.url}async lookupBatch(t){let e=new Map,r=[],i=[],n=[],s=0,a=this.resolveEndpoint();if("reason"in a)return{status:qo(t.length,0),results:e,packagesRequested:t.length,packagesChecked:0,unchecked:t.map(d=>({...d,reason:a.reason})),errors:[a.reason]};for(let d of t)d.version&&tf(d.version)?n.push(d):r.push({...d,reason:d.version?`version "${d.version}" is a range or tag, not a concrete version (no lockfile resolution)`:"no version declared; advisories cannot be matched"});let o=[];for(let d=0;d<n.length;d+=this.config.batchSize){let m=n.slice(d,d+this.config.batchSize),p=await this.postBatch(m);if("reason"in p){i.push(`querybatch for ${m.length} package(s) failed: ${p.reason}`);for(let h of m)r.push({...h,reason:p.reason});continue}p.entries.forEach((h,v)=>{"reason"in h?r.push({...m[v],reason:h.reason}):o.push({pkg:m[v],ids:h.ids})})}let l=await this.fetchDetails([...new Set(o.flatMap(d=>d.ids))]);for(let{pkg:d,ids:m}of o){let p=m.filter(v=>"reason"in l.get(v));if(p.length>0){let v=l.get(p[0]).reason;r.push({...d,reason:`advisory details unavailable for ${ef(p)}: ${v}`});continue}let h=m.map(v=>l.get(v).vuln).filter(v=>sf(v,{name:d.name,ecosystem:d.ecosystem,version:d.version}));e.set(nr(d),this.parseVulnerabilities(h).map(v=>({...v,affectedPackage:d.name}))),s++}let u=[...l.values()].filter(d=>"reason"in d);return u.length>0&&i.push(`${u.length} advisory detail request(s) failed: ${u[0].reason}`),{status:qo(t.length,s),results:e,packagesRequested:t.length,packagesChecked:s,unchecked:r,errors:i}}async lookupNpmDependencies(t,e={}){let r=[],i=[];for(let[a,o]of Object.entries(t)){let l=Bo(o);if(l.kind==="local"||l.kind==="remote"){i.push({name:a,ecosystem:"npm",version:o,reason:l.kind==="local"?`local package ("${o}"); not an OSV subject`:`not a registry dependency ("${o}": git/URL/tarball source); OSV advisories cannot be matched`});continue}let u=l.kind==="alias"?l.name:a,d=gr(e,a),p=(d!==void 0?xi(d):null)??xi(l.spec);p?r.push({name:u,ecosystem:"npm",version:p}):i.push({name:a,ecosystem:"npm",version:o,reason:`version range "${o}", no lockfile resolution`})}let n=await this.lookupBatch(r),s=r.length+i.length;return{...n,status:qo(s,n.packagesChecked),packagesRequested:s,unchecked:[...i,...n.unchecked]}}async queryPackage(t,e,r){let i=await this.http.post(`${this.base}/v1/query`,{package:{name:t,ecosystem:e},...r&&{version:r}},this.requestOptions()),n=await this.readJson(i);if("reason"in n)throw new Ke(`OSV query for ${e}:${t} failed: ${n.reason}`);let s=n.value?.vulns;if(s===void 0&&n.value&&typeof n.value=="object")return[];if(!Array.isArray(s)||!s.every(Cd))throw new Ke(`OSV query for ${e}:${t} failed: malformed response`);return this.parseVulnerabilities(s)}async queryBatch(t){let e=await this.lookupBatch(t);if(e.status!=="complete")throw Ke.fromLookup(e);return e.results}async queryByCVE(t){this.base;let e=await this.fetchDetail(t);if("vuln"in e)return this.parseVulnerabilities([e.vuln]);if(e.reason==="HTTP 404")return[];throw new Ke(`OSV lookup for ${t} failed: ${e.reason}`)}async scanNpmDependencies(t){let e=await this.lookupNpmDependencies(t);if(e.status!=="complete")throw Ke.fromLookup(e);return[...e.results.values()].flat()}async scanPythonRequirements(t){let e=t.split(`
2900
2900
  `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#")&&!i.startsWith("-")).map(i=>i.match(/^([a-zA-Z0-9_.-]+)(?:\s*==\s*([^\s;#,]+))?/)).filter(i=>i!==null).map(i=>({name:i[1],ecosystem:"PyPI",version:i[2]})),r=await this.lookupBatch(e);if(r.status!=="complete")throw Ke.fromLookup(r);return[...r.results.values()].flat()}clearCache(){this.detailCache.clear()}requestOptions(){return{timeout:this.config.timeout,retries:this.config.retries}}async readJson(t){if(!t.success)return{reason:`${t.error.code}: ${t.error.message}`};let e=t.value;if(!e.ok)return await e.body?.cancel().catch(()=>{}),{reason:`HTTP ${e.status}${e.status===429?" (rate limited)":""}`};let r;try{r=await e.text()}catch(i){return{reason:`${i instanceof Error&&(i.name==="TimeoutError"||i.name==="AbortError")?"TIMEOUT":"BODY_READ_FAILED"}: response body could not be read`}}try{return{value:JSON.parse(r)}}catch{return{reason:"malformed JSON response"}}}async postBatch(t){let e=t.map(s=>({package:{name:s.name,ecosystem:s.ecosystem},...s.version?{version:s.version}:{}})),r=await this.http.post(`${this.base}/v1/querybatch`,{queries:e},this.requestOptions()),i=await this.readJson(r);if("reason"in i)return i;let n=rf(i.value,t.length);return n?{entries:n}:{reason:"malformed OSV querybatch response (results do not match the queries)"}}async fetchDetails(t){let e=new Map,r=0,i=async()=>{for(;r<t.length;){let n=t[r++];e.set(n,await this.fetchDetail(n))}};return await Promise.all(Array.from({length:Math.min(this.config.detailConcurrency,t.length)},i)),e}async fetchDetail(t){let e=this.config.enableCache?this.detailCache.get(t):void 0;if(e&&Date.now()-e.timestamp<this.config.cacheTtl)return{vuln:e.data};let r=await this.http.get(`${this.base}/v1/vulns/${encodeURIComponent(t)}`,this.requestOptions()),i=await this.readJson(r);if("reason"in i)return i;if(!Cd(i.value))return{reason:"malformed OSV advisory record"};let n=i.value;return this.config.enableCache&&this.detailCache.set(t,{data:n,timestamp:Date.now()}),{vuln:n}}parseVulnerabilities(t){return t.map(e=>{let r=this.extractCVSSScore(e.severity);return{id:e.id,cveIds:e.aliases?.filter(i=>i.startsWith("CVE-"))||[],summary:e.summary||"No summary available",details:e.details||"",severity:this.scoreSeverity(r,e.database_specific),cvssScore:r,affectedPackage:e.affected?.[0]?.package?.name||"unknown",affectedVersions:e.affected?.[0]?.versions||[],fixedVersions:this.extractFixedVersions(e.affected??[]),publishedDate:e.published?new Date(e.published):null,references:e.references?.map(i=>i.url)||[]}})}extractCVSSScore(t){if(!t||t.length===0)return null;let e=t.find(i=>i.type==="CVSS_V3")??t.find(i=>i.type==="CVSS_V2");if(!e||typeof e.score!="string"||e.score.startsWith("CVSS:"))return null;let r=parseFloat(e.score.split("/")[0]);return isNaN(r)?null:r}scoreSeverity(t,e){if(t!==null)return t>=9?"critical":t>=7?"high":t>=4?"medium":"low";let r=typeof e?.severity=="string"?e.severity.toLowerCase():"";return r==="critical"||r==="high"||r==="low"?r:r==="medium"||r==="moderate"?"medium":"unknown"}extractFixedVersions(t){let e=[];for(let r of t)for(let i of r.ranges||[])for(let n of i.events||[])n.fixed&&e.push(n.fixed);return[...new Set(e)]}};mr();var Go={libraries:[/import\s+.*\bfrom\s+['"]crypto['"]/,/import\s+.*\bfrom\s+['"]bcrypt['"]/,/import\s+.*\bfrom\s+['"]argon2['"]/,/import\s+.*\bfrom\s+['"]node-forge['"]/,/import\s+.*\bfrom\s+['"]crypto-js['"]/,/require\s*\(\s*['"]crypto['"]\s*\)/],encryption:[/\.encrypt\s*\(/,/\.decrypt\s*\(/,/createCipheriv\s*\(/,/createDecipheriv\s*\(/,/\.hash\s*\(/,/bcrypt\.(hash|compare)/,/argon2\.(hash|verify)/],weakCrypto:[/createCipher\s*\(\s*['"]des['"]/i,/createCipher\s*\(\s*['"]md5['"]/i,/\.createHash\s*\(\s*['"]md5['"]\s*\)/,/\.createHash\s*\(\s*['"]sha1['"]\s*\)/],unencryptedData:[/password\s*[:=]\s*[^{]*(?!hash|encrypt|bcrypt)/i,/\.parse\s*\(\s*.*password/i,/JSON\.stringify\s*\([^)]*password[^)]*\)/i]},ns={authMiddleware:[/\.use\s*\(\s*(?:auth|authenticate|passport|jwt|bearer)/i,/middleware\s*[:=].*(?:auth|authenticate|verify)/i,/isAuthenticated/,/requireAuth/,/checkAuth/],routeProtection:[/(?:app|router)\.\w+\s*\([^)]*,\s*(?:auth|authenticate|protect)/i,/@(?:Auth|Authenticated|RequireAuth|Roles?)\s*\(/],unprotectedRoutes:[/(?:app|router)\.(?:get|post|put|delete|patch)\s*\(\s*['"][^'"]*(?:admin|user|account|profile|settings)[^'"]*['"]\s*,\s*(?:async\s*)?\([^)]*\)\s*=>/i],hardcodedCreds:[/(?:password|secret|apikey|api_key|token)\s*[:=]\s*['"][^'"]{8,}['"]/i,/Authorization\s*[:=]\s*['"]Bearer\s+[^'"]+['"]/i]},jo={auditLog:[/audit\.log/i,/auditLog/,/\.audit\s*\(/,/logger\.(?:audit|security)/i,/winston\.(?:audit)/i],generalLog:[/console\.(?:log|info|warn|error)/,/logger\.(?:log|info|warn|error|debug)/,/winston\.(?:log|info|warn|error)/,/pino\.(?:info|warn|error)/],sensitiveOperations:[/\.delete\s*\(/,/\.remove\s*\(/,/\.update\s*\([^)]*(?:password|role|permission)/i,/\.create(?:User|Admin|Account)/i,/login|logout|signIn|signOut/i],sensitiveInLogs:[/console\.log\s*\([^)]*(?:password|secret|token|apikey|ssn|creditcard)/i,/logger\.(?:log|info|debug)\s*\([^)]*(?:password|secret|token)/i]},Ho={piiFields:[/(?:email|phone|ssn|social_security|date_of_birth|dob|address|zip_code|postal)\s*[:=?]/i,/firstName|lastName|fullName|name\s*:/i,/creditCard|cardNumber|cvv|expiry/i,/passport|driverLicense|nationalId/i],masking:[/\.mask\s*\(/,/maskPii|maskData|redact/i,/\*{3,}/,/x{3,}/i],validation:[/\.validate\s*\(/,/Joi\.|yup\.|zod\./,/@IsEmail|@IsString|@IsNumber|@ValidateNested/,/express-validator/]},Wo={rateLimiting:[/rateLimit|rate-limit|rateLimiter/i,/express-rate-limit/,/slowDown/,/throttle/i],csrf:[/csrf|csurf/i,/csrfToken/,/@Csrf/],cors:[/\bcors\b/i,/Access-Control-Allow/,/\.cors\s*\(/],sanitization:[/sanitize|escape|xss/i,/DOMPurify/,/validator\.escape/],sqlInjection:[/\$\d|:\w+|\?/,/\.prepare\s*\(/,/sequelize|prisma|typeorm|knex/i]},Uo=class{fileReader;constructor(){this.fileReader=new it({projectRoot:Ce()})}async analyzeEncryption(t){let e=[],r=[],i=[],n=!1;for(let s of t){let a=await this.fileReader.readFile(s);if(!a.success)continue;let o=a.value,l=o.split(`
2901
2901
  `);for(let u of Go.libraries)if(u.test(o)){n=!0;let d=o.match(u);if(d){let m=d[0].match(/['"]([^'"]+)['"]/)?.[1];m&&!e.includes(m)&&e.push(m)}}for(let u of Go.encryption)u.test(o)&&(n=!0);for(let u=0;u<l.length;u++){let d=l[u];for(let m of Go.weakCrypto)m.test(d)&&i.push({file:s,line:u+1,snippet:d.trim().substring(0,100),pattern:"weak-crypto",severity:"critical"});for(let m of Go.unencryptedData)m.test(d)&&r.push({file:s,line:u+1,snippet:d.trim().substring(0,100),pattern:"unencrypted-data",severity:"warning"})}}return{hasEncryption:n,encryptionLibraries:e,unencryptedDataHandling:r,weakCrypto:i}}async analyzeAccessControl(t){let e=[],r=[],i=[],n=!1;for(let s of t){let a=await this.fileReader.readFile(s);if(!a.success)continue;let o=a.value,l=o.split(`
2902
2902
  `);for(let u of ns.authMiddleware)if(u.test(o)){n=!0;break}for(let u of ns.routeProtection)u.test(o)&&(n=!0);for(let u=0;u<l.length;u++){let d=l[u];for(let m of ns.unprotectedRoutes)if(m.test(d)){let p=l.slice(u,u+3).join(`
@@ -2905,12 +2905,12 @@ Provide detailed remediation advice specific to this code.`}],model:r,maxTokens:
2905
2905
  `);jo.generalLog.some(b=>b.test(h))||e.push({file:n,line:l+1,snippet:u.trim().substring(0,100),pattern:"missing-audit-log",severity:"warning"})}for(let d of jo.sensitiveInLogs)d.test(u)&&r.push({file:n,line:l+1,snippet:u.trim().substring(0,100),pattern:"sensitive-data-logged",severity:"critical"})}}return{hasAuditLogging:i,sensitiveOperationsWithoutLogging:e,sensitiveDataInLogs:r}}async analyzeDataProtection(t){let e=[],r=[],i=[];for(let n of t){let s=await this.fileReader.readFile(n);if(!s.success)continue;let a=s.value,o=a.split(`
2906
2906
  `),l=Ho.validation.some(d=>d.test(a)),u=Ho.masking.some(d=>d.test(a));for(let d=0;d<o.length;d++){let m=o[d];for(let p of Ho.piiFields)if(p.test(m)){e.push({file:n,line:d+1,snippet:m.trim().substring(0,100),pattern:"pii-field",severity:"info"});let h=o.slice(Math.max(0,d-2),d+3).join(`
2907
2907
  `);!Ho.masking.some(b=>b.test(h))&&!u&&r.push({file:n,line:d+1,snippet:m.trim().substring(0,100),pattern:"unmasked-pii",severity:"warning"})}}e.length>0&&!l&&i.push({file:n,line:1,snippet:"File contains PII fields without input validation",pattern:"missing-validation",severity:"warning"})}return{piiFields:e,unmaskedPii:r,missingValidation:i}}async analyzeSecurityControls(t){let e=[],r=[],i=!1,n=!1,s=!1,a=!1;for(let o of t){let l=await this.fileReader.readFile(o);if(!l.success)continue;let u=l.value;Wo.rateLimiting.some(d=>d.test(u))&&(i=!0),Wo.csrf.some(d=>d.test(u))&&(n=!0),Wo.cors.some(d=>d.test(u))&&(s=!0),Wo.sanitization.some(d=>d.test(u))&&(a=!0)}return i||r.push("Rate Limiting"),n||r.push("CSRF Protection"),s||r.push("CORS Configuration"),a||r.push("Input Validation/Sanitization"),{hasRateLimiting:i,hasCsrfProtection:n,hasCors:s,hasInputValidation:a,missingControls:r,vulnerabilities:e}}async scanForDataTypes(t,e){let r=new Map,i={pii:[/email|phone|ssn|social_security|address|date_of_birth|dob/i,/firstName|lastName|fullName/i,/passport|driverLicense|nationalId/i],phi:[/medical|diagnosis|prescription|patient|health/i,/insurance|provider|treatment/i,/blood_type|allergy|medication/i],financial:[/creditCard|cardNumber|cvv|expiry|account_number/i,/bank|routing|swift|iban/i,/transaction|payment|billing/i],credentials:[/password|secret|apikey|api_key|token|auth/i,/private_key|certificate|credential/i],biometric:[/fingerprint|faceId|retina|voice_print/i,/biometric|facial_recognition/i]};for(let n of e)r.set(n,[]);for(let n of t){let s=await this.fileReader.readFile(n);if(!s.success)continue;let a=s.value.split(`
2908
- `);for(let o=0;o<a.length;o++){let l=a[o];for(let u of e){let d=i[u]||[];for(let m of d)if(m.test(l)){let p=r.get(u)||[];p.push({file:n,line:o+1,snippet:l.trim().substring(0,100),pattern:u,severity:"info"}),r.set(u,p);break}}}}return r}},Rd=null;function Td(){return Rd||(Rd=new Uo),Rd}var lf=["ls","cat","echo","grep","find","head","tail","wc","npm","node","yarn","pnpm","git","jest","vitest","playwright"],uf=[/;/,/&&/,/\|\|/,/\|/,/`[^`]*`/,/\$\([^)]*\)/,/>\s*\/dev\/sd/i,/>\s*\/etc\//i],b0=/[|;&$`<>{}[\]!#*?~]/g,ss=class{name="command-injection";defaultAllowedCommands;constructor(t=lf){this.defaultAllowedCommands=t}getRiskLevel(){return"critical"}validate(t,e={}){let r=e.allowedCommands??this.defaultAllowedCommands;return this.validateCommand(t,r)}validateCommand(t,e=this.defaultAllowedCommands){let r=[];for(let a of uf)a.test(t)&&r.push(a.source);if(r.length>0)return{valid:!1,error:"Command contains blocked patterns",blockedPatterns:r,riskLevel:"critical"};let i=t.trim().split(/\s+/),n=i[0].split("/").pop()||"";return e.includes(n)?{valid:!0,sanitizedCommand:i.map((a,o)=>o===0?a:a.replace(b0,"")).join(" "),blockedPatterns:[],riskLevel:"none"}:{valid:!1,error:`Command '${n}' is not in the allowed list`,blockedPatterns:[],riskLevel:"high"}}escapeShellArg(t){return`'${t.replace(/'/g,"'\\''")}'`}},cf=new ss,Qo=(c,t)=>t?cf.validateCommand(c,t):cf.validate(c);var df={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"},mf=[/('|")\s*;\s*--/i,/'\s*OR\s+'1'\s*=\s*'1/i,/"\s*OR\s+"1"\s*=\s*"1/i,/UNION\s+SELECT/i,/INSERT\s+INTO/i,/DROP\s+TABLE/i,/DELETE\s+FROM/i,/UPDATE\s+[^\s.!]+(?:\.[^\s.!]+)*\s+SET/i,/EXEC(\s+|\()sp_/i,/xp_cmdshell/i],pf=/[|;&$`<>{}[\]!#*?~]/g,gf=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,Ko=class{name="input-sanitization";getRiskLevel(){return"high"}sanitize(t,e={}){let{maxLength:r=1e4,allowedChars:i,stripHtml:n=!0,stripSql:s=!0,escapeShell:a=!0,trim:o=!0,stripControlChars:l=!0}=e,u=t;if(l&&(u=u.replace(gf,"")),o&&(u=u.trim()),u.length>r&&(u=u.substring(0,r)),n&&(u=this.stripHtmlTags(u)),s)for(let d of mf)u=u.replace(d,"");return a&&(u=u.replace(pf,"")),i&&(u=u.split("").filter(d=>i.test(d)).join("")),u}escapeHtml(t){return t.replace(/[&<>"'`=/]/g,e=>df[e]||e)}stripHtmlTags(t){t.length>1e5&&(t=t.slice(0,1e5));let r=t,i;do{i=r.length;let n="",s=!1;for(let a=0;a<r.length;a++){let o=r[a];o==="<"?s=!0:o===">"&&s?s=!1:s||(n+=o)}r=n}while(r.length<i&&r.length>0);return r=r.replace(/</g,"&lt;").replace(/>/g,"&gt;"),r}},uJ=new Ko;import{createHash as hf,timingSafeEqual as w0,randomBytes as C0}from"crypto";var Jo=class{name="crypto-security";getRiskLevel(){return"critical"}timingSafeCompare(t,e){let r=Math.max(t.length,e.length),i=t.padEnd(r,"\0"),n=e.padEnd(r,"\0");try{return w0(Buffer.from(i),Buffer.from(n))}catch{return!1}}timingSafeHashCompare(t,e){let r=hf("sha256").update(t).digest("hex");return this.timingSafeCompare(r,e)}generateSecureToken(t=32){return C0(t).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}secureHash(t,e){let r=e?`${e}:${t}`:t;return hf("sha256").update(r).digest("hex")}},pJ=new Jo;k();import*as ar from"fs/promises";var Hd=fb(av(),1);X();import*as se from"path";import{parse as Ox}from"yaml";hr();X();var lv=["npm-shrinkwrap.json","package-lock.json","pnpm-lock.yaml","yarn.lock"],Ix=["dependencies","devDependencies","optionalDependencies","peerDependencies"];function uv(c,t){let e=t.replace(/^\uFEFF/,"");if(c==="pnpm-lock.yaml"){if(!/^lockfileVersion:/m.test(e))throw new Error("not a pnpm lockfile (no lockfileVersion)");return Lx(e)}if(c==="yarn.lock"){if(!/^# yarn lockfile v1\b|^__metadata:/m.test(e))throw new Error('not a yarn lockfile (no "# yarn lockfile v1" or __metadata header)');return $x(e)}return Mx(c,e)}function Mx(c,t){let e=D(t);if(!e||typeof e!="object"||Array.isArray(e))throw new Error("not a JSON object");if(typeof e.lockfileVersion!="number")throw new Error("not an npm lockfile (no numeric lockfileVersion)");let r=e.packages,i=n=>n?`${n}/`:"";return{file:c,members:()=>r?Object.keys(r).filter(n=>n!==""&&!n.includes("node_modules/")):[],hasImporter:n=>n===""||!!r?.[n],recordedSpec(n,s){if(!r)return null;let a=r[n];if(a)for(let o of Ix){let l=a[o]?.[s];if(typeof l=="string")return l}},resolve(n,s){if(!r){let l=e.dependencies?.[s]?.version;if(typeof l!="string")return;let u=/^npm:((?:@[^/@]+\/)?[^@]+)@(.+)$/.exec(l);return u?{version:u[2],realName:u[1]}:{version:l}}let a=r[`${i(n)}node_modules/${s}`]??r[`node_modules/${s}`];if(!a)return;if(a.link===!0)return{local:!0};let o=typeof a.name=="string"&&a.name!==s?a.name:void 0;return typeof a.version=="string"?{version:a.version,...o?{realName:o}:{}}:void 0}}}var Di=c=>c.trim().replace(/^['"]|['"]$/g,""),ds=c=>c.length-c.trimStart().length;function ov(c,t,e,r){let i=new Map,n=new Map,s=null;for(let a=t;a<e;a++){let o=c[a];if(!o.trim()||o.trimStart().startsWith("#"))continue;let l=ds(o);if(l===r){let p=o.trim();s=/^(dependencies|devDependencies|optionalDependencies):\s*$/.test(p)?"deps":/^specifiers:\s*$/.test(p)?"specifiers":null;continue}if(!s||l!==r+2)continue;let u=cv(o.trim());if(!u)continue;let d=Di(u[1]);if(s==="specifiers"){n.set(d,Di(u[2]));continue}let m={};if(u[2])m.version=Di(u[2]);else for(let p=a+1;p<e&&(c[p].trim()===""||ds(c[p])>l);p++){let h=cv(c[p].trim());h&&(h[1]==="specifier"||h[1]==="version")&&h[2]&&(m[h[1]]=Di(h[2]))}i.set(d,m)}for(let[a,o]of n){let l=i.get(a);l&&l.specifier===void 0&&(l.specifier=o)}return i}function cv(c){let t=c.indexOf(":");if(t<=0)return null;let e=t+1;for(;e<c.length&&/\s/.test(c[e]);)e++;return[c,c.slice(0,t),c.slice(e)]}function lc(c,t){let e=c.indexOf(t);return e<0?c:c.slice(0,e)}var Fx=/^(?:npm:|\/)?((?:@[a-zA-Z0-9~-][a-zA-Z0-9._~-]*\/)?[a-zA-Z0-9~-][a-zA-Z0-9._~-]*)[@/](\d\S*)$/;function Lx(c){let t=c.split(/\r?\n/),e=new Map,r=t.findIndex(n=>/^importers:\s*$/.test(n));if(r>=0){let n=t.findIndex((s,a)=>a>r&&s.trim()!==""&&ds(s)===0);n<0&&(n=t.length);for(let s=r+1;s<n;s++){let a=t[s];if(ds(a)!==2||!a.trimEnd().endsWith(":"))continue;let o=Di(a.trim().slice(0,-1)),l=s+1;for(;l<n&&(t[l].trim()===""||ds(t[l])>2);)l++;e.set(o==="."?"":o,ov(t,s+1,l,4))}}else e.set("",ov(t,0,t.length,0));let i=n=>{let s=lc(n,"(").trim();if(s.startsWith("link:")||s.startsWith("file:")||s.startsWith("workspace:"))return{local:!0};if(/^\d/.test(s))return{version:lc(s,"_")};let a=Fx.exec(s);return a?{version:lc(a[2],"_"),realName:a[1]}:{version:lc(s,"_")}};return{file:"pnpm-lock.yaml",members:()=>[...e.keys()].filter(n=>n!==""),hasImporter:n=>n===""||e.has(n),recordedSpec(n,s){let a=e.get(n);if(!a)return;let o=a.get(s);if(o)return o.specifier??null},resolve(n,s){let a=e.get(n)?.get(s);return a?.version?i(a.version):void 0}}}function $x(c){let t=new Map,e=c.split(/\r?\n/);for(let r=0;r<e.length;r++){let i=e[r];if(!i||/^\s|^#/.test(i)||!i.trimEnd().endsWith(":"))continue;let n="",s="";for(let l=r+1;l<e.length&&/^\s/.test(e[l]);l++){let u=/^\s+version:?\s+"?([^"\s]+)"?\s*$/.exec(e[l]);u&&!n&&(n=u[1]);let d=/^\s+resolution:\s+"?([^"\s]+)"?\s*$/.exec(e[l]);d&&(s=d[1])}if(!n)continue;let a=n==="0.0.0-use.local"||/@(workspace|link|portal|file):/.test(s),o=/^((?:@[^/@]+\/)?[^@]+)@npm:/.exec(s)?.[1];for(let l of i.trimEnd().slice(0,-1).split(",")){let u=Di(l);t.set(u,a?{local:!0}:{version:n,...o&&!u.startsWith(`${o}@`)?{realName:o}:{}})}}return{file:"yarn.lock",members:()=>[],hasImporter:()=>!0,recordedSpec:()=>null,resolve:(r,i,n)=>t.get(`${i}@${n}`)??t.get(`${i}@npm:${n}`)}}var Nx="workspace member dependencies are not scanned yet (#1057); scan each member directory separately",_x="lockfile out of sync with package.json";function Vx(c){let t=Ve();for(let e of["peerDependencies","optionalDependencies","devDependencies","dependencies"])for(let[r,i]of Object.entries(c[e]??{}))typeof i=="string"&&ws(t,r,i);return t}async function dv(c){return D(await Re(c,{outsideRoot:"allow"}))}async function mv(c){try{return await ar.access(c),!0}catch{return!1}}async function Wd(c){try{return await ar.realpath(c)}catch{return se.resolve(c)}}async function zx(c,t=process.env){let e=await Wd(c),r=t.AQE_PROJECT_ROOT?await Wd(t.AQE_PROJECT_ROOT):null,i=r&&Bx(r,e)?r:null;for(;;){for(let s of lv)if(await mv(se.join(e,s)))return{dir:e,file:s};if(e===i||await mv(se.join(e,".git")))return null;let n=se.dirname(e);if(n===e)return null;e=n}}function Bx(c,t){let e=se.relative(c,t);return e===""||!e.startsWith("..")&&!se.isAbsolute(e)}var pv=1024*1024,gv=c=>Array.isArray(c)&&c.length>0;async function hv(c,t){let e=t.workspaces;return gv(e)||e!==null&&typeof e=="object"&&gv(e.packages)?!0:qx(se.join(c,"pnpm-workspace.yaml"))}async function qx(c){try{await ar.lstat(c)}catch(r){return r.code!=="ENOENT"}let t;try{let r=await ar.stat(c);if(!r.isFile()||r.size>pv)return!0;let i=await Re(c,{outsideRoot:"allow",maxBytes:pv});t=Ox(i,{uniqueKeys:!1,merge:!0,maxAliasCount:100})}catch{return!0}if(t===null||typeof t!="object"||Array.isArray(t))return!0;if(!Object.prototype.hasOwnProperty.call(t,"packages"))return!1;let e=t.packages;return!Array.isArray(e)||e.length>0}function fv(c,t,e,r,i){let n={name:c,spec:t,member:e},s=Bo(t);if(s.kind==="local")return{...n,kind:"local",reason:"local package (workspace/link/file directory)"};if(s.kind==="remote")return{...n,kind:"unchecked",reason:`not a registry dependency ("${t}": git/URL/tarball source); OSV advisories cannot be matched`};let a=s.kind==="alias"?s.name:c,o=s.spec,l=r?.resolve(e,c,t);if(l?.local||!l&&i.has(c))return{...n,kind:"local",reason:"workspace package (local source)"};if(l&&r){let d=r.recordedSpec(e,c),m=l.version?xi(l.version)??void 0:void 0,p=d===void 0||d!==null&&d!==t,h=m!==void 0&&!!Hd.default.validRange(o)&&!Hd.default.satisfies(m,o,{includePrerelease:!0});if(p||h)return{...n,kind:"unchecked",...m?{lockedVersion:m}:{},reason:`${_x} (${r.file} has ${d?`"${d}"`:"no entry"}${m?` -> ${m}`:""} for "${t}")`};if(m)return{...n,kind:"check",packageName:l.realName??a,version:m,lockedVersion:m}}let u=xi(o);return u?{...n,kind:"check",packageName:a,version:u}:{...n,kind:"unchecked",reason:`version range "${t}", no lockfile resolution`}}function yv(c,t={}){let e={file:"package-lock.json",members:()=>[],hasImporter:()=>!0,recordedSpec:()=>null,resolve:(r,i)=>{let n=gr(t,i);return n!==void 0?{version:n}:void 0}};return Object.entries(c).map(([r,i])=>fv(r,i,"",e,new Set))}async function uc(c){let t=se.dirname(se.resolve(c)),e=await dv(c),r=null,i=await Wd(t),n=i,s=null,a,o=await zx(t);if(o){let m=se.relative(o.dir,n).split(se.sep).join("/");try{let p=uv(o.file,await Re(se.join(o.dir,o.file),{outsideRoot:"allow"})),h=m?await dv(se.join(o.dir,"package.json")).catch(()=>({})):e;(m===""||p.hasImporter(m)&&(p.file!=="yarn.lock"||await hv(o.dir,h)))&&(r=p,i=o.dir,s=se.relative(n,se.join(o.dir,o.file)).split(se.sep).join("/"))}catch(p){a=`${se.relative(n,se.join(o.dir,o.file)).split(se.sep).join("/")} could not be read or parsed (${p instanceof Error?p.message.slice(0,120):"error"}); versions were not resolved from it`}}let l=se.relative(i,n).split(se.sep).join("/"),u=await hv(n,e)?[Nx]:[],d=[];for(let[m,p]of Object.entries(Vx(e)))d.push(fv(m,p,l,r,new Set));return{dependencies:d,lockfile:s,memberErrors:u,...a?{error:a}:{}}}var Ii=class{config;memory;osvClient;activeScans;constructor(t,e,r,i){this.config=t,this.memory=e,this.osvClient=i??new Nr({enableCache:!0}),this.activeScans=r||new Map}async scanDependencies(t,e={}){return Object.keys(t).length===0?g(new Error("No dependencies provided for scanning")):this.runScan({dependencies:yv(t,e),lockfile:null,errors:[]})}async scanPackageJson(t){try{let e=await uc(t);return this.runScan({dependencies:e.dependencies,lockfile:e.lockfile,errors:[...e.error?[e.error]:[],...e.memberErrors]})}catch(e){return e instanceof SyntaxError?g(new Error(`Invalid JSON in package.json: ${e.message}`)):g(y(e))}}async getScanStatus(t){return this.activeScans.get(t)??"pending"}async runScan(t){let e=w(),r=Date.now();try{this.activeScans.set(e,"running");let i=t.dependencies.filter(T=>T.kind==="check"),n=[...new Map(i.map(T=>{let I={name:T.packageName,ecosystem:"npm",version:T.version};return[nr(I),I]})).values()],s=await this.osvClient.lookupBatch(n),a=new Map(s.unchecked.map(T=>[nr(T),T.reason])),o=[],l=[],u=[],d=new Set,m=0,p=T=>T.member?{member:T.member}:{};for(let T of t.dependencies){if(T.kind==="local"){u.push({name:T.name,spec:T.spec,reason:T.reason??"local package",...p(T)});continue}if(T.kind==="unchecked"){l.push({name:T.name,version:T.spec,reason:T.reason??"not checked",...p(T),...T.lockedVersion?{lockedVersion:T.lockedVersion}:{}});continue}let I=nr({name:T.packageName,ecosystem:"npm",version:T.version}),O=s.results.get(I);if(!O){l.push({name:T.name,version:T.spec,reason:a.get(I)??"advisory lookup did not return a result",...p(T),...T.lockedVersion?{lockedVersion:T.lockedVersion}:{}});continue}m++,O.length>0&&d.add(T.packageName),o.push(...this.convertOSVVulnerabilities(O,T))}let h=m+l.length,b=m===h&&t.errors.length===0?"complete":m===0&&h>0?"failed":"incomplete",C=Date.now()-r,S=this.calculateSummary(o,h,C),R=b==="complete"?void 0:Gx([...t.errors,...s.errors],l),E={scanId:e,vulnerabilities:o,packagesScanned:h,vulnerablePackages:d.size,summary:S,scanDurationMs:C,status:b,measured:b==="complete",packagesChecked:m,uncheckedPackages:l,lockfile:t.lockfile,localPackages:u,resolutionErrors:t.errors,scope:"direct",...R?{error:R}:{}};return await this.storeScanResults(E),this.activeScans.set(e,b==="complete"?"completed":"failed"),f(E)}catch(i){return this.activeScans.set(e,"failed"),g(y(i))}}convertOSVVulnerabilities(t,e){let r=e.packageName,i=r===e.name?r:`${e.name} (${r})`;return t.map(n=>{let s={file:e.member?`${e.member}/package.json`:"package.json",line:1,column:1,snippet:`"${e.name}": "${e.spec}"`,dependency:{name:r,version:e.version,ecosystem:"npm"}},a={description:n.fixedVersions.length>0?`Update to version ${n.fixedVersions[0]} or later`:"No fixed version available; consider alternative packages",fixExample:n.fixedVersions.length>0?`npm install ${r}@${n.fixedVersions[0]}`:void 0,estimatedEffort:"minor",automatable:!0};return{id:w(),cveId:n.cveIds[0],title:`${i}: ${n.summary.substring(0,80)}`,description:n.details||n.summary,severity:this.mapOSVSeverity(n.severity),category:"vulnerable-components",location:s,remediation:a,references:n.references.slice(0,5)}})}mapOSVSeverity(t){return{critical:"critical",high:"high",medium:"medium",low:"low",unknown:"medium"}[t]}calculateSummary(t,e,r){let i={critical:0,high:0,medium:0,low:0,informational:0,totalFiles:e,scanDurationMs:r};for(let n of t)i[n.severity]++;return i}async storeScanResults(t){await this.memory.set(`security:scan:${t.scanId}`,{scanId:t.scanId,scanType:"dependency",advisorySource:"osv",status:t.status,measured:t.measured,scope:t.scope??"direct",packagesRequested:t.packagesScanned,packagesChecked:t.packagesChecked,uncheckedPackages:t.uncheckedPackages,localPackages:t.localPackages??[],resolutionErrors:t.resolutionErrors??[],lockfile:t.lockfile??null,...t.error?{error:t.error}:{},vulnerabilities:t.vulnerabilities,summary:t.summary,timestamp:new Date().toISOString()},{namespace:"security-compliance",ttl:86400*7})}};function Gx(c,t){let e=c.length>0?c:[...new Set(t.map(i=>i.reason))];return`Dependency advisories could not be checked for ${t.length>0?`${t.length} package(s)`:"some dependencies"}: ${e.slice(0,3).join("; ")}`}k();var dt=class{config;memory;llmRouter;activeScans=new Map;sastScanner;dastScanner;dependencyScanner;constructor(t,e={}){this.config={...xo,...e},"memory"in t?(this.memory=t.memory,this.llmRouter=t.llmRouter):this.memory=t,this.sastScanner=new Ei(this.config,this.memory,this.llmRouter,this.activeScans),this.dastScanner=new Ai(this.config,this.memory,this.activeScans),this.dependencyScanner=new Ii(this.config,this.memory,this.activeScans)}async scanFiles(t){return this.sastScanner.scanFiles(t)}async scanWithRules(t,e){return this.sastScanner.scanWithRules(t,e)}async getAvailableRuleSets(){return this.sastScanner.getAvailableRuleSets()}async checkFalsePositive(t){return this.sastScanner.checkFalsePositive(t)}async scanUrl(t,e){return this.dastScanner.scanUrl(t,e)}async scanAuthenticated(t,e,r){return this.dastScanner.scanAuthenticated(t,e,r)}async getScanStatus(t){return this.activeScans.get(t)??"pending"}async scanDependencies(t){return this.dependencyScanner.scanDependencies(t)}async scanPackageJson(t){return this.dependencyScanner.scanPackageJson(t)}async runFullScan(t,e,r){try{let i=await this.scanWithRules(t,this.config.defaultRuleSets);if(i.success===!1)return g(i.error);let n;if(e){let a=await this.scanUrl(e,r);if(a.success)n=a.value;else return g(a.error)}let s=this.combineSummaries(i.value.summary,n?.summary);return f({sastResult:i.value,dastResult:n,combinedSummary:s})}catch(i){return g(y(i))}}isLLMAnalysisAvailable(){return this.sastScanner.isLLMAnalysisAvailable()}getModelForTier(t){return this.sastScanner.getModelForTier(t)}async analyzeVulnerabilityWithLLM(t,e){return this.sastScanner.analyzeVulnerabilityWithLLM(t,e)}combineSummaries(t,e){return e?{critical:t.critical+e.critical,high:t.high+e.high,medium:t.medium+e.medium,low:t.low+e.low,informational:t.informational+e.informational,totalFiles:t.totalFiles+e.totalFiles,scanDurationMs:t.scanDurationMs+e.scanDurationMs}:t}};_();import*as Pv from"fs/promises";import*as ps from"path";k();X();async function ms(c){let t=await fetch(c,{method:"GET",headers:{Accept:"application/json"}}),e=await t.json();return{ok:t.ok,status:t.status,data:e}}var Ud={secretPatterns:[/(?:api[_-]?key|apikey)['":\s]*['"=]?\s*['"]?([a-zA-Z0-9_\-]{20,})['"]?/gi,/(?:password|passwd|pwd)['":\s]*['"=]?\s*['"]?([^\s'"]{8,})['"]?/gi,/(?:secret|token)['":\s]*['"=]?\s*['"]?([a-zA-Z0-9_\-]{16,})['"]?/gi,/(?:aws[_-]?access[_-]?key|aws[_-]?secret)['":\s]*['"=]?\s*['"]?([A-Z0-9]{20,})['"]?/gi,/-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/gi,/ghp_[a-zA-Z0-9]{36}/g,/gho_[a-zA-Z0-9]{36}/g,/sk-[a-zA-Z0-9]{48}/g],excludePatterns:["node_modules","dist","build",".git","*.test.*","*.spec.*"],maxFileSizeKb:1024,enableHistoricalAnalysis:!0,riskThreshold:.7};_();import*as vv from"path";var jx=x.create("security-compliance/security-auditor-sast");function Hx(){return[{id:"sqli-concat",pattern:/(?:query|execute|exec|run)\s*\(\s*(?:['"`].*?\s*\+|`[^`]*\$\{)/gi,title:"SQL Injection via String Concatenation",description:"SQL query constructed using string concatenation with potentially untrusted input",severity:"critical",category:"injection",remediation:"Use parameterized queries or prepared statements",fixExample:'db.query("SELECT * FROM users WHERE id = $1", [userId])',cweId:"CWE-89"},{id:"xss-innerhtml",pattern:/\.innerHTML\s*=\s*(?!['"`])/g,title:"XSS via innerHTML Assignment",description:"Direct innerHTML assignment with potentially unsanitized content",severity:"high",category:"xss",remediation:"Use textContent for text, or sanitize HTML with DOMPurify",fixExample:"element.textContent = userInput;",cweId:"CWE-79"},{id:"xss-document-write",pattern:/document\.write\s*\([^)]+\)/g,title:"XSS via document.write",description:"document.write() can execute scripts from untrusted data",severity:"high",category:"xss",remediation:"Avoid document.write(); use DOM manipulation methods",cweId:"CWE-79"},{id:"xss-eval",pattern:/(?<!\.)\beval\s*\([^)]+\)/g,title:"Code Injection via eval()",description:"eval() executes arbitrary code and is a major security risk",severity:"critical",category:"xss",remediation:"Never use eval(); use JSON.parse() for JSON data",fixExample:"JSON.parse(jsonString)",cweId:"CWE-95"},{id:"xss-dangerous-react",pattern:/dangerouslySetInnerHTML\s*=\s*\{/g,title:"React dangerouslySetInnerHTML Usage",description:"dangerouslySetInnerHTML bypasses React XSS protections",severity:"medium",category:"xss",remediation:"Sanitize HTML content with DOMPurify before use",fixExample:"dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(content) }}",cweId:"CWE-79"},{id:"cmd-injection-exec",pattern:/(?:child_process\.)?exec\s*\(\s*(?:[^,)]*\s*\+|`[^`]*\$\{)/g,title:"Command Injection via exec()",description:"Shell command execution with unsanitized input",severity:"critical",category:"injection",remediation:"Use execFile() with argument array instead of exec()",fixExample:'execFile("command", [arg1, arg2], callback)',cweId:"CWE-78"},{id:"cmd-injection-spawn-shell",pattern:/spawn\s*\([^)]+,\s*\{[^}]*shell\s*:\s*true/g,title:"Dangerous Shell Option in spawn()",description:"spawn() with shell: true can enable command injection",severity:"high",category:"injection",remediation:"Avoid shell: true option; use direct command execution",cweId:"CWE-78"},{id:"path-traversal-readfile",pattern:/(?:readFile|readFileSync)\s*\([^)]*\+/g,title:"Path Traversal via File Read",description:"File read operation with concatenated path may allow directory traversal",severity:"high",category:"access-control",remediation:"Validate and sanitize file paths; use path.resolve() and check against base directory",fixExample:"const safePath = path.resolve(baseDir, path.basename(userInput))",cweId:"CWE-22"},{id:"path-traversal-writefile",pattern:/(?:writeFile|writeFileSync)\s*\([^)]*\+/g,title:"Path Traversal via File Write",description:"File write operation with concatenated path may allow directory traversal",severity:"high",category:"access-control",remediation:"Validate file paths before writing; ensure path is within allowed directory",cweId:"CWE-22"},{id:"secret-private-key",pattern:/-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/g,title:"Private Key Detected in Source",description:"Private key found in source code",severity:"critical",category:"sensitive-data",remediation:"Store private keys in secure key management systems, not in code",cweId:"CWE-798"},{id:"config-tls-disabled",pattern:/rejectUnauthorized\s*:\s*false/g,title:"TLS Certificate Validation Disabled",description:"Disabling TLS certificate validation exposes to MITM attacks",severity:"high",category:"security-misconfiguration",remediation:"Always enable TLS certificate validation in production",cweId:"CWE-295"},{id:"config-cors-wildcard",pattern:/cors\s*\(\s*\{[^}]*origin\s*:\s*['"]\*['"]/gi,title:"Permissive CORS Configuration",description:"CORS allows all origins (*) which may expose sensitive data",severity:"medium",category:"security-misconfiguration",remediation:"Restrict CORS to specific trusted origins",fixExample:'cors({ origin: ["https://trusted-domain.com"] })',cweId:"CWE-942"}]}async function bv(c,t){let e=w(),r=Date.now(),i=[],n=0,s=0;try{let p=await c(process.cwd()),h=Hx();for(let v of p){if(t(v))continue;let b=vv.extname(v).toLowerCase();if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(b))try{let C=await Re(v,{outsideRoot:"allow"}),S=C.split(`
2908
+ `);for(let o=0;o<a.length;o++){let l=a[o];for(let u of e){let d=i[u]||[];for(let m of d)if(m.test(l)){let p=r.get(u)||[];p.push({file:n,line:o+1,snippet:l.trim().substring(0,100),pattern:u,severity:"info"}),r.set(u,p);break}}}}return r}},Rd=null;function Td(){return Rd||(Rd=new Uo),Rd}var lf=["ls","cat","echo","grep","find","head","tail","wc","npm","node","yarn","pnpm","git","jest","vitest","playwright"],uf=[/;/,/&&/,/\|\|/,/\|/,/`[^`]*`/,/\$\([^)]*\)/,/>\s*\/dev\/sd/i,/>\s*\/etc\//i],w0=/[|;&$`<>{}[\]!#*?~]/g,ss=class{name="command-injection";defaultAllowedCommands;constructor(t=lf){this.defaultAllowedCommands=t}getRiskLevel(){return"critical"}validate(t,e={}){let r=e.allowedCommands??this.defaultAllowedCommands;return this.validateCommand(t,r)}validateCommand(t,e=this.defaultAllowedCommands){let r=[];for(let a of uf)a.test(t)&&r.push(a.source);if(r.length>0)return{valid:!1,error:"Command contains blocked patterns",blockedPatterns:r,riskLevel:"critical"};let i=t.trim().split(/\s+/),n=i[0].split("/").pop()||"";return e.includes(n)?{valid:!0,sanitizedCommand:i.map((a,o)=>o===0?a:a.replace(w0,"")).join(" "),blockedPatterns:[],riskLevel:"none"}:{valid:!1,error:`Command '${n}' is not in the allowed list`,blockedPatterns:[],riskLevel:"high"}}escapeShellArg(t){return`'${t.replace(/'/g,"'\\''")}'`}},cf=new ss,Qo=(c,t)=>t?cf.validateCommand(c,t):cf.validate(c);var df={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"},mf=[/('|")\s*;\s*--/i,/'\s*OR\s+'1'\s*=\s*'1/i,/"\s*OR\s+"1"\s*=\s*"1/i,/UNION\s+SELECT/i,/INSERT\s+INTO/i,/DROP\s+TABLE/i,/DELETE\s+FROM/i,/UPDATE\s+[^\s.!]+(?:\.[^\s.!]+)*\s+SET/i,/EXEC(\s+|\()sp_/i,/xp_cmdshell/i],pf=/[|;&$`<>{}[\]!#*?~]/g,gf=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,Ko=class{name="input-sanitization";getRiskLevel(){return"high"}sanitize(t,e={}){let{maxLength:r=1e4,allowedChars:i,stripHtml:n=!0,stripSql:s=!0,escapeShell:a=!0,trim:o=!0,stripControlChars:l=!0}=e,u=t;if(l&&(u=u.replace(gf,"")),o&&(u=u.trim()),u.length>r&&(u=u.substring(0,r)),n&&(u=this.stripHtmlTags(u)),s)for(let d of mf)u=u.replace(d,"");return a&&(u=u.replace(pf,"")),i&&(u=u.split("").filter(d=>i.test(d)).join("")),u}escapeHtml(t){return t.replace(/[&<>"'`=/]/g,e=>df[e]||e)}stripHtmlTags(t){t.length>1e5&&(t=t.slice(0,1e5));let r=t,i;do{i=r.length;let n="",s=!1;for(let a=0;a<r.length;a++){let o=r[a];o==="<"?s=!0:o===">"&&s?s=!1:s||(n+=o)}r=n}while(r.length<i&&r.length>0);return r=r.replace(/</g,"&lt;").replace(/>/g,"&gt;"),r}},mJ=new Ko;import{createHash as hf,timingSafeEqual as C0,randomBytes as S0}from"crypto";var Jo=class{name="crypto-security";getRiskLevel(){return"critical"}timingSafeCompare(t,e){let r=Math.max(t.length,e.length),i=t.padEnd(r,"\0"),n=e.padEnd(r,"\0");try{return C0(Buffer.from(i),Buffer.from(n))}catch{return!1}}timingSafeHashCompare(t,e){let r=hf("sha256").update(t).digest("hex");return this.timingSafeCompare(r,e)}generateSecureToken(t=32){return S0(t).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}secureHash(t,e){let r=e?`${e}:${t}`:t;return hf("sha256").update(r).digest("hex")}},hJ=new Jo;k();import*as ar from"fs/promises";var Hd=fb(av(),1);X();import*as se from"path";import{parse as Nx}from"yaml";hr();X();var lv=["npm-shrinkwrap.json","package-lock.json","pnpm-lock.yaml","yarn.lock"],Mx=["dependencies","devDependencies","optionalDependencies","peerDependencies"];function uv(c,t){let e=t.replace(/^\uFEFF/,"");if(c==="pnpm-lock.yaml"){if(!/^lockfileVersion:/m.test(e))throw new Error("not a pnpm lockfile (no lockfileVersion)");return $x(e)}if(c==="yarn.lock"){if(!/^# yarn lockfile v1\b|^__metadata:/m.test(e))throw new Error('not a yarn lockfile (no "# yarn lockfile v1" or __metadata header)');return Ox(e)}return Fx(c,e)}function Fx(c,t){let e=D(t);if(!e||typeof e!="object"||Array.isArray(e))throw new Error("not a JSON object");if(typeof e.lockfileVersion!="number")throw new Error("not an npm lockfile (no numeric lockfileVersion)");let r=e.packages,i=n=>n?`${n}/`:"";return{file:c,members:()=>r?Object.keys(r).filter(n=>n!==""&&!n.includes("node_modules/")):[],hasImporter:n=>n===""||!!r?.[n],recordedSpec(n,s){if(!r)return null;let a=r[n];if(a)for(let o of Mx){let l=a[o]?.[s];if(typeof l=="string")return l}},resolve(n,s){if(!r){let l=e.dependencies?.[s]?.version;if(typeof l!="string")return;let u=/^npm:((?:@[^/@]+\/)?[^@]+)@(.+)$/.exec(l);return u?{version:u[2],realName:u[1]}:{version:l}}let a=r[`${i(n)}node_modules/${s}`]??r[`node_modules/${s}`];if(!a)return;if(a.link===!0)return{local:!0};let o=typeof a.name=="string"&&a.name!==s?a.name:void 0;return typeof a.version=="string"?{version:a.version,...o?{realName:o}:{}}:void 0}}}var Di=c=>c.trim().replace(/^['"]|['"]$/g,""),ds=c=>c.length-c.trimStart().length;function ov(c,t,e,r){let i=new Map,n=new Map,s=null;for(let a=t;a<e;a++){let o=c[a];if(!o.trim()||o.trimStart().startsWith("#"))continue;let l=ds(o);if(l===r){let p=o.trim();s=/^(dependencies|devDependencies|optionalDependencies):\s*$/.test(p)?"deps":/^specifiers:\s*$/.test(p)?"specifiers":null;continue}if(!s||l!==r+2)continue;let u=cv(o.trim());if(!u)continue;let d=Di(u[1]);if(s==="specifiers"){n.set(d,Di(u[2]));continue}let m={};if(u[2])m.version=Di(u[2]);else for(let p=a+1;p<e&&(c[p].trim()===""||ds(c[p])>l);p++){let h=cv(c[p].trim());h&&(h[1]==="specifier"||h[1]==="version")&&h[2]&&(m[h[1]]=Di(h[2]))}i.set(d,m)}for(let[a,o]of n){let l=i.get(a);l&&l.specifier===void 0&&(l.specifier=o)}return i}function cv(c){let t=c.indexOf(":");if(t<=0)return null;let e=t+1;for(;e<c.length&&/\s/.test(c[e]);)e++;return[c,c.slice(0,t),c.slice(e)]}function lc(c,t){let e=c.indexOf(t);return e<0?c:c.slice(0,e)}var Lx=/^(?:npm:|\/)?((?:@[a-zA-Z0-9~-][a-zA-Z0-9._~-]*\/)?[a-zA-Z0-9~-][a-zA-Z0-9._~-]*)[@/](\d\S*)$/;function $x(c){let t=c.split(/\r?\n/),e=new Map,r=t.findIndex(n=>/^importers:\s*$/.test(n));if(r>=0){let n=t.findIndex((s,a)=>a>r&&s.trim()!==""&&ds(s)===0);n<0&&(n=t.length);for(let s=r+1;s<n;s++){let a=t[s];if(ds(a)!==2||!a.trimEnd().endsWith(":"))continue;let o=Di(a.trim().slice(0,-1)),l=s+1;for(;l<n&&(t[l].trim()===""||ds(t[l])>2);)l++;e.set(o==="."?"":o,ov(t,s+1,l,4))}}else e.set("",ov(t,0,t.length,0));let i=n=>{let s=lc(n,"(").trim();if(s.startsWith("link:")||s.startsWith("file:")||s.startsWith("workspace:"))return{local:!0};if(/^\d/.test(s))return{version:lc(s,"_")};let a=Lx.exec(s);return a?{version:lc(a[2],"_"),realName:a[1]}:{version:lc(s,"_")}};return{file:"pnpm-lock.yaml",members:()=>[...e.keys()].filter(n=>n!==""),hasImporter:n=>n===""||e.has(n),recordedSpec(n,s){let a=e.get(n);if(!a)return;let o=a.get(s);if(o)return o.specifier??null},resolve(n,s){let a=e.get(n)?.get(s);return a?.version?i(a.version):void 0}}}function Ox(c){let t=new Map,e=c.split(/\r?\n/);for(let r=0;r<e.length;r++){let i=e[r];if(!i||/^\s|^#/.test(i)||!i.trimEnd().endsWith(":"))continue;let n="",s="";for(let l=r+1;l<e.length&&/^\s/.test(e[l]);l++){let u=/^\s+version:?\s+"?([^"\s]+)"?\s*$/.exec(e[l]);u&&!n&&(n=u[1]);let d=/^\s+resolution:\s+"?([^"\s]+)"?\s*$/.exec(e[l]);d&&(s=d[1])}if(!n)continue;let a=n==="0.0.0-use.local"||/@(workspace|link|portal|file):/.test(s),o=/^((?:@[^/@]+\/)?[^@]+)@npm:/.exec(s)?.[1];for(let l of i.trimEnd().slice(0,-1).split(",")){let u=Di(l);t.set(u,a?{local:!0}:{version:n,...o&&!u.startsWith(`${o}@`)?{realName:o}:{}})}}return{file:"yarn.lock",members:()=>[],hasImporter:()=>!0,recordedSpec:()=>null,resolve:(r,i,n)=>t.get(`${i}@${n}`)??t.get(`${i}@npm:${n}`)}}var _x="workspace member dependencies are not scanned yet (#1057); scan each member directory separately",Vx="lockfile out of sync with package.json";function zx(c){let t=Ve();for(let e of["peerDependencies","optionalDependencies","devDependencies","dependencies"])for(let[r,i]of Object.entries(c[e]??{}))typeof i=="string"&&ws(t,r,i);return t}async function dv(c){return D(await Re(c,{outsideRoot:"allow"}))}async function mv(c){try{return await ar.access(c),!0}catch{return!1}}async function Wd(c){try{return await ar.realpath(c)}catch{return se.resolve(c)}}async function Bx(c,t=process.env){let e=await Wd(c),r=t.AQE_PROJECT_ROOT?await Wd(t.AQE_PROJECT_ROOT):null,i=r&&qx(r,e)?r:null;for(;;){for(let s of lv)if(await mv(se.join(e,s)))return{dir:e,file:s};if(e===i||await mv(se.join(e,".git")))return null;let n=se.dirname(e);if(n===e)return null;e=n}}function qx(c,t){let e=se.relative(c,t);return e===""||!e.startsWith("..")&&!se.isAbsolute(e)}var pv=1024*1024,gv=c=>Array.isArray(c)&&c.length>0;async function hv(c,t){let e=t.workspaces;return gv(e)||e!==null&&typeof e=="object"&&gv(e.packages)?!0:Gx(se.join(c,"pnpm-workspace.yaml"))}async function Gx(c){try{await ar.lstat(c)}catch(r){return r.code!=="ENOENT"}let t;try{let r=await ar.stat(c);if(!r.isFile()||r.size>pv)return!0;let i=await Re(c,{outsideRoot:"allow",maxBytes:pv});t=Nx(i,{uniqueKeys:!1,merge:!0,maxAliasCount:100})}catch{return!0}if(t===null||typeof t!="object"||Array.isArray(t))return!0;if(!Object.prototype.hasOwnProperty.call(t,"packages"))return!1;let e=t.packages;return!Array.isArray(e)||e.length>0}function fv(c,t,e,r,i){let n={name:c,spec:t,member:e},s=Bo(t);if(s.kind==="local")return{...n,kind:"local",reason:"local package (workspace/link/file directory)"};if(s.kind==="remote")return{...n,kind:"unchecked",reason:`not a registry dependency ("${t}": git/URL/tarball source); OSV advisories cannot be matched`};let a=s.kind==="alias"?s.name:c,o=s.spec,l=r?.resolve(e,c,t);if(l?.local||!l&&i.has(c))return{...n,kind:"local",reason:"workspace package (local source)"};if(l&&r){let d=r.recordedSpec(e,c),m=l.version?xi(l.version)??void 0:void 0,p=d===void 0||d!==null&&d!==t,h=m!==void 0&&!!Hd.default.validRange(o)&&!Hd.default.satisfies(m,o,{includePrerelease:!0});if(p||h)return{...n,kind:"unchecked",...m?{lockedVersion:m}:{},reason:`${Vx} (${r.file} has ${d?`"${d}"`:"no entry"}${m?` -> ${m}`:""} for "${t}")`};if(m)return{...n,kind:"check",packageName:l.realName??a,version:m,lockedVersion:m}}let u=xi(o);return u?{...n,kind:"check",packageName:a,version:u}:{...n,kind:"unchecked",reason:`version range "${t}", no lockfile resolution`}}function yv(c,t={}){let e={file:"package-lock.json",members:()=>[],hasImporter:()=>!0,recordedSpec:()=>null,resolve:(r,i)=>{let n=gr(t,i);return n!==void 0?{version:n}:void 0}};return Object.entries(c).map(([r,i])=>fv(r,i,"",e,new Set))}async function uc(c){let t=se.dirname(se.resolve(c)),e=await dv(c),r=null,i=await Wd(t),n=i,s=null,a,o=await Bx(t);if(o){let m=se.relative(o.dir,n).split(se.sep).join("/");try{let p=uv(o.file,await Re(se.join(o.dir,o.file),{outsideRoot:"allow"})),h=m?await dv(se.join(o.dir,"package.json")).catch(()=>({})):e;(m===""||p.hasImporter(m)&&(p.file!=="yarn.lock"||await hv(o.dir,h)))&&(r=p,i=o.dir,s=se.relative(n,se.join(o.dir,o.file)).split(se.sep).join("/"))}catch(p){a=`${se.relative(n,se.join(o.dir,o.file)).split(se.sep).join("/")} could not be read or parsed (${p instanceof Error?p.message.slice(0,120):"error"}); versions were not resolved from it`}}let l=se.relative(i,n).split(se.sep).join("/"),u=await hv(n,e)?[_x]:[],d=[];for(let[m,p]of Object.entries(zx(e)))d.push(fv(m,p,l,r,new Set));return{dependencies:d,lockfile:s,memberErrors:u,...a?{error:a}:{}}}var Ii=class{config;memory;osvClient;activeScans;constructor(t,e,r,i){this.config=t,this.memory=e,this.osvClient=i??new Nr({enableCache:!0}),this.activeScans=r||new Map}async scanDependencies(t,e={}){return Object.keys(t).length===0?g(new Error("No dependencies provided for scanning")):this.runScan({dependencies:yv(t,e),lockfile:null,errors:[]})}async scanPackageJson(t){try{let e=await uc(t);return this.runScan({dependencies:e.dependencies,lockfile:e.lockfile,errors:[...e.error?[e.error]:[],...e.memberErrors]})}catch(e){return e instanceof SyntaxError?g(new Error(`Invalid JSON in package.json: ${e.message}`)):g(y(e))}}async getScanStatus(t){return this.activeScans.get(t)??"pending"}async runScan(t){let e=w(),r=Date.now();try{this.activeScans.set(e,"running");let i=t.dependencies.filter(T=>T.kind==="check"),n=[...new Map(i.map(T=>{let I={name:T.packageName,ecosystem:"npm",version:T.version};return[nr(I),I]})).values()],s=await this.osvClient.lookupBatch(n),a=new Map(s.unchecked.map(T=>[nr(T),T.reason])),o=[],l=[],u=[],d=new Set,m=0,p=T=>T.member?{member:T.member}:{};for(let T of t.dependencies){if(T.kind==="local"){u.push({name:T.name,spec:T.spec,reason:T.reason??"local package",...p(T)});continue}if(T.kind==="unchecked"){l.push({name:T.name,version:T.spec,reason:T.reason??"not checked",...p(T),...T.lockedVersion?{lockedVersion:T.lockedVersion}:{}});continue}let I=nr({name:T.packageName,ecosystem:"npm",version:T.version}),O=s.results.get(I);if(!O){l.push({name:T.name,version:T.spec,reason:a.get(I)??"advisory lookup did not return a result",...p(T),...T.lockedVersion?{lockedVersion:T.lockedVersion}:{}});continue}m++,O.length>0&&d.add(T.packageName),o.push(...this.convertOSVVulnerabilities(O,T))}let h=m+l.length,b=m===h&&t.errors.length===0?"complete":m===0&&h>0?"failed":"incomplete",C=Date.now()-r,S=this.calculateSummary(o,h,C),R=b==="complete"?void 0:jx([...t.errors,...s.errors],l),E={scanId:e,vulnerabilities:o,packagesScanned:h,vulnerablePackages:d.size,summary:S,scanDurationMs:C,status:b,measured:b==="complete",packagesChecked:m,uncheckedPackages:l,lockfile:t.lockfile,localPackages:u,resolutionErrors:t.errors,scope:"direct",...R?{error:R}:{}};return await this.storeScanResults(E),this.activeScans.set(e,b==="complete"?"completed":"failed"),f(E)}catch(i){return this.activeScans.set(e,"failed"),g(y(i))}}convertOSVVulnerabilities(t,e){let r=e.packageName,i=r===e.name?r:`${e.name} (${r})`;return t.map(n=>{let s={file:e.member?`${e.member}/package.json`:"package.json",line:1,column:1,snippet:`"${e.name}": "${e.spec}"`,dependency:{name:r,version:e.version,ecosystem:"npm"}},a={description:n.fixedVersions.length>0?`Update to version ${n.fixedVersions[0]} or later`:"No fixed version available; consider alternative packages",fixExample:n.fixedVersions.length>0?`npm install ${r}@${n.fixedVersions[0]}`:void 0,estimatedEffort:"minor",automatable:!0};return{id:w(),cveId:n.cveIds[0],title:`${i}: ${n.summary.substring(0,80)}`,description:n.details||n.summary,severity:this.mapOSVSeverity(n.severity),category:"vulnerable-components",location:s,remediation:a,references:n.references.slice(0,5)}})}mapOSVSeverity(t){return{critical:"critical",high:"high",medium:"medium",low:"low",unknown:"medium"}[t]}calculateSummary(t,e,r){let i={critical:0,high:0,medium:0,low:0,informational:0,totalFiles:e,scanDurationMs:r};for(let n of t)i[n.severity]++;return i}async storeScanResults(t){await this.memory.set(`security:scan:${t.scanId}`,{scanId:t.scanId,scanType:"dependency",advisorySource:"osv",status:t.status,measured:t.measured,scope:t.scope??"direct",packagesRequested:t.packagesScanned,packagesChecked:t.packagesChecked,uncheckedPackages:t.uncheckedPackages,localPackages:t.localPackages??[],resolutionErrors:t.resolutionErrors??[],lockfile:t.lockfile??null,...t.error?{error:t.error}:{},vulnerabilities:t.vulnerabilities,summary:t.summary,timestamp:new Date().toISOString()},{namespace:"security-compliance",ttl:86400*7})}};function jx(c,t){let e=c.length>0?c:[...new Set(t.map(i=>i.reason))];return`Dependency advisories could not be checked for ${t.length>0?`${t.length} package(s)`:"some dependencies"}: ${e.slice(0,3).join("; ")}`}k();var dt=class{config;memory;llmRouter;activeScans=new Map;sastScanner;dastScanner;dependencyScanner;constructor(t,e={}){this.config={...xo,...e},"memory"in t?(this.memory=t.memory,this.llmRouter=t.llmRouter):this.memory=t,this.sastScanner=new Ei(this.config,this.memory,this.llmRouter,this.activeScans),this.dastScanner=new Ai(this.config,this.memory,this.activeScans),this.dependencyScanner=new Ii(this.config,this.memory,this.activeScans)}async scanFiles(t){return this.sastScanner.scanFiles(t)}async scanWithRules(t,e){return this.sastScanner.scanWithRules(t,e)}async getAvailableRuleSets(){return this.sastScanner.getAvailableRuleSets()}async checkFalsePositive(t){return this.sastScanner.checkFalsePositive(t)}async scanUrl(t,e){return this.dastScanner.scanUrl(t,e)}async scanAuthenticated(t,e,r){return this.dastScanner.scanAuthenticated(t,e,r)}async getScanStatus(t){return this.activeScans.get(t)??"pending"}async scanDependencies(t){return this.dependencyScanner.scanDependencies(t)}async scanPackageJson(t){return this.dependencyScanner.scanPackageJson(t)}async runFullScan(t,e,r){try{let i=await this.scanWithRules(t,this.config.defaultRuleSets);if(i.success===!1)return g(i.error);let n;if(e){let a=await this.scanUrl(e,r);if(a.success)n=a.value;else return g(a.error)}let s=this.combineSummaries(i.value.summary,n?.summary);return f({sastResult:i.value,dastResult:n,combinedSummary:s})}catch(i){return g(y(i))}}isLLMAnalysisAvailable(){return this.sastScanner.isLLMAnalysisAvailable()}getModelForTier(t){return this.sastScanner.getModelForTier(t)}async analyzeVulnerabilityWithLLM(t,e){return this.sastScanner.analyzeVulnerabilityWithLLM(t,e)}combineSummaries(t,e){return e?{critical:t.critical+e.critical,high:t.high+e.high,medium:t.medium+e.medium,low:t.low+e.low,informational:t.informational+e.informational,totalFiles:t.totalFiles+e.totalFiles,scanDurationMs:t.scanDurationMs+e.scanDurationMs}:t}};_();import*as Pv from"fs/promises";import*as ps from"path";k();X();async function ms(c){let t=await fetch(c,{method:"GET",headers:{Accept:"application/json"}}),e=await t.json();return{ok:t.ok,status:t.status,data:e}}var Ud={secretPatterns:[/(?:api[_-]?key|apikey)['":\s]*['"=]?\s*['"]?([a-zA-Z0-9_\-]{20,})['"]?/gi,/(?:password|passwd|pwd)['":\s]*['"=]?\s*['"]?([^\s'"]{8,})['"]?/gi,/(?:secret|token)['":\s]*['"=]?\s*['"]?([a-zA-Z0-9_\-]{16,})['"]?/gi,/(?:aws[_-]?access[_-]?key|aws[_-]?secret)['":\s]*['"=]?\s*['"]?([A-Z0-9]{20,})['"]?/gi,/-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/gi,/ghp_[a-zA-Z0-9]{36}/g,/gho_[a-zA-Z0-9]{36}/g,/sk-[a-zA-Z0-9]{48}/g],excludePatterns:["node_modules","dist","build",".git","*.test.*","*.spec.*"],maxFileSizeKb:1024,enableHistoricalAnalysis:!0,riskThreshold:.7};_();import*as vv from"path";var Hx=x.create("security-compliance/security-auditor-sast");function Wx(){return[{id:"sqli-concat",pattern:/(?:query|execute|exec|run)\s*\(\s*(?:['"`].*?\s*\+|`[^`]*\$\{)/gi,title:"SQL Injection via String Concatenation",description:"SQL query constructed using string concatenation with potentially untrusted input",severity:"critical",category:"injection",remediation:"Use parameterized queries or prepared statements",fixExample:'db.query("SELECT * FROM users WHERE id = $1", [userId])',cweId:"CWE-89"},{id:"xss-innerhtml",pattern:/\.innerHTML\s*=\s*(?!['"`])/g,title:"XSS via innerHTML Assignment",description:"Direct innerHTML assignment with potentially unsanitized content",severity:"high",category:"xss",remediation:"Use textContent for text, or sanitize HTML with DOMPurify",fixExample:"element.textContent = userInput;",cweId:"CWE-79"},{id:"xss-document-write",pattern:/document\.write\s*\([^)]+\)/g,title:"XSS via document.write",description:"document.write() can execute scripts from untrusted data",severity:"high",category:"xss",remediation:"Avoid document.write(); use DOM manipulation methods",cweId:"CWE-79"},{id:"xss-eval",pattern:/(?<!\.)\beval\s*\([^)]+\)/g,title:"Code Injection via eval()",description:"eval() executes arbitrary code and is a major security risk",severity:"critical",category:"xss",remediation:"Never use eval(); use JSON.parse() for JSON data",fixExample:"JSON.parse(jsonString)",cweId:"CWE-95"},{id:"xss-dangerous-react",pattern:/dangerouslySetInnerHTML\s*=\s*\{/g,title:"React dangerouslySetInnerHTML Usage",description:"dangerouslySetInnerHTML bypasses React XSS protections",severity:"medium",category:"xss",remediation:"Sanitize HTML content with DOMPurify before use",fixExample:"dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(content) }}",cweId:"CWE-79"},{id:"cmd-injection-exec",pattern:/(?:child_process\.)?exec\s*\(\s*(?:[^,)]*\s*\+|`[^`]*\$\{)/g,title:"Command Injection via exec()",description:"Shell command execution with unsanitized input",severity:"critical",category:"injection",remediation:"Use execFile() with argument array instead of exec()",fixExample:'execFile("command", [arg1, arg2], callback)',cweId:"CWE-78"},{id:"cmd-injection-spawn-shell",pattern:/spawn\s*\([^)]+,\s*\{[^}]*shell\s*:\s*true/g,title:"Dangerous Shell Option in spawn()",description:"spawn() with shell: true can enable command injection",severity:"high",category:"injection",remediation:"Avoid shell: true option; use direct command execution",cweId:"CWE-78"},{id:"path-traversal-readfile",pattern:/(?:readFile|readFileSync)\s*\([^)]*\+/g,title:"Path Traversal via File Read",description:"File read operation with concatenated path may allow directory traversal",severity:"high",category:"access-control",remediation:"Validate and sanitize file paths; use path.resolve() and check against base directory",fixExample:"const safePath = path.resolve(baseDir, path.basename(userInput))",cweId:"CWE-22"},{id:"path-traversal-writefile",pattern:/(?:writeFile|writeFileSync)\s*\([^)]*\+/g,title:"Path Traversal via File Write",description:"File write operation with concatenated path may allow directory traversal",severity:"high",category:"access-control",remediation:"Validate file paths before writing; ensure path is within allowed directory",cweId:"CWE-22"},{id:"secret-private-key",pattern:/-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/g,title:"Private Key Detected in Source",description:"Private key found in source code",severity:"critical",category:"sensitive-data",remediation:"Store private keys in secure key management systems, not in code",cweId:"CWE-798"},{id:"config-tls-disabled",pattern:/rejectUnauthorized\s*:\s*false/g,title:"TLS Certificate Validation Disabled",description:"Disabling TLS certificate validation exposes to MITM attacks",severity:"high",category:"security-misconfiguration",remediation:"Always enable TLS certificate validation in production",cweId:"CWE-295"},{id:"config-cors-wildcard",pattern:/cors\s*\(\s*\{[^}]*origin\s*:\s*['"]\*['"]/gi,title:"Permissive CORS Configuration",description:"CORS allows all origins (*) which may expose sensitive data",severity:"medium",category:"security-misconfiguration",remediation:"Restrict CORS to specific trusted origins",fixExample:'cors({ origin: ["https://trusted-domain.com"] })',cweId:"CWE-942"}]}async function bv(c,t){let e=w(),r=Date.now(),i=[],n=0,s=0;try{let p=await c(process.cwd()),h=Wx();for(let v of p){if(t(v))continue;let b=vv.extname(v).toLowerCase();if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(b))try{let C=await Re(v,{outsideRoot:"allow"}),S=C.split(`
2909
2909
  `);n++,s+=S.length;for(let R of h){R.pattern.lastIndex=0;let E;for(;(E=R.pattern.exec(C))!==null;){let I=C.substring(0,E.index).split(`
2910
2910
  `),O=I.length,q=I[I.length-1].length+1,j=S[O-1]||"";if(j.trimStart().startsWith("//")||j.trimStart().startsWith("*")||j.includes("// nosec")||j.includes("// security-ignore"))continue;let $=Math.max(0,O-2),ee=Math.min(S.length,O+1),Y=S.slice($,ee).join(`
2911
- `),Ic={file:v,line:O,column:q,snippet:Y},hb={description:R.remediation,fixExample:R.fixExample,estimatedEffort:R.severity==="critical"?"moderate":"minor",automatable:R.severity==="low"||R.severity==="medium"};i.push({id:w(),cveId:void 0,title:R.title,description:`${R.description} [${R.cweId}]`,severity:R.severity,category:R.category,location:Ic,remediation:hb,references:[`https://cwe.mitre.org/data/definitions/${R.cweId.replace("CWE-","")}.html`]})}}}catch{}}}catch(p){jx.error("SAST scan failed:",p instanceof Error?p:void 0)}let a=Date.now()-r,o=0,l=0,u=0,d=0,m=0;for(let p of i)switch(p.severity){case"critical":o++;break;case"high":l++;break;case"medium":u++;break;case"low":d++;break;case"informational":m++;break}return{scanId:e,vulnerabilities:i,summary:{critical:o,high:l,medium:u,low:d,informational:m,totalFiles:n,scanDurationMs:a},coverage:{filesScanned:n,linesScanned:s,rulesApplied:12}}}_();k();var Wx=x.create("security-compliance/security-auditor-dast");async function wv(c){let t=w(),e=Date.now(),r=[],i=0;try{let d;try{d=new URL(c)}catch{return{scanId:t,targetUrl:c,vulnerabilities:[{id:w(),title:"Invalid Target URL",description:"The provided target URL is not valid",severity:"informational",category:"security-misconfiguration",location:{file:c},remediation:{description:"Provide a valid URL",estimatedEffort:"trivial",automatable:!1},references:[]}],summary:{critical:0,high:0,medium:0,low:0,informational:1,totalFiles:0,scanDurationMs:Date.now()-e},crawledUrls:0}}let m=new AbortController,p=setTimeout(()=>m.abort(),3e4);try{let h=await fetch(c,{method:"GET",headers:{"User-Agent":"AgenticQE-SecurityScanner/3.0",Accept:"text/html,application/json,*/*"},signal:m.signal,redirect:"follow"});clearTimeout(p),i=1;let v=h.headers,b=[{header:"strict-transport-security",title:"Missing HTTP Strict Transport Security (HSTS)",description:"HSTS header is missing, allowing downgrade attacks",severity:"medium",remediation:"Add Strict-Transport-Security header with appropriate max-age"},{header:"x-content-type-options",title:"Missing X-Content-Type-Options Header",description:"X-Content-Type-Options header is missing, allowing MIME sniffing attacks",severity:"low",remediation:"Add X-Content-Type-Options: nosniff header"},{header:"x-frame-options",title:"Missing X-Frame-Options Header",description:"X-Frame-Options header is missing, allowing clickjacking attacks",severity:"medium",remediation:"Add X-Frame-Options: DENY or SAMEORIGIN header"},{header:"content-security-policy",title:"Missing Content Security Policy",description:"CSP header is missing, increasing XSS attack surface",severity:"medium",remediation:"Implement a Content-Security-Policy header"},{header:"x-xss-protection",title:"Missing X-XSS-Protection Header",description:"X-XSS-Protection header is missing (legacy XSS filter)",severity:"low",remediation:"Add X-XSS-Protection: 1; mode=block header"}];for(let E of b)v.get(E.header)||r.push({id:w(),title:E.title,description:E.description,severity:E.severity,category:"security-misconfiguration",location:{file:c,snippet:`Response Headers: ${E.header} not present`},remediation:{description:E.remediation,estimatedEffort:"minor",automatable:!0},references:["https://owasp.org/www-project-secure-headers/"]});let C=v.get("set-cookie");C&&(C.toLowerCase().includes("secure")||r.push({id:w(),title:"Cookie Without Secure Flag",description:"Session cookie is set without the Secure flag",severity:"medium",category:"sensitive-data",location:{file:c,snippet:`Set-Cookie: ${C.substring(0,50)}...`},remediation:{description:"Add Secure flag to cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/controls/SecureCookieAttribute"]}),C.toLowerCase().includes("httponly")||r.push({id:w(),title:"Cookie Without HttpOnly Flag",description:"Session cookie is set without the HttpOnly flag, making it accessible to JavaScript",severity:"medium",category:"sensitive-data",location:{file:c,snippet:`Set-Cookie: ${C.substring(0,50)}...`},remediation:{description:"Add HttpOnly flag to session cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/HttpOnly"]}),C.toLowerCase().includes("samesite")||r.push({id:w(),title:"Cookie Without SameSite Attribute",description:"Cookie is set without the SameSite attribute, potentially vulnerable to CSRF",severity:"low",category:"broken-auth",location:{file:c,snippet:`Set-Cookie: ${C.substring(0,50)}...`},remediation:{description:"Add SameSite=Strict or SameSite=Lax to cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/SameSite"]}));let S=v.get("server");S&&/[0-9]+\.[0-9]+/.test(S)&&r.push({id:w(),title:"Server Version Disclosure",description:`Server header reveals version information: ${S}`,severity:"low",category:"security-misconfiguration",location:{file:c,snippet:`Server: ${S}`},remediation:{description:"Remove or obfuscate server version information",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]}),d.protocol==="http:"&&r.push({id:w(),title:"Insecure HTTP Protocol",description:"Target is using HTTP instead of HTTPS, exposing data in transit",severity:"high",category:"sensitive-data",location:{file:c},remediation:{description:"Use HTTPS with valid TLS certificate",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]});let R=[{path:"/.git/config",vuln:"Git Repository Exposed",severity:"high"},{path:"/.env",vuln:"Environment File Exposed",severity:"critical"},{path:"/phpinfo.php",vuln:"PHP Info Exposed",severity:"medium"},{path:"/wp-config.php.bak",vuln:"WordPress Config Backup Exposed",severity:"critical"}];for(let E of R)try{let T=new URL(E.path,d.origin).toString(),I=await fetch(T,{method:"GET",signal:AbortSignal.timeout(5e3)});if(I.ok&&I.status===200){let O=await I.text();O.length>10&&!O.toLowerCase().includes("not found")&&(i++,r.push({id:w(),title:E.vuln,description:`Sensitive file found at ${E.path}`,severity:E.severity,category:"sensitive-data",location:{file:T},remediation:{description:"Remove or restrict access to sensitive files",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]}))}}catch{}}catch(h){clearTimeout(p);let v=P(h);(v.includes("certificate")||v.includes("SSL")||v.includes("TLS"))&&r.push({id:w(),title:"TLS/SSL Certificate Issue",description:`Certificate error: ${v}`,severity:"high",category:"security-misconfiguration",location:{file:c},remediation:{description:"Fix TLS certificate configuration",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]})}}catch(d){Wx.error("DAST scan failed:",d instanceof Error?d:void 0)}let n=Date.now()-e,s=0,a=0,o=0,l=0,u=0;for(let d of r)switch(d.severity){case"critical":s++;break;case"high":a++;break;case"medium":o++;break;case"low":l++;break;case"informational":u++;break}return{scanId:t,targetUrl:c,vulnerabilities:r,summary:{critical:s,high:a,medium:o,low:l,informational:u,totalFiles:1,scanDurationMs:n},crawledUrls:i}}_();var Ux=x.create("security-compliance/security-auditor-secrets");function Qx(){return[{name:"AWS Access Key ID",type:"api-key",regex:/AKIA[0-9A-Z]{16}/g},{name:"AWS Secret Access Key",type:"api-key",regex:/(?:aws[_-]?secret[_-]?access[_-]?key|AWS_SECRET_ACCESS_KEY)['"]?\s*[:=]\s*['"]?([A-Za-z0-9/+=]{40})['"]?/gi,entropyThreshold:4},{name:"GitHub Personal Access Token",type:"token",regex:/ghp_[A-Za-z0-9]{36}/g},{name:"GitHub OAuth Access Token",type:"token",regex:/gho_[A-Za-z0-9]{36}/g},{name:"GitHub App Token",type:"token",regex:/(?:ghu|ghs)_[A-Za-z0-9]{36}/g},{name:"Generic API Key",type:"api-key",regex:/(?:api[_-]?key|apikey|api_secret)['"]?\s*[:=]\s*['"]([A-Za-z0-9_\-]{20,})['"]?/gi,entropyThreshold:3.5},{name:"OpenAI API Key",type:"api-key",regex:/sk-[A-Za-z0-9]{48}/g},{name:"Stripe Secret Key",type:"api-key",regex:/sk_live_[A-Za-z0-9]{24,}/g},{name:"Stripe Publishable Key",type:"api-key",regex:/pk_live_[A-Za-z0-9]{24,}/g},{name:"RSA Private Key",type:"private-key",regex:/-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/gi},{name:"PGP Private Key",type:"private-key",regex:/-----BEGIN\s+PGP\s+PRIVATE\s+KEY\s+BLOCK-----/gi},{name:"SSH Private Key",type:"private-key",regex:/-----BEGIN\s+(?:OPENSSH|DSA|EC)?\s*PRIVATE\s+KEY-----/gi},{name:"Password Assignment",type:"password",regex:/(?:password|passwd|pwd|secret)['"]?\s*[:=]\s*['"]([^'"\s]{8,})['"]?/gi,entropyThreshold:3},{name:"Database Connection String",type:"password",regex:/(?:mongodb|postgres|mysql|redis):\/\/[^:]+:[^@]+@[^\s'"]+/gi},{name:"JWT Token",type:"token",regex:/eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*/g,entropyThreshold:4},{name:"Slack Token",type:"token",regex:/xox[baprs]-[A-Za-z0-9-]{10,}/g},{name:"Google API Key",type:"api-key",regex:/AIza[A-Za-z0-9_-]{35}/g},{name:"Twilio API Key",type:"api-key",regex:/SK[A-Za-z0-9]{32}/g},{name:"SendGrid API Key",type:"api-key",regex:/SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}/g},{name:"X.509 Certificate",type:"certificate",regex:/-----BEGIN\s+CERTIFICATE-----/gi}]}function Kx(c){if(!c||c.length===0)return 0;let t={};for(let i of c)t[i]=(t[i]||0)+1;let e=0,r=c.length;for(let i in t){let n=t[i]/r;e-=n*Math.log2(n)}return e}function Jx(c,t,e){let n=Math.max(0,t-20),s=Math.min(c.length,t+e+10),a=c.substring(n,s),o=t-n,l=a.substring(o,o+e);if(l.length>8){let u=l.substring(0,4)+"..."+l.substring(l.length-4);a=a.substring(0,o)+u+a.substring(o+e)}return n>0&&(a="..."+a),s<c.length&&(a=a+"..."),a}function Yx(c,t){switch(c){case"api-key":return t.length>=20&&/[a-z]/.test(t)&&/[A-Z0-9]/.test(t);case"token":return t.length>=20;case"password":return!["password","secret","changeme","12345678","qwerty"].includes(t.toLowerCase());case"private-key":return!0;case"certificate":return!0;default:return!0}}async function Qd(c){let t=[];try{let r=(await Re(c.value,{outsideRoot:"allow"})).split(`
2912
- `),i=Qx();for(let n=0;n<r.length;n++){let s=r[n],a=n+1;for(let o of i){o.regex.lastIndex=0;let l;for(;(l=o.regex.exec(s))!==null;){let u=l[1]||l[0],d=Kx(u);if(o.entropyThreshold&&d<o.entropyThreshold)continue;let m=Jx(s,l.index,u.length),p={file:c.value,line:a,column:l.index+1,snippet:m};t.push({type:o.type,location:p,entropy:d,isValid:Yx(o.type,u)})}}}}catch(e){Ux.error(`Failed to scan file for secrets: ${c.value}`,e instanceof Error?e:void 0)}return t}function Cv(c,t,e,r){let i=0,n=0;if(c&&(i+=Kd(c.summary)*.35,n+=.35),t&&(i+=Kd(t.summary)*.25,n+=.25),e&&(i+=Kd(e.summary)*.25,n+=.25),r){let a=r.secretsFound.length>0?.9:.1;i+=a*.15,n+=.15}let s=n>0?i/n:0;return{value:Math.min(1,s),percentage:s*100,level:s>=.8?"critical":s>=.6?"high":s>=.3?"medium":"low"}}function Kd(c){let t={critical:1,high:.7,medium:.4,low:.1,informational:.02};if(c.critical+c.high+c.medium+c.low+c.informational===0)return 0;let r=c.critical*t.critical+c.high*t.high+c.medium*t.medium+c.low*t.low+c.informational*t.informational;return Math.min(1,r/10)}function Sv(c,t,e,r){let i=[];return c&&c.summary.critical>0&&i.push(`Address ${c.summary.critical} critical vulnerabilities found in static analysis`),t&&t.summary.high>0&&i.push(`Fix ${t.summary.high} high-severity issues found in dynamic testing`),e&&e.outdatedPackages.length>5&&i.push(`Update ${e.outdatedPackages.length} outdated dependencies`),r&&r.secretsFound.length>0&&i.push(`Remove ${r.secretsFound.length} exposed secrets and rotate credentials`),i.length===0&&i.push("Security posture is good. Continue regular scanning."),i}function Jd(c,t){if(!c)return 0;let e=0;return c.sastResults&&(e+=c.sastResults.summary[t]),c.dastResults&&(e+=c.dastResults.summary[t]),c.dependencyResults&&(e+=c.dependencyResults.summary[t]),e}function Mi(c){if(!c)return 0;let t=0;return c.sastResults&&(t+=c.sastResults.vulnerabilities.length),c.dastResults&&(t+=c.dastResults.vulnerabilities.length),c.dependencyResults&&(t+=c.dependencyResults.vulnerabilities.length),t}function Rv(c,t){if(!c||!t)return"stable";let e=Mi(c),r=Mi(t);return e<r*.9?"improving":e>r*1.1?"declining":"stable"}function Tv(c,t,e){let r=100;return r-=c*20,r-=t*10,r-=e*2,Math.max(0,Math.min(100,r))}function Ev(c,t,e){let r=[];return c>0&&r.push("Immediately address all critical vulnerabilities"),t>3&&r.push("Prioritize fixing high-severity issues"),e<50&&(r.push("Consider a comprehensive security review"),r.push("Implement automated security scanning in CI/CD")),e>=80&&(r.push("Maintain current security practices"),r.push("Consider penetration testing for deeper analysis")),r}function Av(c){let t=c.remediation.estimatedEffort;return c.severity==="critical"?"immediate":c.severity==="high"?t==="trivial"||t==="minor"?"immediate":"shortTerm":c.severity==="medium"?t==="major"?"longTerm":"mediumTerm":c.severity==="low"||c.severity==="informational"?"longTerm":"accepted"}var Dt=x.create("security-compliance/security-auditor"),xv="(dependency plan)",_r=class{constructor(t,e={},r){this.memory=t;this.config={...Ud,...e},this.osvClient=r??new Nr}memory;config;osvClient;async scanDependencies(t){try{let e=t.value,r=this.detectEcosystem(e);if(!r)return g(new Error(`Unknown manifest format: ${e}`));let i=[],{dependencies:n,preUnchecked:s}=await this.parseDependenciesForScan(e,r),a=await this.checkDependencyAdvisories(n,s);for(let u of n){let d=await this.checkOutdated(u);d&&i.push(d)}let o=this.createDependencySummary(a.vulnerabilities,n.length),l=this.toDependencyScanResult(a,i,o);return await this.memory.set(`security:deps:${t.filename}`,l,{namespace:"security-compliance",ttl:86400}),f(l)}catch(e){return g(y(e))}}async checkPackage(t,e,r){try{let i=await this.queryVulnerabilityDatabase(t,e,r),n=await this.getLatestVersion(t,r),s=await this.checkDeprecation(t,r);return f({name:t,version:e,vulnerabilities:i,latestVersion:n,isDeprecated:s})}catch(i){return g(y(i))}}async getUpgradeRecommendations(t){try{let e=[],r=new Map;for(let i of t){let n=i.location.dependency;if(n){let s=`${n.ecosystem}:${n.name}`,a=r.get(s)||[];a.push(i),r.set(s,a)}}for(let[i,n]of r){let[s,a]=i.split(":"),o=n[0].location.dependency?.version||"unknown",l=await this.getLatestVersion(a,s),u=n.filter(d=>d.id).map(d=>d.id);e.push({package:a,fromVersion:o,toVersion:l,fixesVulnerabilities:u,breakingChanges:this.hasBreakingChanges(o,l)})}return e.sort((i,n)=>n.fixesVulnerabilities.length-i.fixesVulnerabilities.length),f(e)}catch(e){return g(y(e))}}async runAudit(t){let e=w(),r=new Date;try{let i,n,s,a;t.includeSAST&&(i=await bv(d=>this.findSourceFiles(d),d=>this.shouldExclude(d))),t.includeDAST&&t.targetUrl&&(n=await wv(t.targetUrl)),t.includeDependencies&&(s=await this.performDependencyScan()),t.includeSecrets&&(a=await this.performSecretScan());let o=Cv(i,n,s,a),l=Sv(i,n,s,a);s&&s.status!=="complete"&&l.unshift(`${s.error??"Dependency advisories could not be checked"}. Dependency risk is unmeasured; re-run the scan when the OSV API is reachable.`);let u={auditId:e,timestamp:r,sastResults:i,dastResults:n,dependencyResults:s,secretScanResults:a,overallRiskScore:o,recommendations:l};return await this.memory.set(`security:audit:${e}`,u,{namespace:"security-compliance",persist:!0}),f(u)}catch(i){return g(y(i))}}async scanSecrets(t){try{let e=[],r=0;for(let i of t){if(this.shouldExclude(i.value))continue;r++;let n=await Qd(i);e.push(...n)}return f({secretsFound:e,filesScanned:r})}catch(e){return g(y(e))}}async getSecurityPosture(){try{let t=await this.getRecentAudits(),e=t[0],r=t[1],i=Jd(e,"critical"),n=Jd(e,"high"),s=Mi(e),a=Rv(e,r),o=Tv(i,n,s),l=Ev(i,n,o);return f({overallScore:o,trend:a,criticalIssues:i,highIssues:n,openVulnerabilities:s,resolvedLastWeek:await this.countResolvedLastWeek(),averageResolutionTime:await this.calculateAverageResolutionTime(),lastAuditDate:e?.timestamp??new Date,recommendations:l})}catch(t){return g(y(t))}}async triageVulnerabilities(t){try{let e={immediate:[],shortTerm:[],mediumTerm:[],longTerm:[],accepted:[]};for(let i of t){let n=Av(i);e[n].push(i)}let r=["critical","high","medium","low","informational"];for(let i of Object.values(e))i.sort((n,s)=>r.indexOf(n.severity)-r.indexOf(s.severity));return f(e)}catch(e){return g(y(e))}}detectEcosystem(t){return t.includes("package.json")?"npm":t.includes("requirements.txt")||t.includes("Pipfile")?"pip":t.includes("pom.xml")||t.includes("build.gradle")?"maven":t.includes("Cargo.toml")?"cargo":t.includes(".csproj")||t.includes("packages.config")?"nuget":null}async parseDependencies(t,e){let r=[];try{if(e==="npm"){let i=await Re(t,{outsideRoot:"allow"}),n=D(i),s={...n.dependencies,...n.devDependencies,...n.peerDependencies,...n.optionalDependencies};for(let[a,o]of Object.entries(s))r.push({name:a,version:o,ecosystem:"npm"})}else if(e==="pip"){let n=(await Re(t,{outsideRoot:"allow"})).split(`
2913
- `);for(let s of n){let a=s.trim();if(!a||a.startsWith("#"))continue;let o=a.match(/^([a-zA-Z0-9_.-]+)\s*(===?|>=|<=|~=|!=|>|<)?\s*([^\s;#]+)?/);if(o){let[,l,u,d]=o;r.push({name:l,version:d&&(u==="=="||u==="===")?d:u&&d?`${u}${d}`:"*",ecosystem:"pip"})}}}}catch(i){throw Dt.error(`Failed to parse dependencies from ${t}:`,i instanceof Error?i:void 0),i}return r}async parseDependenciesForScan(t,e){if(e!=="npm")return{dependencies:await this.parseDependencies(t,e),preUnchecked:[]};let r;try{r=await uc(t)}catch(s){throw Dt.error(`Failed to parse dependencies from ${t}:`,s instanceof Error?s:void 0),s}let i=[],n=[];for(let s of r.dependencies)s.kind==="check"?i.push({name:s.packageName,version:s.version,ecosystem:"npm"}):s.kind==="unchecked"&&n.push({name:s.name,version:s.spec,reason:s.reason??"not checked",...s.member?{member:s.member}:{},...s.lockedVersion?{lockedVersion:s.lockedVersion}:{}});for(let s of[...r.error?[r.error]:[],...r.memberErrors])n.push({name:xv,version:"*",reason:s});return{dependencies:i,preUnchecked:n}}async checkDependencyAdvisories(t,e=[]){let r=await this.osvClient.lookupBatch(t.map(u=>({name:u.name,ecosystem:this.mapToOSVEcosystem(u.ecosystem),version:u.version}))),i=[];for(let u of t){let d=r.results.get(nr({ecosystem:this.mapToOSVEcosystem(u.ecosystem),name:u.name,version:u.version}))??[];i.push(...d.map(m=>this.mapParsedVulnerability(m,u)))}let n=[...e,...r.unchecked.map(u=>({name:u.name,version:u.version??"unknown",reason:u.reason}))],s=r.errors.length>0?r.errors:[...new Set(n.map(u=>u.reason))],a=r.packagesChecked+n.length,o=a-n.filter(u=>u.name===xv).length,l=r.packagesChecked===a?"complete":r.packagesChecked===0&&o>0?"failed":"incomplete";return{vulnerabilities:i,status:l,packagesChecked:r.packagesChecked,uncheckedPackages:n,...l==="complete"?{}:{error:`Dependency advisories could not be checked for ${n.length} package(s): ${s.slice(0,3).join("; ")}`}}}toDependencyScanResult(t,e,r){return{vulnerabilities:t.vulnerabilities,outdatedPackages:e,summary:r,status:t.status,measured:t.status==="complete",packagesChecked:t.packagesChecked,uncheckedPackages:t.uncheckedPackages,...t.error?{error:t.error}:{}}}mapToOSVEcosystem(t){return{npm:"npm",pip:"PyPI",maven:"Maven",nuget:"NuGet",cargo:"crates.io"}[t]}mapParsedVulnerability(t,e){let r=t.fixedVersions[0],i={file:e.ecosystem==="pip"?"requirements.txt":"package.json",dependency:e},n={description:r?`Upgrade ${e.name} to version ${r} or higher`:`Review and address vulnerability in ${e.name}`,fixExample:r?`"${e.name}": "^${r}"`:void 0,estimatedEffort:r?"trivial":"moderate",automatable:!!r};return{id:w(),cveId:t.cveIds[0],title:t.summary||`Vulnerability in ${e.name}`,description:t.details||t.summary||"No description available",severity:t.severity==="unknown"?"medium":t.severity,category:this.categorizeVulnerability({summary:t.summary,details:t.details}),location:i,remediation:n,references:t.references}}categorizeVulnerability(t){let e=(t.summary||"").toLowerCase(),r=(t.details||"").toLowerCase(),i=`${e} ${r}`;return i.includes("injection")||i.includes("sql")?"injection":i.includes("xss")||i.includes("cross-site scripting")?"xss":i.includes("authentication")||i.includes("auth bypass")?"broken-auth":i.includes("sensitive data")||i.includes("exposure")?"sensitive-data":i.includes("xxe")||i.includes("xml external")?"xxe":i.includes("access control")||i.includes("authorization")?"access-control":i.includes("deseriali")?"insecure-deserialization":(i.includes("prototype pollution")||i.includes("dependency"),"vulnerable-components")}async checkOutdated(t){let e=await this.getLatestVersion(t.name,t.ecosystem);return e!=="unknown"&&e!==t.version?{name:t.name,currentVersion:t.version,latestVersion:e,updateType:this.determineUpdateType(t.version,e)}:null}async queryVulnerabilityDatabase(t,e,r){let i=await this.checkDependencyAdvisories([{name:t,version:e,ecosystem:r}]);if(i.status!=="complete")throw new Error(i.error??`Dependency advisories could not be checked for ${t}@${e}`);return i.vulnerabilities}async getLatestVersion(t,e){try{if(e==="npm"){let r=await ms(`https://registry.npmjs.org/${encodeURIComponent(t)}/latest`);if(r.ok&&r.data.version)return r.data.version}else if(e==="pip"){let r=await ms(`https://pypi.org/pypi/${encodeURIComponent(t)}/json`);if(r.ok&&r.data.info?.version)return r.data.info.version}}catch(r){Dt.error(`Failed to get latest version for ${t}:`,r instanceof Error?r:void 0)}return"unknown"}async checkDeprecation(t,e){try{if(e==="npm"){let r=await ms(`https://registry.npmjs.org/${encodeURIComponent(t)}/latest`);if(r.ok&&r.data.deprecated)return!0}}catch(r){Dt.error(`Failed to check deprecation for ${t}:`,r instanceof Error?r:void 0)}return!1}determineUpdateType(t,e){let r=t.split(".").map(Number),i=e.split(".").map(Number);return i[0]>r[0]?"major":i[1]>r[1]?"minor":"patch"}hasBreakingChanges(t,e){let r=parseInt(t.split(".")[0]);return parseInt(e.split(".")[0])>r}createDependencySummary(t,e){let r=0,i=0,n=0,s=0,a=0;for(let o of t)switch(o.severity){case"critical":r++;break;case"high":i++;break;case"medium":n++;break;case"low":s++;break;case"informational":a++;break}return{critical:r,high:i,medium:n,low:s,informational:a,totalFiles:e,scanDurationMs:0}}shouldExclude(t){return this.config.excludePatterns.some(e=>e.startsWith("*")?t.endsWith(e.slice(1)):t.includes(e))}async performDependencyScan(){let t=Date.now(),e=[],r=ps.join(process.cwd(),"package.json");try{let{dependencies:i,preUnchecked:n}=await this.parseDependenciesForScan(r,"npm"),s=await this.checkDependencyAdvisories(i,n);for(let o of i){let l=await this.checkOutdated(o);l&&e.push(l)}let a=this.createDependencySummary(s.vulnerabilities,i.length);return this.toDependencyScanResult(s,e,{...a,scanDurationMs:Date.now()-t})}catch(i){return Dt.error("Dependency scan failed:",i instanceof Error?i:void 0),{vulnerabilities:[],outdatedPackages:[],summary:{critical:0,high:0,medium:0,low:0,informational:0,totalFiles:0,scanDurationMs:Date.now()-t},status:"failed",measured:!1,packagesChecked:0,uncheckedPackages:[],error:`Dependency scan of ${r} failed: ${y(i).message}`}}}async performSecretScan(){let t=[],e=0;try{let r=await this.findSourceFiles(process.cwd());for(let i of r){if(this.shouldExclude(i))continue;e++;let s=await Qd({value:i});t.push(...s)}}catch(r){Dt.error("Secret scan failed:",r instanceof Error?r:void 0)}return{secretsFound:t,filesScanned:e}}async findSourceFiles(t,e=[]){let r=[".ts",".js",".tsx",".jsx",".json",".env",".yaml",".yml",".config"];try{let i=await Pv.readdir(t,{withFileTypes:!0});for(let n of i){let s=ps.join(t,n.name);if(!this.shouldExclude(s)){if(n.isDirectory())await this.findSourceFiles(s,e);else if(n.isFile()){let a=ps.extname(n.name).toLowerCase();(r.includes(a)||n.name.startsWith(".env"))&&e.push(s)}}}}catch{Dt.debug("Directory read error:")}return e}async getRecentAudits(){let t=await this.memory.search("security:audit:*",10),e=[];for(let r of t){let i=await this.memory.get(r);i&&e.push(i)}return e.sort((r,i)=>new Date(i.timestamp).getTime()-new Date(r.timestamp).getTime())}async countResolvedLastWeek(){try{let t=await this.getRecentAudits();if(t.length<2)return 0;let e=new Date(Date.now()-10080*60*1e3),r=t.filter(o=>new Date(o.timestamp)>=e);if(r.length<2)return 0;let i=r[r.length-1],n=r[0],s=Mi(i),a=Mi(n);return Math.max(0,s-a)}catch(t){return Dt.error("Failed to count resolved vulnerabilities:",t instanceof Error?t:void 0),0}}async calculateAverageResolutionTime(){try{let t=await this.getRecentAudits();if(t.length<2)return 72;let e=new Map,r=[],i=[...t].reverse();for(let s of i){let a=new Set;s.sastResults&&s.sastResults.vulnerabilities.forEach(o=>a.add(o.id)),s.dastResults&&s.dastResults.vulnerabilities.forEach(o=>a.add(o.id)),s.dependencyResults&&s.dependencyResults.vulnerabilities.forEach(o=>a.add(o.id));for(let o of a)e.has(o)||e.set(o,s.timestamp);for(let[o,l]of e)if(!a.has(o)){let u=(s.timestamp.getTime()-l.getTime())/36e5;r.push(u),e.delete(o)}}if(r.length===0)return 72;let n=r.reduce((s,a)=>s+a,0);return Math.round(n/r.length)}catch(t){return Dt.error("Failed to calculate average resolution time:",t instanceof Error?t:void 0),72}}};k();var Xx={customStandards:[],strictMode:!1,includeRecommended:!0,evidenceRetentionDays:365},Zx={id:"gdpr",name:"General Data Protection Regulation",version:"2018",rules:[{id:"gdpr-art5-accuracy",title:"Data Accuracy",description:"Personal data must be accurate and kept up to date",category:"data-quality",severity:"required",checkType:"manual"},{id:"gdpr-art17-erasure",title:"Right to Erasure",description:"Data subjects have the right to request deletion of their data",category:"data-rights",severity:"required",checkType:"static"},{id:"gdpr-art25-privacy-design",title:"Privacy by Design",description:"Data protection must be built into systems from the start",category:"architecture",severity:"required",checkType:"static"},{id:"gdpr-art32-security",title:"Security of Processing",description:"Appropriate security measures must protect personal data",category:"security",severity:"required",checkType:"static"},{id:"gdpr-art33-breach-notification",title:"Breach Notification",description:"Data breaches must be reported within 72 hours",category:"incident-response",severity:"required",checkType:"manual"}]},eP={id:"hipaa",name:"Health Insurance Portability and Accountability Act",version:"1996-amended",rules:[{id:"hipaa-164.312-access",title:"Access Control",description:"Implement technical policies for ePHI access",category:"access-control",severity:"required",checkType:"static"},{id:"hipaa-164.312-audit",title:"Audit Controls",description:"Implement hardware, software, and procedural audit mechanisms",category:"audit",severity:"required",checkType:"static"},{id:"hipaa-164.312-integrity",title:"Integrity Controls",description:"Protect ePHI from improper alteration or destruction",category:"data-integrity",severity:"required",checkType:"static"},{id:"hipaa-164.312-transmission",title:"Transmission Security",description:"Protect ePHI during electronic transmission",category:"encryption",severity:"required",checkType:"static"},{id:"hipaa-164.314-baa",title:"Business Associate Agreements",description:"Ensure contracts with business associates protect PHI",category:"contracts",severity:"required",checkType:"manual"}]},tP={id:"soc2",name:"SOC 2 Type II",version:"2017",rules:[{id:"soc2-cc6.1",title:"Logical Access Security",description:"Security software, infrastructure, and architectures are implemented",category:"security",severity:"required",checkType:"static"},{id:"soc2-cc6.2",title:"Access Controls",description:"Registration and authorization of new users",category:"access-control",severity:"required",checkType:"static"},{id:"soc2-cc6.6",title:"Encryption",description:"Logical access security measures to protect data",category:"encryption",severity:"required",checkType:"static"},{id:"soc2-cc7.1",title:"System Monitoring",description:"Detect and respond to security incidents",category:"monitoring",severity:"required",checkType:"static"},{id:"soc2-cc8.1",title:"Change Management",description:"Changes to infrastructure are authorized and tested",category:"change-management",severity:"required",checkType:"manual"}]},rP={id:"pci-dss",name:"Payment Card Industry Data Security Standard",version:"4.0",rules:[{id:"pci-req1",title:"Network Security Controls",description:"Install and maintain network security controls",category:"network-security",severity:"required",checkType:"static"},{id:"pci-req3",title:"Protect Account Data",description:"Protect stored account data",category:"data-protection",severity:"required",checkType:"static"},{id:"pci-req4",title:"Encrypt Transmissions",description:"Protect cardholder data with strong cryptography during transmission",category:"encryption",severity:"required",checkType:"static"},{id:"pci-req6",title:"Secure Development",description:"Develop and maintain secure systems and software",category:"secure-sdlc",severity:"required",checkType:"static"},{id:"pci-req10",title:"Log and Monitor Access",description:"Log and monitor all access to system components",category:"logging",severity:"required",checkType:"static"}]},iP=[Zx,eP,tP,rP],Vr=class{constructor(t,e={}){this.memory=t;this.config={...Xx,...e},this.patternAnalyzer=Td(),this.standards=new Map;for(let r of iP)this.standards.set(r.id,r);for(let r of this.config.customStandards)this.standards.set(r.id,r)}memory;config;standards;patternAnalyzer;async validate(t,e){try{let r=[],i=[],n=[],s=this.config.includeRecommended?t.rules:t.rules.filter(u=>u.severity==="required");for(let u of s){if(u.checkType==="manual"){n.push(u.id);continue}let d=await this.checkRule(u,e);d.passed?i.push(u.id):r.push(...d.violations)}let a=s.length-n.length,o=a>0?Math.round(i.length/a*100):100,l={standardId:t.id,standardName:t.name,violations:r,passedRules:i,skippedRules:n,complianceScore:o,generatedAt:new Date};return await this.storeReport(l),f(l)}catch(r){return g(y(r))}}async getAvailableStandards(){return Array.from(this.standards.values())}async analyzeGaps(t,e){try{let r=[],i=[],n=new Set(t.violations.map(u=>u.ruleId)),s=new Set(t.passedRules);for(let u of e.rules)n.has(u.id)?r.push({ruleId:u.id,currentStatus:"failed",effort:this.estimateEffort(u),impact:u.severity==="required"?"high":"medium"}):s.has(u.id)||r.push({ruleId:u.id,currentStatus:"not-implemented",effort:this.estimateEffort(u),impact:u.severity==="required"?"high":"low"});let a=[...r].sort((u,d)=>{let m={high:0,medium:1,low:2},p={trivial:0,minor:1,moderate:2,major:3},h=m[u.impact]*10+p[u.effort],v=m[d.impact]*10+p[d.effort];return h-v});for(let u=0;u<a.length;u++){let d=a[u],m=e.rules.find(p=>p.id===d.ruleId);i.push({id:w(),description:`Implement ${m?.title||d.ruleId}`,affectedRules:[d.ruleId],effort:d.effort,priority:u+1})}let o=100,l=t.complianceScore;return f({currentScore:l,targetScore:o,gaps:r,prioritizedActions:i})}catch(r){return g(y(r))}}async validateMultiple(t,e){try{let r=[],i=[];for(let a of t){let o=await this.validate(a,e);o.success&&r.push(o.value)}let n=new Map;for(let a of r)for(let o of a.violations){let l=`${o.location.file}:${o.location.line}`;n.set(l,(n.get(l)||0)+1)}for(let a of r)for(let o of a.violations){let l=`${o.location.file}:${o.location.line}`;(n.get(l)||0)>1&&(i.some(u=>u.location.file===o.location.file&&u.location.line===o.location.line)||i.push(o))}let s=r.length>0?Math.round(r.reduce((a,o)=>a+o.complianceScore,0)/r.length):0;return f({reports:r,overallScore:s,crossCuttingViolations:i})}catch(r){return g(y(r))}}async checkDataHandling(t,e){try{let r=new Map,i=[],n=[];for(let s of e)r.set(s,[]);for(let s of t){let a=await this.scanFileForDataTypes(s,e);for(let o of a){let l=r.get(o.type)||[];l.push(o.location),r.set(o.type,l);let u=this.checkDataTypeViolation(o);u&&i.push(u)}}for(let[s,a]of r)a.length>0&&n.push(...this.getDataTypeRecommendations(s,a.length));return f({dataTypesFound:r,violations:i,recommendations:[...new Set(n)]})}catch(r){return g(y(r))}}async generateEvidence(t,e){try{let r=this.standards.get(t);if(!r)return g(new Error(`Unknown standard: ${t}`));let i=await this.validate(r,e);if(!i.success)return g(i.error);let n=i.value,s=[];for(let o of r.rules){let l=n.passedRules.includes(o.id)?"implemented":n.skippedRules.includes(o.id)?"partial":"not-implemented";s.push({controlId:o.id,status:l,evidence:await this.collectEvidence(o,e),lastVerified:new Date})}let a={standardId:t,controls:s,generatedAt:new Date,validUntil:new Date(Date.now()+this.config.evidenceRetentionDays*24*60*60*1e3)};return await this.memory.set(`compliance:evidence:${t}:${Date.now()}`,a,{namespace:"security-compliance",persist:!0}),f(a)}catch(r){return g(y(r))}}async checkRule(t,e){let r=[],i=await this.getFilesFromContext(e);switch(t.category){case"encryption":r.push(...await this.checkEncryption(t,e,i));break;case"access-control":r.push(...await this.checkAccessControl(t,e,i));break;case"audit":case"logging":r.push(...await this.checkLogging(t,e,i));break;case"data-protection":case"data-quality":r.push(...await this.checkDataProtection(t,e,i));break;case"security":r.push(...await this.checkSecurityControls(t,e,i));break;default:break}return{passed:r.length===0,violations:r}}async getFilesFromContext(t){let e=[],r=t.projectRoot.value;if(t.includePatterns.length===0)return[];for(let i of t.includePatterns)t.excludePatterns.some(s=>i.includes(s)||s.includes(i))||e.push(`${r}/${i}`);return e}async checkEncryption(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeEncryption(r);for(let s of n.weakCrypto)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Weak or deprecated cryptographic algorithm detected",remediation:"Use strong encryption algorithms (AES-256, SHA-256 or higher)"});for(let s of n.unencryptedDataHandling)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Sensitive data handled without encryption verification",remediation:"Ensure data is encrypted before processing sensitive information"});return i}async checkAccessControl(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeAccessControl(r);for(let s of n.unprotectedRoutes)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Sensitive endpoint potentially missing authorization middleware",remediation:"Add authorization check before sensitive operations"});for(let s of n.hardcodedCredentials)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Hardcoded credentials detected",remediation:"Use environment variables or secure secret management"});return i}async checkLogging(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeLogging(r);for(let s of n.sensitiveOperationsWithoutLogging)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Sensitive operation without audit logging",remediation:"Add audit log entry for data modification operations"});for(let s of n.sensitiveDataInLogs)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Sensitive data being logged",remediation:"Remove or mask sensitive data before logging"});return i}async checkDataProtection(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeDataProtection(r);for(let s of n.unmaskedPii)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"PII field without masking or encryption decorator",remediation:"Apply data protection decorators to sensitive fields"});for(let s of n.missingValidation)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Data fields without input validation",remediation:"Add input validation for all data fields, especially PII"});return i}async checkSecurityControls(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeSecurityControls(r);for(let s of n.missingControls)i.push({ruleId:t.id,ruleName:t.title,location:{file:"project-wide",line:0,snippet:`Missing: ${s}`},details:`Security control not detected: ${s}`,remediation:`Implement ${s} to enhance security posture`});for(let s of n.vulnerabilities)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Security vulnerability detected",remediation:"Review and fix the security issue"});return i}estimateEffort(t){let e=["architecture","data-rights","incident-response"],r=["access-control","encryption","change-management"];return e.includes(t.category)?"major":r.includes(t.category)||t.checkType==="manual"?"moderate":"minor"}async scanFileForDataTypes(t,e){let r=[],i=await this.patternAnalyzer.scanForDataTypes([t.value],e);for(let n of e){let s=i.get(n)||[];for(let a of s)r.push({type:n,location:{file:a.file,line:a.line,context:a.snippet||this.getDataTypeContext(n)}})}return r}getDataTypeContext(t){return{pii:"User personal information field",phi:"Health-related data field",financial:"Payment/financial data field",credentials:"Authentication credential field",biometric:"Biometric data field"}[t]}checkDataTypeViolation(t){let e=t.location.context.toLowerCase(),i=[/encrypt/i,/hash/i,/mask/i,/redact/i,/validate/i,/sanitize/i,/bcrypt/i,/argon2/i,/aes/i].some(a=>a.test(e)),s=[/console\.(log|debug|info)/i,/JSON\.stringify/i,/\.toString\(\)/i,/plaintext/i,/unencrypted/i].some(a=>a.test(e));if(!i||s){let a={pii:"gdpr-art32-security",phi:"hipaa-164.312-transmission",financial:"pci-req3",credentials:"soc2-cc6.6",biometric:"gdpr-art9-special"},o={file:t.location.file,line:t.location.line,snippet:t.location.context},l=s?"Potentially exposed in logs or serialization":"No protective measures detected";return{ruleId:a[t.type],ruleName:`${t.type.toUpperCase()} Data Protection`,location:o,details:`${t.type.toUpperCase()} data found: ${l}`,remediation:`Apply appropriate security controls for ${t.type} data`}}return null}getDataTypeRecommendations(t,e){let r=`Found ${e} ${t.toUpperCase()} data locations`;return{pii:[r,"Implement data minimization principles","Ensure consent mechanisms are in place","Add data retention policies"],phi:[r,"Verify HIPAA safeguards are implemented","Ensure business associate agreements are in place","Implement minimum necessary access"],financial:[r,"Verify PCI-DSS compliance for payment data","Implement tokenization where possible","Ensure proper key management"],credentials:[r,"Use secure credential storage (vaults)","Implement credential rotation","Avoid hardcoded credentials"],biometric:[r,"Implement enhanced protection measures","Obtain explicit consent","Consider data localization requirements"]}[t]}async collectEvidence(t,e){let r=[],i=await this.getFilesFromContext(e);if(t.checkType==="static"&&i.length>0){switch(t.category){case"encryption":{let n=await this.patternAnalyzer.analyzeEncryption(i);n.hasEncryption&&r.push(`Encryption detected: ${n.encryptionLibraries.join(", ")||"standard crypto"}`),n.weakCrypto.length>0&&r.push(`Weak crypto found in ${n.weakCrypto.length} location(s)`),r.push(`Unencrypted data handling: ${n.unencryptedDataHandling.length} instance(s)`);break}case"access_control":{let n=await this.patternAnalyzer.analyzeAccessControl(i);r.push(`Auth middleware: ${n.hasAuthMiddleware?"present":"not found"}`),r.push(`Unprotected routes: ${n.unprotectedRoutes.length}`),r.push(`Hardcoded credentials: ${n.hardcodedCredentials.length}`);break}case"logging":{let n=await this.patternAnalyzer.analyzeLogging(i);r.push(`Audit logging: ${n.hasAuditLogging?"implemented":"not found"}`),r.push(`Sensitive data in logs: ${n.sensitiveDataInLogs.length} instance(s)`);break}case"data_protection":{let n=await this.patternAnalyzer.analyzeDataProtection(i);r.push(`PII fields detected: ${n.piiFields.length}`),r.push(`Unmasked PII: ${n.unmaskedPii.length} instance(s)`),r.push(`Missing validation: ${n.missingValidation.length} field(s)`);break}default:r.push(`Static analysis completed for ${t.category}`),r.push(`Code patterns reviewed: ${t.title}`)}r.push(`Files analyzed: ${i.length}`)}else t.checkType==="dynamic"?(r.push(`Dynamic check required for: ${t.title}`),r.push("Evidence collection pending dynamic analysis")):t.checkType==="manual"&&(r.push(`Manual verification required for: ${t.title}`),r.push(`Review scope: ${e.projectRoot.value}`));return r.push(`Rule ${t.id} verified at ${new Date().toISOString()}`),r}async storeReport(t){await this.memory.set(`compliance:report:${t.standardId}:${Date.now()}`,t,{namespace:"security-compliance",persist:!0})}};var nP={stateSize:10,actionSize:5,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0},dc=class extends ve{qNetwork;targetNetwork;replayBufferClass;dqnConfig;updateCount=0;actions=[];constructor(t={}){super("dqn","value-based"),this.dqnConfig={...nP,...t},this.initializeActions(),this.qNetwork=new J({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass=new At(this.config.replayBufferSize,!1)}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.targetNetwork.forward(e),i=this.argmax(r),n=this.actions[i];return{action:n,confidence:.7,value:r[i],reasoning:`DQN: ${n.type}`}}async trainCore(t){for(let i of t)this.replayBufferClass.add(i);if(!this.replayBufferClass.isReady(this.dqnConfig.minReplaySize))return this.getStats();let e=this.replayBufferClass.sample(this.config.batchSize),r=0;for(let i of e){let n=this.prepareState(i.state),s=this.prepareState(i.nextState),a=this.actionToIndex(i.action),o=this.qNetwork.forward(n),l;if(this.dqnConfig.doubleDQN&&!i.done){let d=this.qNetwork.forward(s),m=this.argmax(d),p=this.targetNetwork.forward(s);l=i.reward+this.config.discountFactor*p[m]}else{let d=this.targetNetwork.forward(s);l=i.reward+this.config.discountFactor*Math.max(...d)*(i.done?0:1)}let u=new Float32Array(o.length);for(let d=0;d<u.length;d++)u[d]=d===a?l:o[d];r+=Math.abs(this.qNetwork.train(n,u,new Fe))}return this.updateCount++,this.updateCount%this.dqnConfig.targetUpdateFreq===0&&(this.targetNetwork=this.qNetwork.clone()),{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/e.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural DQN for Parallel Execution Scheduling",capabilities:["Experience replay","Target network","Double DQN"],hyperparameters:{stateSize:this.dqnConfig.stateSize,actionSize:this.dqnConfig.actionSize,hiddenLayers:this.dqnConfig.hiddenLayers.join(",")},stats:this.stats}}prepareState(t){let e=t.features.slice(0,this.dqnConfig.stateSize);for(;e.length<this.dqnConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]/=r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"parallelize",value:2},{type:"parallelize",value:4},{type:"parallelize",value:8},{type:"sequential",value:1},{type:"skip",value:0}],this.dqnConfig.actionSize=this.actions.length,this.qNetwork=new J({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone()}actionToIndex(t){let e=`${t.type}:${JSON.stringify(t.value)}`;for(let r=0;r<this.actions.length;r++)if(`${this.actions[r].type}:${JSON.stringify(this.actions[r].value)}`===e)return r;return 0}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}async exportCustomData(){return{qNetwork:this.qNetwork.getParameters(),targetNetwork:this.targetNetwork.getParameters(),dqnConfig:this.dqnConfig,updateCount:this.updateCount}}async importCustomData(t){t.qNetwork&&this.qNetwork.setParameters(t.qNetwork),t.targetNetwork&&this.targetNetwork.setParameters(t.targetNetwork),t.dqnConfig&&(this.dqnConfig={...this.dqnConfig,...t.dqnConfig}),typeof t.updateCount=="number"&&(this.updateCount=t.updateCount),this.initialized=!0}async resetAlgorithm(){this.qNetwork=new J({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass.clear(),this.updateCount=0}};var sP={maxConcurrentWorkflows:3,defaultTimeout:3e5,publishEvents:!0,autoTriageVulnerabilities:!0,riskThreshold:.7,enableDQN:!0,enableFlashAttention:!0,enableConsensus:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},de=x.create("security-compliance"),gs=class extends ie{constructor(e,r,i,n={},s){let a={...sP,...n};super(e,"security-compliance",a,{verifyFindingTypes:["security-vulnerability","compliance-violation","credential-exposure"],...a.consensusMixinConfig});this.memory=r;this.agentCoordinator=i;this.securityGovernanceMixin=Np(this.domainName),this.securityScanner=new dt({memory:r,llmRouter:s}),this.securityAuditor=new _r(r),this.complianceValidator=new Vr(r)}memory;agentCoordinator;securityScanner;securityAuditor;complianceValidator;dqnAlgorithm;flashAttention;rlInitialized=!1;consensusEngine;securityGovernanceMixin;async onInitialize(){this.subscribeToEvents(),await this.loadWorkflowState(),(this.config.enableDQN||this.config.enableFlashAttention||this.config.enableConsensus)&&await this.initializeRLIntegrations()}async initializeRLIntegrations(){try{if(this.config.enableDQN&&(this.dqnAlgorithm=new dc({stateSize:8,actionSize:5,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0})),this.config.enableFlashAttention){let e="test-similarity";this.flashAttention=await tt(e,{dim:384,strategy:"flash",numHeads:8})}if(this.config.enableConsensus){let r=xr(!0).getAll();r.length>0?(this.consensusEngine=In({strategy:"weighted",models:r,engineConfig:{minModels:Math.min(2,r.length),defaultModelTimeout:6e4,...this.config.consensusEngineConfig}}),de.info(`Multi-Model Consensus initialized with ${r.length} providers`)):de.warn("No model providers available for consensus verification")}this.rlInitialized=!0}catch(e){throw de.error("Failed to initialize RL integrations:",e instanceof Error?e:void 0),e}}async onDispose(){await this.saveWorkflowState()}getActiveWorkflows(){return super.getActiveWorkflows()}async runSecurityAudit(e){let r=w();try{if(this.startWorkflow(r,"audit"),this.detectAuthCodeInScope(e)&&this.securityGovernanceMixin.isGovernanceEnabled()&&!(await this.securityGovernanceMixin.validateSecurityScanRequired(r,!0,void 0)).allowed&&this.securityGovernanceMixin.isStrictMode()&&de.info("Security audit for auth code registered with governance"),this.minCutMixin.shouldPauseOperations())return de.warn("Security audit paused: topology is in critical state"),this.failWorkflow(r,"Topology is in critical state"),g(new Error("Security audit paused: topology is in critical state"));if(this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&de.warn("Topology degraded, using conservative audit strategy"),!this.agentCoordinator.canSpawn())return g(new Error("Agent limit reached, cannot spawn security audit agents"));let n=await this.spawnSecurityAuditAgent(r,e);if(!n.success)return this.failWorkflow(r,n.error.message),g(n.error);this.addAgentToWorkflow(r,n.value);let s=e.tests||[];this.config.enableDQN&&this.dqnAlgorithm&&s.length>0&&(s=await this.prioritizeSecurityTests(e,s));let a={...e},o=await this.securityAuditor.runAudit(a);if(o.success){this.completeWorkflow(r);let l=this.extractVulnerabilitiesFromReport(o.value);this.config.enableFlashAttention&&this.flashAttention&&l.length>0&&await this.enhanceVulnerabilityAnalysis(l),this.config.enableDQN&&this.dqnAlgorithm&&await this.trainDQNWithAuditFeedback(e,o.value),this.config.publishEvents&&await this.publishSecurityAuditCompleted(o.value)}else this.failWorkflow(r,o.error.message);return await this.agentCoordinator.stop(n.value),o}catch(i){let n=y(i);return this.failWorkflow(r,n.message),{success:!1,error:n}}}async runSecurityScan(e,r){let i=w();try{if(this.startWorkflow(i,"scan"),this.minCutMixin.shouldPauseOperations())return de.warn("Security scan paused: topology is in critical state"),this.failWorkflow(i,"Topology is in critical state"),g(new Error("Security scan paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&de.warn("Topology degraded, proceeding with conservative scan strategy");let n;return r==="sast"?n=await this.securityScanner.scanFiles(e):r==="dast"?n=await this.securityScanner.scanUrl(e[0]?.value??""):n=await this.securityScanner.scanFiles(e),n.success?this.completeWorkflow(i):this.failWorkflow(i,n.error.message),n}catch(n){let s=y(n);return this.failWorkflow(i,s.message),{success:!1,error:s}}}async runComplianceValidation(e,r){let i=w();try{if(this.startWorkflow(i,"compliance"),this.minCutMixin.shouldPauseOperations())return de.warn("Compliance validation paused: topology is in critical state"),this.failWorkflow(i,"Topology is in critical state"),g(new Error("Compliance validation paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&de.warn("Topology degraded, proceeding with compliance validation");let s=(await this.complianceValidator.getAvailableStandards()).find(o=>o.id===e);if(!s)return g(new Error(`Unknown compliance standard: ${e}`));let a=await this.complianceValidator.validate(s,r);return a.success?(this.completeWorkflow(i),this.config.publishEvents&&await this.publishComplianceValidationCompleted(a.value)):this.failWorkflow(i,a.error.message),a}catch(n){let s=y(n);return this.failWorkflow(i,s.message),{success:!1,error:s}}}async assessSecurityPosture(){let e=w();try{if(this.startWorkflow(e,"posture"),this.minCutMixin.shouldPauseOperations())return de.warn("Security posture assessment paused: topology is in critical state"),this.failWorkflow(e,"Topology is in critical state"),g(new Error("Security posture assessment paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&de.warn("Topology degraded, proceeding with security posture assessment");let r=await this.securityAuditor.getSecurityPosture();if(r.success){this.completeWorkflow(e);let i={overallScore:r.value.overallScore,trend:r.value.trend,criticalVulnerabilities:r.value.criticalIssues,complianceStatus:new Map,lastAuditDate:r.value.lastAuditDate};return f(i)}else return this.failWorkflow(e,r.error.message),r}catch(r){let i=y(r);return this.failWorkflow(e,i.message),{success:!1,error:i}}}async runComplianceCheck(e){let r={projectRoot:he.create("."),includePatterns:["**/*.ts","**/*.js"],excludePatterns:["node_modules/**"]};return this.runComplianceValidation(e,r)}async getSecurityPosture(){return this.assessSecurityPosture()}async prioritizeSecurityTests(e,r){if(!this.dqnAlgorithm||!this.rlInitialized)return r;try{let i=await Promise.all(r.map(async n=>{let s={id:`test-${n}`,features:this.extractSecurityTestFeatures(e,n)},a=await this.dqnAlgorithm.predict(s);return{test:n,score:a.value||0}}));return i.sort((n,s)=>s.score-n.score),i.map(n=>n.test)}catch(i){return de.error("Failed to prioritize security tests:",i instanceof Error?i:void 0),r}}async trainDQNWithAuditFeedback(e,r){if(!(!this.dqnAlgorithm||!this.rlInitialized))try{let i=this.extractVulnerabilitiesFromReport(r),n={id:`audit-${r.auditId}-${Date.now()}`,features:this.extractAuditFeatures(e)},s={type:"run-audit",value:i.length},a=this.calculateAuditReward(r),o={state:n,action:s,reward:a,nextState:n,done:!0,timestamp:new Date};await this.dqnAlgorithm.train(o),de.info(`Trained security audit with reward: ${a.toFixed(3)}`)}catch(i){de.error("Failed to train DQN:",i instanceof Error?i:void 0)}}calculateAuditReward(e){let r=this.extractVulnerabilitiesFromReport(e);if(r.length===0)return .5;let i=.5,n=r.filter(a=>a.severity==="critical").length;i+=Math.min(.3,n*.1);let s=r.filter(a=>a.severity==="high").length;return i+=Math.min(.2,s*.05),i+=(e.overallRiskScore?.value??0)*.1,Math.max(0,Math.min(1,i))}extractSecurityTestFeatures(e,r){let i=e.targetUrl??"";return[i.includes("/api")?1:0,i.startsWith("http")?1:0,e.includeSAST?1:0,r.includes("auth")?1:0,r.includes("sql")?1:0,r.includes("xss")?1:0,r.includes("injection")?1:0,r.length/100]}extractAuditFeatures(e){let r=e.depth??"standard",i=r==="deep"?1:r==="standard"?.5:.25;return[e.includeSAST?1:0,e.includeDAST?1:0,i,(e.scanTypes?.length??0)/4,e.includeDependencies?1:0,e.includeSecrets?1:0,(e.complianceFrameworks?.length??0)/5,e.targetUrl?1:0]}async enhanceVulnerabilityAnalysis(e){if(!(!this.flashAttention||!this.rlInitialized||e.length===0))try{let r=e.map(u=>this.createVulnerabilityEmbedding(u)),i=r.length,n=r[0].length,s=new Float32Array(i*n),a=new Float32Array(i*n),o=new Float32Array(i*n);for(let u=0;u<i;u++)s.set(r[u],u*n),a.set(r[u],u*n),o.set(r[u],u*n);let l=await this.flashAttention.computeFlashAttention(s,a,o,i,n);for(let u=0;u<e.length;u++){let d=Array.from(l.slice(u*n,(u+1)*n));r[u].reduce((p,h,v)=>p+h*d[v],0)>.7&&de.info(`High self-attention for vulnerability ${e[u].id}`)}}catch(r){de.error("Failed to enhance vulnerability analysis:",r instanceof Error?r:void 0)}}createVulnerabilityEmbedding(e){let r=[],i=this.hashCode(e.category);r.push(i%1e3/1e3);let n={critical:1,high:.75,medium:.5,low:.25,informational:.1};r.push(n[e.severity]||.5);let s=this.hashCode(e.title);r.push(s%1e3/1e3),r.push(Math.min(1,e.description.length/500));let a=e.cveId?this.hashCode(e.cveId):0;r.push(a%1e3/1e3);let o=this.hashCode(e.description.slice(0,200));for(let l=r.length;l<384;l++)r.push(o*(l+1)%1e4/1e4);return r.slice(0,384)}hashCode(e){let r=0;for(let i=0;i<e.length;i++)r=(r<<5)-r+e.charCodeAt(i),r=r|0;return Math.abs(r)}async spawnSecurityAuditAgent(e,r){let i={name:`security-auditor-${e.slice(0,8)}`,domain:"security-compliance",type:"auditor",capabilities:["security-audit","vulnerability-scanning","compliance-check"],config:{workflowId:e,targetUrl:r.targetUrl,depth:r.depth}};return this.agentCoordinator.spawn(i)}extractVulnerabilitiesFromReport(e){let r=[];return e.sastResults?.vulnerabilities&&r.push(...e.sastResults.vulnerabilities),e.dastResults?.vulnerabilities&&r.push(...e.dastResults.vulnerabilities),e.dependencyResults?.vulnerabilities&&r.push(...e.dependencyResults.vulnerabilities),r}async publishSecurityAuditCompleted(e){let r=this.extractVulnerabilitiesFromReport(e),i=await this.verifyHighSeverityFindings(r);for(let n of i){let s={vulnId:n.id,cve:n.cveId,severity:n.severity,file:n.location.file,line:n.location.line,description:n.description,remediation:n.remediation.description},a=N(zc.SecurityAuditCompleted,"security-compliance",s);await this.eventBus.publish(a)}}async verifyHighSeverityFindings(e){if(!this.config.enableConsensus)return e;if(!this.isConsensusAvailable())return this.consensusEngine?this.verifyHighSeverityFindingsLegacy(e):e;let r=[],i=e.filter(a=>a.severity==="critical"||a.severity==="high"),n=e.filter(a=>a.severity!=="critical"&&a.severity!=="high");r.push(...n);for(let a of i)try{let o=U({id:a.id,type:"security-vulnerability",confidence:.8,description:`${a.title}: ${a.description}`,payload:{vulnerability:a,location:a.location},detectedBy:"security-scanner",severity:a.severity,context:{domain:this.domainName,cveId:a.cveId,category:a.category}});if(!this.consensusMixin.requiresConsensus(o)){r.push(a);continue}let l=await this.consensusMixin.verifyFinding(o);l.success&&l.value.verdict==="verified"?(de.info(`Consensus VERIFIED: ${a.title} (confidence: ${(l.value.confidence*100).toFixed(1)}%)`),r.push(a)):l.success&&l.value.verdict==="disputed"?(de.info(`Consensus DISPUTED: ${a.title} - including with lower confidence`),r.push(a)):de.info(`Consensus REJECTED: ${a.title} - likely false positive`)}catch{de.warn(`Consensus error verifying ${a.title}, including by default:`),r.push(a)}let s=i.length-r.filter(a=>a.severity==="critical"||a.severity==="high").length;return s>0&&de.info(`Consensus filtered out ${s} likely false positive(s)`),r}async verifyHighSeverityFindingsLegacy(e){if(!this.consensusEngine)return e;let r=[],i=e.filter(s=>s.severity==="critical"||s.severity==="high"),n=e.filter(s=>s.severity!=="critical"&&s.severity!=="high");r.push(...n);for(let s of i)try{let a={id:s.id,type:s.category,description:s.description,category:s.category,severity:s.severity,location:{file:s.location.file,line:s.location.line,column:s.location.column},evidence:[{type:"code-snippet",content:s.location.snippet||s.description}],cveId:s.cveId,remediation:s.remediation.description,detectedAt:new Date,detectedBy:"security-scanner"},o=await this.consensusEngine.verify(a);(o.success&&o.value.verdict==="verified"||o.success&&o.value.verdict==="disputed")&&r.push(s)}catch{r.push(s)}return r}async publishComplianceValidationCompleted(e){let r={standard:e.standardId,passed:e.complianceScore>=.8,violations:e.violations.length,findings:e.violations.map(n=>n.details).slice(0,10)},i=N(zc.ComplianceValidated,"security-compliance",r);await this.eventBus.publish(i)}detectAuthCodeInScope(e){let r=[/auth/i,/login/i,/password/i,/token/i,/session/i,/oauth/i,/jwt/i,/credential/i,/identity/i];if(e.targetUrl){for(let i of r)if(i.test(e.targetUrl))return!0}if(e.scanTypes){let i=["authentication","authorization","session-management"];for(let n of e.scanTypes)if(i.includes(n.toLowerCase()))return!0}if(e.complianceFrameworks){let i=["soc2","pci-dss","hipaa","iso27001"];for(let n of e.complianceFrameworks)if(i.includes(n.toLowerCase()))return!0}return!1}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this))}async handleTestRunCompleted(e){}async handleImpactAnalysis(e){}async loadWorkflowState(){let e=await this.memory.get("security-compliance:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("security-compliance:coordinator:workflows",e,{namespace:"security-compliance",persist:!0})}getHealthyRoutingDomains(){return this.minCutMixin.getHealthyRoutingDomains()}};k();var mc=class extends te{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;securityScanner=null;securityAuditor=null;complianceValidator=null;pluginConfig;get name(){return"security-compliance"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{runSecurityAudit:this.runSecurityAudit.bind(this),getSecurityPosture:this.getSecurityPosture.bind(this),runSASTScan:this.runSASTScan.bind(this),runDASTScan:this.runDASTScan.bind(this),runDependencyScan:this.runDependencyScan.bind(this),triageVulnerabilities:this.triageVulnerabilities.bind(this),runComplianceCheck:this.runComplianceCheck.bind(this),getAvailableStandards:this.getAvailableStandards.bind(this),analyzeComplianceGaps:this.analyzeComplianceGaps.bind(this),getCoordinator:()=>this.coordinator,getSecurityScanner:()=>this.securityScanner,getSecurityAuditor:()=>this.securityAuditor,getComplianceValidator:()=>this.complianceValidator}}getTaskHandlers(){return new Map([["security-audit",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.target??e.targetUrl;return r?this.coordinator.runSecurityAudit({includeSAST:e.includeSAST??!0,includeDAST:e.includeDAST??!1,includeDependencies:e.includeDependencies??!0,includeSecrets:e.includeSecrets??!0,targetUrl:r}):g(new Error("Invalid security-audit payload: missing target"))}],["compliance-check",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.standardId;return r?this.coordinator.runComplianceCheck(r):g(new Error("Invalid compliance-check payload: missing standardId"))}],["sast-scan",async e=>{if(!this.securityScanner)return g(new Error("Security scanner not initialized"));let r=e.files;if(!r||r.length===0)return g(new Error("Invalid sast-scan payload: missing files"));if(r.some(s=>typeof s=="string"?s.trim()==="":!(s instanceof he)))return g(new Error("Invalid sast-scan payload: files must be non-empty file paths"));let{accepted:i,skipped:n}=await Uh(r.map(s=>typeof s=="string"?s:s.value));return n.length>0?g(new Error(`Invalid sast-scan payload: these files cannot be scanned: ${n.map(s=>`${s.path} (${s.reason})`).join(", ")}. Pass regular files inside the project, at most ${sd/(1024*1024)} MB each.`)):this.securityScanner.scanFiles(i.map(s=>he.create(s)))}],["dast-scan",async e=>{if(!this.securityScanner)return g(new Error("Security scanner not initialized"));let r=e.targetUrl;return r?this.securityScanner.scanUrl(r):g(new Error("Invalid dast-scan payload: missing targetUrl"))}],["triage-vulnerabilities",async e=>{if(!this.securityAuditor)return g(new Error("Security auditor not initialized"));let r=e.vulnerabilities;return!r||r.length===0?g(new Error("Invalid triage-vulnerabilities payload: missing vulnerabilities")):this.securityAuditor.triageVulnerabilities(r)}]])}async onInitialize(){this.securityScanner=new dt({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.securityScanner),this.securityAuditor=new _r(this.memory,this.pluginConfig.securityAuditor),this.complianceValidator=new Vr(this.memory,this.pluginConfig.complianceValidator),this.coordinator=new gs(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.securityScanner=null,this.securityAuditor=null,this.complianceValidator=null}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.KnowledgeGraphUpdated",this.handleKnowledgeGraphUpdate.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGateEvaluated.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"code-intelligence.KnowledgeGraphUpdated":await this.handleKnowledgeGraphUpdate(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGateEvaluated(e);break;default:break}}async runSecurityAudit(e){this.ensureInitialized();try{let r=await this.coordinator.runSecurityAudit(e);return r.success?this.trackSuccessfulOperation("audit"):this.trackFailedOperation("audit",r.error),r}catch(r){return this.handleError(r)}}async getSecurityPosture(){this.ensureInitialized();try{return await this.coordinator.getSecurityPosture()}catch(e){return this.handleError(e)}}async runDependencyScan(e){this.ensureInitialized();try{let r=await this.securityScanner.scanPackageJson(e);return r.success&&r.value.status==="complete"?this.trackSuccessfulOperation("dependency-scan"):this.trackFailedOperation("dependency-scan",r.success?new Error(r.value.error??"Dependency advisory scan incomplete"):r.error),r}catch(r){return this.handleError(r)}}async runSASTScan(e){this.ensureInitialized();try{let r=await this.securityScanner.scanFiles(e);return r.success?this.trackSuccessfulOperation("sast-scan"):this.trackFailedOperation("sast-scan",r.error),r}catch(r){return this.handleError(r)}}async runDASTScan(e){this.ensureInitialized();try{let r=await this.securityScanner.scanUrl(e);return r.success?this.trackSuccessfulOperation("dast-scan"):this.trackFailedOperation("dast-scan",r.error),r}catch(r){return this.handleError(r)}}async triageVulnerabilities(e){this.ensureInitialized();try{let r=await this.securityAuditor.triageVulnerabilities(e);return r.success?{success:!0,value:{immediate:r.value.immediate,shortTerm:r.value.shortTerm}}:{success:!1,error:r.error}}catch(r){return this.handleError(r)}}async runComplianceCheck(e){this.ensureInitialized();try{let r=await this.coordinator.runComplianceCheck(e);return r.success?this.trackSuccessfulOperation("compliance-check"):this.trackFailedOperation("compliance-check",r.error),r}catch(r){return this.handleError(r)}}async getAvailableStandards(){return this.ensureInitialized(),this.complianceValidator.getAvailableStandards()}async analyzeComplianceGaps(e,r){this.ensureInitialized();try{return await this.complianceValidator.analyzeGaps(e,r)}catch(i){return this.handleError(i)}}async handleKnowledgeGraphUpdate(e){let r=e.payload;await this.memory.set(`security:code-update:${Date.now()}`,{filesIndexed:r.filesIndexed,timestamp:new Date},{namespace:"security-compliance",ttl:3600})}async handleQualityGateEvaluated(e){let r=e.payload,i=r.checks.filter(n=>n.name.toLowerCase().includes("security"));i.length>0&&await this.memory.set(`security:gate-results:${r.gateId}`,{securityChecks:i,passed:r.passed},{namespace:"security-compliance",persist:!0})}async handleTestRunCompleted(e){}ensureInitialized(){if(!this._initialized)throw new Error("SecurityCompliancePlugin is not initialized");if(!this.coordinator||!this.securityScanner||!this.securityAuditor||!this.complianceValidator)throw new Error("SecurityCompliancePlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date}),this.memory.set(`security:operation:${e}:${Date.now()}`,{operation:e,success:!0,timestamp:new Date},{namespace:"security-compliance",ttl:86400})}trackFailedOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,failed:i.agents.failed+1},errors:[...i.errors.slice(-9),r.message]}),this.memory.set(`security:operation:${e}:${Date.now()}`,{operation:e,success:!1,error:r.message,timestamp:new Date},{namespace:"security-compliance",ttl:86400})}};function Yd(c,t,e,r,i){return new mc(c,t,e,r,i)}_();k();mr();_();k();X();Pe();var aP={strictMode:!0,validateExamples:!0,maxSchemaDepth:ha.MAX_SCHEMA_DEPTH,cacheValidations:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:fa.MAX_TOKENS},oP=x.create("contract-testing/contract-validator"),Fi=class{config;memory;llmRouter;validationCache=new Map;MAX_CACHED_VALIDATIONS=ha.MAX_CACHED_VALIDATIONS;CACHE_TTL_MS=ha.CACHE_TTL_MS;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...aP,...e}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(t){return ae(t)}async analyzeContractWithLLM(t){if(!this.isLLMAnalysisAvailable())return null;try{let e=t.consumers.map(i=>i.name).join(", ");return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze this API contract for potential issues:
2911
+ `),Ic={file:v,line:O,column:q,snippet:Y},hb={description:R.remediation,fixExample:R.fixExample,estimatedEffort:R.severity==="critical"?"moderate":"minor",automatable:R.severity==="low"||R.severity==="medium"};i.push({id:w(),cveId:void 0,title:R.title,description:`${R.description} [${R.cweId}]`,severity:R.severity,category:R.category,location:Ic,remediation:hb,references:[`https://cwe.mitre.org/data/definitions/${R.cweId.replace("CWE-","")}.html`]})}}}catch{}}}catch(p){Hx.error("SAST scan failed:",p instanceof Error?p:void 0)}let a=Date.now()-r,o=0,l=0,u=0,d=0,m=0;for(let p of i)switch(p.severity){case"critical":o++;break;case"high":l++;break;case"medium":u++;break;case"low":d++;break;case"informational":m++;break}return{scanId:e,vulnerabilities:i,summary:{critical:o,high:l,medium:u,low:d,informational:m,totalFiles:n,scanDurationMs:a},coverage:{filesScanned:n,linesScanned:s,rulesApplied:12}}}_();k();var Ux=x.create("security-compliance/security-auditor-dast");async function wv(c){let t=w(),e=Date.now(),r=[],i=0;try{let d;try{d=new URL(c)}catch{return{scanId:t,targetUrl:c,vulnerabilities:[{id:w(),title:"Invalid Target URL",description:"The provided target URL is not valid",severity:"informational",category:"security-misconfiguration",location:{file:c},remediation:{description:"Provide a valid URL",estimatedEffort:"trivial",automatable:!1},references:[]}],summary:{critical:0,high:0,medium:0,low:0,informational:1,totalFiles:0,scanDurationMs:Date.now()-e},crawledUrls:0}}let m=new AbortController,p=setTimeout(()=>m.abort(),3e4);try{let h=await fetch(c,{method:"GET",headers:{"User-Agent":"AgenticQE-SecurityScanner/3.0",Accept:"text/html,application/json,*/*"},signal:m.signal,redirect:"follow"});clearTimeout(p),i=1;let v=h.headers,b=[{header:"strict-transport-security",title:"Missing HTTP Strict Transport Security (HSTS)",description:"HSTS header is missing, allowing downgrade attacks",severity:"medium",remediation:"Add Strict-Transport-Security header with appropriate max-age"},{header:"x-content-type-options",title:"Missing X-Content-Type-Options Header",description:"X-Content-Type-Options header is missing, allowing MIME sniffing attacks",severity:"low",remediation:"Add X-Content-Type-Options: nosniff header"},{header:"x-frame-options",title:"Missing X-Frame-Options Header",description:"X-Frame-Options header is missing, allowing clickjacking attacks",severity:"medium",remediation:"Add X-Frame-Options: DENY or SAMEORIGIN header"},{header:"content-security-policy",title:"Missing Content Security Policy",description:"CSP header is missing, increasing XSS attack surface",severity:"medium",remediation:"Implement a Content-Security-Policy header"},{header:"x-xss-protection",title:"Missing X-XSS-Protection Header",description:"X-XSS-Protection header is missing (legacy XSS filter)",severity:"low",remediation:"Add X-XSS-Protection: 1; mode=block header"}];for(let E of b)v.get(E.header)||r.push({id:w(),title:E.title,description:E.description,severity:E.severity,category:"security-misconfiguration",location:{file:c,snippet:`Response Headers: ${E.header} not present`},remediation:{description:E.remediation,estimatedEffort:"minor",automatable:!0},references:["https://owasp.org/www-project-secure-headers/"]});let C=v.get("set-cookie");C&&(C.toLowerCase().includes("secure")||r.push({id:w(),title:"Cookie Without Secure Flag",description:"Session cookie is set without the Secure flag",severity:"medium",category:"sensitive-data",location:{file:c,snippet:`Set-Cookie: ${C.substring(0,50)}...`},remediation:{description:"Add Secure flag to cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/controls/SecureCookieAttribute"]}),C.toLowerCase().includes("httponly")||r.push({id:w(),title:"Cookie Without HttpOnly Flag",description:"Session cookie is set without the HttpOnly flag, making it accessible to JavaScript",severity:"medium",category:"sensitive-data",location:{file:c,snippet:`Set-Cookie: ${C.substring(0,50)}...`},remediation:{description:"Add HttpOnly flag to session cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/HttpOnly"]}),C.toLowerCase().includes("samesite")||r.push({id:w(),title:"Cookie Without SameSite Attribute",description:"Cookie is set without the SameSite attribute, potentially vulnerable to CSRF",severity:"low",category:"broken-auth",location:{file:c,snippet:`Set-Cookie: ${C.substring(0,50)}...`},remediation:{description:"Add SameSite=Strict or SameSite=Lax to cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/SameSite"]}));let S=v.get("server");S&&/[0-9]+\.[0-9]+/.test(S)&&r.push({id:w(),title:"Server Version Disclosure",description:`Server header reveals version information: ${S}`,severity:"low",category:"security-misconfiguration",location:{file:c,snippet:`Server: ${S}`},remediation:{description:"Remove or obfuscate server version information",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]}),d.protocol==="http:"&&r.push({id:w(),title:"Insecure HTTP Protocol",description:"Target is using HTTP instead of HTTPS, exposing data in transit",severity:"high",category:"sensitive-data",location:{file:c},remediation:{description:"Use HTTPS with valid TLS certificate",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]});let R=[{path:"/.git/config",vuln:"Git Repository Exposed",severity:"high"},{path:"/.env",vuln:"Environment File Exposed",severity:"critical"},{path:"/phpinfo.php",vuln:"PHP Info Exposed",severity:"medium"},{path:"/wp-config.php.bak",vuln:"WordPress Config Backup Exposed",severity:"critical"}];for(let E of R)try{let T=new URL(E.path,d.origin).toString(),I=await fetch(T,{method:"GET",signal:AbortSignal.timeout(5e3)});if(I.ok&&I.status===200){let O=await I.text();O.length>10&&!O.toLowerCase().includes("not found")&&(i++,r.push({id:w(),title:E.vuln,description:`Sensitive file found at ${E.path}`,severity:E.severity,category:"sensitive-data",location:{file:T},remediation:{description:"Remove or restrict access to sensitive files",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]}))}}catch{}}catch(h){clearTimeout(p);let v=P(h);(v.includes("certificate")||v.includes("SSL")||v.includes("TLS"))&&r.push({id:w(),title:"TLS/SSL Certificate Issue",description:`Certificate error: ${v}`,severity:"high",category:"security-misconfiguration",location:{file:c},remediation:{description:"Fix TLS certificate configuration",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]})}}catch(d){Ux.error("DAST scan failed:",d instanceof Error?d:void 0)}let n=Date.now()-e,s=0,a=0,o=0,l=0,u=0;for(let d of r)switch(d.severity){case"critical":s++;break;case"high":a++;break;case"medium":o++;break;case"low":l++;break;case"informational":u++;break}return{scanId:t,targetUrl:c,vulnerabilities:r,summary:{critical:s,high:a,medium:o,low:l,informational:u,totalFiles:1,scanDurationMs:n},crawledUrls:i}}_();var Qx=x.create("security-compliance/security-auditor-secrets");function Kx(){return[{name:"AWS Access Key ID",type:"api-key",regex:/AKIA[0-9A-Z]{16}/g},{name:"AWS Secret Access Key",type:"api-key",regex:/(?:aws[_-]?secret[_-]?access[_-]?key|AWS_SECRET_ACCESS_KEY)['"]?\s*[:=]\s*['"]?([A-Za-z0-9/+=]{40})['"]?/gi,entropyThreshold:4},{name:"GitHub Personal Access Token",type:"token",regex:/ghp_[A-Za-z0-9]{36}/g},{name:"GitHub OAuth Access Token",type:"token",regex:/gho_[A-Za-z0-9]{36}/g},{name:"GitHub App Token",type:"token",regex:/(?:ghu|ghs)_[A-Za-z0-9]{36}/g},{name:"Generic API Key",type:"api-key",regex:/(?:api[_-]?key|apikey|api_secret)['"]?\s*[:=]\s*['"]([A-Za-z0-9_\-]{20,})['"]?/gi,entropyThreshold:3.5},{name:"OpenAI API Key",type:"api-key",regex:/sk-[A-Za-z0-9]{48}/g},{name:"Stripe Secret Key",type:"api-key",regex:/sk_live_[A-Za-z0-9]{24,}/g},{name:"Stripe Publishable Key",type:"api-key",regex:/pk_live_[A-Za-z0-9]{24,}/g},{name:"RSA Private Key",type:"private-key",regex:/-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/gi},{name:"PGP Private Key",type:"private-key",regex:/-----BEGIN\s+PGP\s+PRIVATE\s+KEY\s+BLOCK-----/gi},{name:"SSH Private Key",type:"private-key",regex:/-----BEGIN\s+(?:OPENSSH|DSA|EC)?\s*PRIVATE\s+KEY-----/gi},{name:"Password Assignment",type:"password",regex:/(?:password|passwd|pwd|secret)['"]?\s*[:=]\s*['"]([^'"\s]{8,})['"]?/gi,entropyThreshold:3},{name:"Database Connection String",type:"password",regex:/(?:mongodb|postgres|mysql|redis):\/\/[^:]+:[^@]+@[^\s'"]+/gi},{name:"JWT Token",type:"token",regex:/eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*/g,entropyThreshold:4},{name:"Slack Token",type:"token",regex:/xox[baprs]-[A-Za-z0-9-]{10,}/g},{name:"Google API Key",type:"api-key",regex:/AIza[A-Za-z0-9_-]{35}/g},{name:"Twilio API Key",type:"api-key",regex:/SK[A-Za-z0-9]{32}/g},{name:"SendGrid API Key",type:"api-key",regex:/SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}/g},{name:"X.509 Certificate",type:"certificate",regex:/-----BEGIN\s+CERTIFICATE-----/gi}]}function Jx(c){if(!c||c.length===0)return 0;let t={};for(let i of c)t[i]=(t[i]||0)+1;let e=0,r=c.length;for(let i in t){let n=t[i]/r;e-=n*Math.log2(n)}return e}function Yx(c,t,e){let n=Math.max(0,t-20),s=Math.min(c.length,t+e+10),a=c.substring(n,s),o=t-n,l=a.substring(o,o+e);if(l.length>8){let u=l.substring(0,4)+"..."+l.substring(l.length-4);a=a.substring(0,o)+u+a.substring(o+e)}return n>0&&(a="..."+a),s<c.length&&(a=a+"..."),a}function Xx(c,t){switch(c){case"api-key":return t.length>=20&&/[a-z]/.test(t)&&/[A-Z0-9]/.test(t);case"token":return t.length>=20;case"password":return!["password","secret","changeme","12345678","qwerty"].includes(t.toLowerCase());case"private-key":return!0;case"certificate":return!0;default:return!0}}async function Qd(c){let t=[];try{let r=(await Re(c.value,{outsideRoot:"allow"})).split(`
2912
+ `),i=Kx();for(let n=0;n<r.length;n++){let s=r[n],a=n+1;for(let o of i){o.regex.lastIndex=0;let l;for(;(l=o.regex.exec(s))!==null;){let u=l[1]||l[0],d=Jx(u);if(o.entropyThreshold&&d<o.entropyThreshold)continue;let m=Yx(s,l.index,u.length),p={file:c.value,line:a,column:l.index+1,snippet:m};t.push({type:o.type,location:p,entropy:d,isValid:Xx(o.type,u)})}}}}catch(e){Qx.error(`Failed to scan file for secrets: ${c.value}`,e instanceof Error?e:void 0)}return t}function Cv(c,t,e,r){let i=0,n=0;if(c&&(i+=Kd(c.summary)*.35,n+=.35),t&&(i+=Kd(t.summary)*.25,n+=.25),e&&(i+=Kd(e.summary)*.25,n+=.25),r){let a=r.secretsFound.length>0?.9:.1;i+=a*.15,n+=.15}let s=n>0?i/n:0;return{value:Math.min(1,s),percentage:s*100,level:s>=.8?"critical":s>=.6?"high":s>=.3?"medium":"low"}}function Kd(c){let t={critical:1,high:.7,medium:.4,low:.1,informational:.02};if(c.critical+c.high+c.medium+c.low+c.informational===0)return 0;let r=c.critical*t.critical+c.high*t.high+c.medium*t.medium+c.low*t.low+c.informational*t.informational;return Math.min(1,r/10)}function Sv(c,t,e,r){let i=[];return c&&c.summary.critical>0&&i.push(`Address ${c.summary.critical} critical vulnerabilities found in static analysis`),t&&t.summary.high>0&&i.push(`Fix ${t.summary.high} high-severity issues found in dynamic testing`),e&&e.outdatedPackages.length>5&&i.push(`Update ${e.outdatedPackages.length} outdated dependencies`),r&&r.secretsFound.length>0&&i.push(`Remove ${r.secretsFound.length} exposed secrets and rotate credentials`),i.length===0&&i.push("Security posture is good. Continue regular scanning."),i}function Jd(c,t){if(!c)return 0;let e=0;return c.sastResults&&(e+=c.sastResults.summary[t]),c.dastResults&&(e+=c.dastResults.summary[t]),c.dependencyResults&&(e+=c.dependencyResults.summary[t]),e}function Mi(c){if(!c)return 0;let t=0;return c.sastResults&&(t+=c.sastResults.vulnerabilities.length),c.dastResults&&(t+=c.dastResults.vulnerabilities.length),c.dependencyResults&&(t+=c.dependencyResults.vulnerabilities.length),t}function Rv(c,t){if(!c||!t)return"stable";let e=Mi(c),r=Mi(t);return e<r*.9?"improving":e>r*1.1?"declining":"stable"}function Tv(c,t,e){let r=100;return r-=c*20,r-=t*10,r-=e*2,Math.max(0,Math.min(100,r))}function Ev(c,t,e){let r=[];return c>0&&r.push("Immediately address all critical vulnerabilities"),t>3&&r.push("Prioritize fixing high-severity issues"),e<50&&(r.push("Consider a comprehensive security review"),r.push("Implement automated security scanning in CI/CD")),e>=80&&(r.push("Maintain current security practices"),r.push("Consider penetration testing for deeper analysis")),r}function Av(c){let t=c.remediation.estimatedEffort;return c.severity==="critical"?"immediate":c.severity==="high"?t==="trivial"||t==="minor"?"immediate":"shortTerm":c.severity==="medium"?t==="major"?"longTerm":"mediumTerm":c.severity==="low"||c.severity==="informational"?"longTerm":"accepted"}var Dt=x.create("security-compliance/security-auditor"),xv="(dependency plan)",_r=class{constructor(t,e={},r){this.memory=t;this.config={...Ud,...e},this.osvClient=r??new Nr}memory;config;osvClient;async scanDependencies(t){try{let e=t.value,r=this.detectEcosystem(e);if(!r)return g(new Error(`Unknown manifest format: ${e}`));let i=[],{dependencies:n,preUnchecked:s}=await this.parseDependenciesForScan(e,r),a=await this.checkDependencyAdvisories(n,s);for(let u of n){let d=await this.checkOutdated(u);d&&i.push(d)}let o=this.createDependencySummary(a.vulnerabilities,n.length),l=this.toDependencyScanResult(a,i,o);return await this.memory.set(`security:deps:${t.filename}`,l,{namespace:"security-compliance",ttl:86400}),f(l)}catch(e){return g(y(e))}}async checkPackage(t,e,r){try{let i=await this.queryVulnerabilityDatabase(t,e,r),n=await this.getLatestVersion(t,r),s=await this.checkDeprecation(t,r);return f({name:t,version:e,vulnerabilities:i,latestVersion:n,isDeprecated:s})}catch(i){return g(y(i))}}async getUpgradeRecommendations(t){try{let e=[],r=new Map;for(let i of t){let n=i.location.dependency;if(n){let s=`${n.ecosystem}:${n.name}`,a=r.get(s)||[];a.push(i),r.set(s,a)}}for(let[i,n]of r){let[s,a]=i.split(":"),o=n[0].location.dependency?.version||"unknown",l=await this.getLatestVersion(a,s),u=n.filter(d=>d.id).map(d=>d.id);e.push({package:a,fromVersion:o,toVersion:l,fixesVulnerabilities:u,breakingChanges:this.hasBreakingChanges(o,l)})}return e.sort((i,n)=>n.fixesVulnerabilities.length-i.fixesVulnerabilities.length),f(e)}catch(e){return g(y(e))}}async runAudit(t){let e=w(),r=new Date;try{let i,n,s,a;t.includeSAST&&(i=await bv(d=>this.findSourceFiles(d),d=>this.shouldExclude(d))),t.includeDAST&&t.targetUrl&&(n=await wv(t.targetUrl)),t.includeDependencies&&(s=await this.performDependencyScan()),t.includeSecrets&&(a=await this.performSecretScan());let o=Cv(i,n,s,a),l=Sv(i,n,s,a);s&&s.status!=="complete"&&l.unshift(`${s.error??"Dependency advisories could not be checked"}. Dependency risk is unmeasured; re-run the scan when the OSV API is reachable.`);let u={auditId:e,timestamp:r,sastResults:i,dastResults:n,dependencyResults:s,secretScanResults:a,overallRiskScore:o,recommendations:l};return await this.memory.set(`security:audit:${e}`,u,{namespace:"security-compliance",persist:!0}),f(u)}catch(i){return g(y(i))}}async scanSecrets(t){try{let e=[],r=0;for(let i of t){if(this.shouldExclude(i.value))continue;r++;let n=await Qd(i);e.push(...n)}return f({secretsFound:e,filesScanned:r})}catch(e){return g(y(e))}}async getSecurityPosture(){try{let t=await this.getRecentAudits(),e=t[0],r=t[1],i=Jd(e,"critical"),n=Jd(e,"high"),s=Mi(e),a=Rv(e,r),o=Tv(i,n,s),l=Ev(i,n,o);return f({overallScore:o,trend:a,criticalIssues:i,highIssues:n,openVulnerabilities:s,resolvedLastWeek:await this.countResolvedLastWeek(),averageResolutionTime:await this.calculateAverageResolutionTime(),lastAuditDate:e?.timestamp??new Date,recommendations:l})}catch(t){return g(y(t))}}async triageVulnerabilities(t){try{let e={immediate:[],shortTerm:[],mediumTerm:[],longTerm:[],accepted:[]};for(let i of t){let n=Av(i);e[n].push(i)}let r=["critical","high","medium","low","informational"];for(let i of Object.values(e))i.sort((n,s)=>r.indexOf(n.severity)-r.indexOf(s.severity));return f(e)}catch(e){return g(y(e))}}detectEcosystem(t){return t.includes("package.json")?"npm":t.includes("requirements.txt")||t.includes("Pipfile")?"pip":t.includes("pom.xml")||t.includes("build.gradle")?"maven":t.includes("Cargo.toml")?"cargo":t.includes(".csproj")||t.includes("packages.config")?"nuget":null}async parseDependencies(t,e){let r=[];try{if(e==="npm"){let i=await Re(t,{outsideRoot:"allow"}),n=D(i),s={...n.dependencies,...n.devDependencies,...n.peerDependencies,...n.optionalDependencies};for(let[a,o]of Object.entries(s))r.push({name:a,version:o,ecosystem:"npm"})}else if(e==="pip"){let n=(await Re(t,{outsideRoot:"allow"})).split(`
2913
+ `);for(let s of n){let a=s.trim();if(!a||a.startsWith("#"))continue;let o=a.match(/^([a-zA-Z0-9_.-]+)\s*(===?|>=|<=|~=|!=|>|<)?\s*([^\s;#]+)?/);if(o){let[,l,u,d]=o;r.push({name:l,version:d&&(u==="=="||u==="===")?d:u&&d?`${u}${d}`:"*",ecosystem:"pip"})}}}}catch(i){throw Dt.error(`Failed to parse dependencies from ${t}:`,i instanceof Error?i:void 0),i}return r}async parseDependenciesForScan(t,e){if(e!=="npm")return{dependencies:await this.parseDependencies(t,e),preUnchecked:[]};let r;try{r=await uc(t)}catch(s){throw Dt.error(`Failed to parse dependencies from ${t}:`,s instanceof Error?s:void 0),s}let i=[],n=[];for(let s of r.dependencies)s.kind==="check"?i.push({name:s.packageName,version:s.version,ecosystem:"npm"}):s.kind==="unchecked"&&n.push({name:s.name,version:s.spec,reason:s.reason??"not checked",...s.member?{member:s.member}:{},...s.lockedVersion?{lockedVersion:s.lockedVersion}:{}});for(let s of[...r.error?[r.error]:[],...r.memberErrors])n.push({name:xv,version:"*",reason:s});return{dependencies:i,preUnchecked:n}}async checkDependencyAdvisories(t,e=[]){let r=await this.osvClient.lookupBatch(t.map(u=>({name:u.name,ecosystem:this.mapToOSVEcosystem(u.ecosystem),version:u.version}))),i=[];for(let u of t){let d=r.results.get(nr({ecosystem:this.mapToOSVEcosystem(u.ecosystem),name:u.name,version:u.version}))??[];i.push(...d.map(m=>this.mapParsedVulnerability(m,u)))}let n=[...e,...r.unchecked.map(u=>({name:u.name,version:u.version??"unknown",reason:u.reason}))],s=r.errors.length>0?r.errors:[...new Set(n.map(u=>u.reason))],a=r.packagesChecked+n.length,o=a-n.filter(u=>u.name===xv).length,l=r.packagesChecked===a?"complete":r.packagesChecked===0&&o>0?"failed":"incomplete";return{vulnerabilities:i,status:l,packagesChecked:r.packagesChecked,uncheckedPackages:n,...l==="complete"?{}:{error:`Dependency advisories could not be checked for ${n.length} package(s): ${s.slice(0,3).join("; ")}`}}}toDependencyScanResult(t,e,r){return{vulnerabilities:t.vulnerabilities,outdatedPackages:e,summary:r,status:t.status,measured:t.status==="complete",packagesChecked:t.packagesChecked,uncheckedPackages:t.uncheckedPackages,...t.error?{error:t.error}:{}}}mapToOSVEcosystem(t){return{npm:"npm",pip:"PyPI",maven:"Maven",nuget:"NuGet",cargo:"crates.io"}[t]}mapParsedVulnerability(t,e){let r=t.fixedVersions[0],i={file:e.ecosystem==="pip"?"requirements.txt":"package.json",dependency:e},n={description:r?`Upgrade ${e.name} to version ${r} or higher`:`Review and address vulnerability in ${e.name}`,fixExample:r?`"${e.name}": "^${r}"`:void 0,estimatedEffort:r?"trivial":"moderate",automatable:!!r};return{id:w(),cveId:t.cveIds[0],title:t.summary||`Vulnerability in ${e.name}`,description:t.details||t.summary||"No description available",severity:t.severity==="unknown"?"medium":t.severity,category:this.categorizeVulnerability({summary:t.summary,details:t.details}),location:i,remediation:n,references:t.references}}categorizeVulnerability(t){let e=(t.summary||"").toLowerCase(),r=(t.details||"").toLowerCase(),i=`${e} ${r}`;return i.includes("injection")||i.includes("sql")?"injection":i.includes("xss")||i.includes("cross-site scripting")?"xss":i.includes("authentication")||i.includes("auth bypass")?"broken-auth":i.includes("sensitive data")||i.includes("exposure")?"sensitive-data":i.includes("xxe")||i.includes("xml external")?"xxe":i.includes("access control")||i.includes("authorization")?"access-control":i.includes("deseriali")?"insecure-deserialization":(i.includes("prototype pollution")||i.includes("dependency"),"vulnerable-components")}async checkOutdated(t){let e=await this.getLatestVersion(t.name,t.ecosystem);return e!=="unknown"&&e!==t.version?{name:t.name,currentVersion:t.version,latestVersion:e,updateType:this.determineUpdateType(t.version,e)}:null}async queryVulnerabilityDatabase(t,e,r){let i=await this.checkDependencyAdvisories([{name:t,version:e,ecosystem:r}]);if(i.status!=="complete")throw new Error(i.error??`Dependency advisories could not be checked for ${t}@${e}`);return i.vulnerabilities}async getLatestVersion(t,e){try{if(e==="npm"){let r=await ms(`https://registry.npmjs.org/${encodeURIComponent(t)}/latest`);if(r.ok&&r.data.version)return r.data.version}else if(e==="pip"){let r=await ms(`https://pypi.org/pypi/${encodeURIComponent(t)}/json`);if(r.ok&&r.data.info?.version)return r.data.info.version}}catch(r){Dt.error(`Failed to get latest version for ${t}:`,r instanceof Error?r:void 0)}return"unknown"}async checkDeprecation(t,e){try{if(e==="npm"){let r=await ms(`https://registry.npmjs.org/${encodeURIComponent(t)}/latest`);if(r.ok&&r.data.deprecated)return!0}}catch(r){Dt.error(`Failed to check deprecation for ${t}:`,r instanceof Error?r:void 0)}return!1}determineUpdateType(t,e){let r=t.split(".").map(Number),i=e.split(".").map(Number);return i[0]>r[0]?"major":i[1]>r[1]?"minor":"patch"}hasBreakingChanges(t,e){let r=parseInt(t.split(".")[0]);return parseInt(e.split(".")[0])>r}createDependencySummary(t,e){let r=0,i=0,n=0,s=0,a=0;for(let o of t)switch(o.severity){case"critical":r++;break;case"high":i++;break;case"medium":n++;break;case"low":s++;break;case"informational":a++;break}return{critical:r,high:i,medium:n,low:s,informational:a,totalFiles:e,scanDurationMs:0}}shouldExclude(t){return this.config.excludePatterns.some(e=>e.startsWith("*")?t.endsWith(e.slice(1)):t.includes(e))}async performDependencyScan(){let t=Date.now(),e=[],r=ps.join(process.cwd(),"package.json");try{let{dependencies:i,preUnchecked:n}=await this.parseDependenciesForScan(r,"npm"),s=await this.checkDependencyAdvisories(i,n);for(let o of i){let l=await this.checkOutdated(o);l&&e.push(l)}let a=this.createDependencySummary(s.vulnerabilities,i.length);return this.toDependencyScanResult(s,e,{...a,scanDurationMs:Date.now()-t})}catch(i){return Dt.error("Dependency scan failed:",i instanceof Error?i:void 0),{vulnerabilities:[],outdatedPackages:[],summary:{critical:0,high:0,medium:0,low:0,informational:0,totalFiles:0,scanDurationMs:Date.now()-t},status:"failed",measured:!1,packagesChecked:0,uncheckedPackages:[],error:`Dependency scan of ${r} failed: ${y(i).message}`}}}async performSecretScan(){let t=[],e=0;try{let r=await this.findSourceFiles(process.cwd());for(let i of r){if(this.shouldExclude(i))continue;e++;let s=await Qd({value:i});t.push(...s)}}catch(r){Dt.error("Secret scan failed:",r instanceof Error?r:void 0)}return{secretsFound:t,filesScanned:e}}async findSourceFiles(t,e=[]){let r=[".ts",".js",".tsx",".jsx",".json",".env",".yaml",".yml",".config"];try{let i=await Pv.readdir(t,{withFileTypes:!0});for(let n of i){let s=ps.join(t,n.name);if(!this.shouldExclude(s)){if(n.isDirectory())await this.findSourceFiles(s,e);else if(n.isFile()){let a=ps.extname(n.name).toLowerCase();(r.includes(a)||n.name.startsWith(".env"))&&e.push(s)}}}}catch{Dt.debug("Directory read error:")}return e}async getRecentAudits(){let t=await this.memory.search("security:audit:*",10),e=[];for(let r of t){let i=await this.memory.get(r);i&&e.push(i)}return e.sort((r,i)=>new Date(i.timestamp).getTime()-new Date(r.timestamp).getTime())}async countResolvedLastWeek(){try{let t=await this.getRecentAudits();if(t.length<2)return 0;let e=new Date(Date.now()-10080*60*1e3),r=t.filter(o=>new Date(o.timestamp)>=e);if(r.length<2)return 0;let i=r[r.length-1],n=r[0],s=Mi(i),a=Mi(n);return Math.max(0,s-a)}catch(t){return Dt.error("Failed to count resolved vulnerabilities:",t instanceof Error?t:void 0),0}}async calculateAverageResolutionTime(){try{let t=await this.getRecentAudits();if(t.length<2)return 72;let e=new Map,r=[],i=[...t].reverse();for(let s of i){let a=new Set;s.sastResults&&s.sastResults.vulnerabilities.forEach(o=>a.add(o.id)),s.dastResults&&s.dastResults.vulnerabilities.forEach(o=>a.add(o.id)),s.dependencyResults&&s.dependencyResults.vulnerabilities.forEach(o=>a.add(o.id));for(let o of a)e.has(o)||e.set(o,s.timestamp);for(let[o,l]of e)if(!a.has(o)){let u=(s.timestamp.getTime()-l.getTime())/36e5;r.push(u),e.delete(o)}}if(r.length===0)return 72;let n=r.reduce((s,a)=>s+a,0);return Math.round(n/r.length)}catch(t){return Dt.error("Failed to calculate average resolution time:",t instanceof Error?t:void 0),72}}};k();var Zx={customStandards:[],strictMode:!1,includeRecommended:!0,evidenceRetentionDays:365},eP={id:"gdpr",name:"General Data Protection Regulation",version:"2018",rules:[{id:"gdpr-art5-accuracy",title:"Data Accuracy",description:"Personal data must be accurate and kept up to date",category:"data-quality",severity:"required",checkType:"manual"},{id:"gdpr-art17-erasure",title:"Right to Erasure",description:"Data subjects have the right to request deletion of their data",category:"data-rights",severity:"required",checkType:"static"},{id:"gdpr-art25-privacy-design",title:"Privacy by Design",description:"Data protection must be built into systems from the start",category:"architecture",severity:"required",checkType:"static"},{id:"gdpr-art32-security",title:"Security of Processing",description:"Appropriate security measures must protect personal data",category:"security",severity:"required",checkType:"static"},{id:"gdpr-art33-breach-notification",title:"Breach Notification",description:"Data breaches must be reported within 72 hours",category:"incident-response",severity:"required",checkType:"manual"}]},tP={id:"hipaa",name:"Health Insurance Portability and Accountability Act",version:"1996-amended",rules:[{id:"hipaa-164.312-access",title:"Access Control",description:"Implement technical policies for ePHI access",category:"access-control",severity:"required",checkType:"static"},{id:"hipaa-164.312-audit",title:"Audit Controls",description:"Implement hardware, software, and procedural audit mechanisms",category:"audit",severity:"required",checkType:"static"},{id:"hipaa-164.312-integrity",title:"Integrity Controls",description:"Protect ePHI from improper alteration or destruction",category:"data-integrity",severity:"required",checkType:"static"},{id:"hipaa-164.312-transmission",title:"Transmission Security",description:"Protect ePHI during electronic transmission",category:"encryption",severity:"required",checkType:"static"},{id:"hipaa-164.314-baa",title:"Business Associate Agreements",description:"Ensure contracts with business associates protect PHI",category:"contracts",severity:"required",checkType:"manual"}]},rP={id:"soc2",name:"SOC 2 Type II",version:"2017",rules:[{id:"soc2-cc6.1",title:"Logical Access Security",description:"Security software, infrastructure, and architectures are implemented",category:"security",severity:"required",checkType:"static"},{id:"soc2-cc6.2",title:"Access Controls",description:"Registration and authorization of new users",category:"access-control",severity:"required",checkType:"static"},{id:"soc2-cc6.6",title:"Encryption",description:"Logical access security measures to protect data",category:"encryption",severity:"required",checkType:"static"},{id:"soc2-cc7.1",title:"System Monitoring",description:"Detect and respond to security incidents",category:"monitoring",severity:"required",checkType:"static"},{id:"soc2-cc8.1",title:"Change Management",description:"Changes to infrastructure are authorized and tested",category:"change-management",severity:"required",checkType:"manual"}]},iP={id:"pci-dss",name:"Payment Card Industry Data Security Standard",version:"4.0",rules:[{id:"pci-req1",title:"Network Security Controls",description:"Install and maintain network security controls",category:"network-security",severity:"required",checkType:"static"},{id:"pci-req3",title:"Protect Account Data",description:"Protect stored account data",category:"data-protection",severity:"required",checkType:"static"},{id:"pci-req4",title:"Encrypt Transmissions",description:"Protect cardholder data with strong cryptography during transmission",category:"encryption",severity:"required",checkType:"static"},{id:"pci-req6",title:"Secure Development",description:"Develop and maintain secure systems and software",category:"secure-sdlc",severity:"required",checkType:"static"},{id:"pci-req10",title:"Log and Monitor Access",description:"Log and monitor all access to system components",category:"logging",severity:"required",checkType:"static"}]},nP=[eP,tP,rP,iP],Vr=class{constructor(t,e={}){this.memory=t;this.config={...Zx,...e},this.patternAnalyzer=Td(),this.standards=new Map;for(let r of nP)this.standards.set(r.id,r);for(let r of this.config.customStandards)this.standards.set(r.id,r)}memory;config;standards;patternAnalyzer;async validate(t,e){try{let r=[],i=[],n=[],s=this.config.includeRecommended?t.rules:t.rules.filter(u=>u.severity==="required");for(let u of s){if(u.checkType==="manual"){n.push(u.id);continue}let d=await this.checkRule(u,e);d.passed?i.push(u.id):r.push(...d.violations)}let a=s.length-n.length,o=a>0?Math.round(i.length/a*100):100,l={standardId:t.id,standardName:t.name,violations:r,passedRules:i,skippedRules:n,complianceScore:o,generatedAt:new Date};return await this.storeReport(l),f(l)}catch(r){return g(y(r))}}async getAvailableStandards(){return Array.from(this.standards.values())}async analyzeGaps(t,e){try{let r=[],i=[],n=new Set(t.violations.map(u=>u.ruleId)),s=new Set(t.passedRules);for(let u of e.rules)n.has(u.id)?r.push({ruleId:u.id,currentStatus:"failed",effort:this.estimateEffort(u),impact:u.severity==="required"?"high":"medium"}):s.has(u.id)||r.push({ruleId:u.id,currentStatus:"not-implemented",effort:this.estimateEffort(u),impact:u.severity==="required"?"high":"low"});let a=[...r].sort((u,d)=>{let m={high:0,medium:1,low:2},p={trivial:0,minor:1,moderate:2,major:3},h=m[u.impact]*10+p[u.effort],v=m[d.impact]*10+p[d.effort];return h-v});for(let u=0;u<a.length;u++){let d=a[u],m=e.rules.find(p=>p.id===d.ruleId);i.push({id:w(),description:`Implement ${m?.title||d.ruleId}`,affectedRules:[d.ruleId],effort:d.effort,priority:u+1})}let o=100,l=t.complianceScore;return f({currentScore:l,targetScore:o,gaps:r,prioritizedActions:i})}catch(r){return g(y(r))}}async validateMultiple(t,e){try{let r=[],i=[];for(let a of t){let o=await this.validate(a,e);o.success&&r.push(o.value)}let n=new Map;for(let a of r)for(let o of a.violations){let l=`${o.location.file}:${o.location.line}`;n.set(l,(n.get(l)||0)+1)}for(let a of r)for(let o of a.violations){let l=`${o.location.file}:${o.location.line}`;(n.get(l)||0)>1&&(i.some(u=>u.location.file===o.location.file&&u.location.line===o.location.line)||i.push(o))}let s=r.length>0?Math.round(r.reduce((a,o)=>a+o.complianceScore,0)/r.length):0;return f({reports:r,overallScore:s,crossCuttingViolations:i})}catch(r){return g(y(r))}}async checkDataHandling(t,e){try{let r=new Map,i=[],n=[];for(let s of e)r.set(s,[]);for(let s of t){let a=await this.scanFileForDataTypes(s,e);for(let o of a){let l=r.get(o.type)||[];l.push(o.location),r.set(o.type,l);let u=this.checkDataTypeViolation(o);u&&i.push(u)}}for(let[s,a]of r)a.length>0&&n.push(...this.getDataTypeRecommendations(s,a.length));return f({dataTypesFound:r,violations:i,recommendations:[...new Set(n)]})}catch(r){return g(y(r))}}async generateEvidence(t,e){try{let r=this.standards.get(t);if(!r)return g(new Error(`Unknown standard: ${t}`));let i=await this.validate(r,e);if(!i.success)return g(i.error);let n=i.value,s=[];for(let o of r.rules){let l=n.passedRules.includes(o.id)?"implemented":n.skippedRules.includes(o.id)?"partial":"not-implemented";s.push({controlId:o.id,status:l,evidence:await this.collectEvidence(o,e),lastVerified:new Date})}let a={standardId:t,controls:s,generatedAt:new Date,validUntil:new Date(Date.now()+this.config.evidenceRetentionDays*24*60*60*1e3)};return await this.memory.set(`compliance:evidence:${t}:${Date.now()}`,a,{namespace:"security-compliance",persist:!0}),f(a)}catch(r){return g(y(r))}}async checkRule(t,e){let r=[],i=await this.getFilesFromContext(e);switch(t.category){case"encryption":r.push(...await this.checkEncryption(t,e,i));break;case"access-control":r.push(...await this.checkAccessControl(t,e,i));break;case"audit":case"logging":r.push(...await this.checkLogging(t,e,i));break;case"data-protection":case"data-quality":r.push(...await this.checkDataProtection(t,e,i));break;case"security":r.push(...await this.checkSecurityControls(t,e,i));break;default:break}return{passed:r.length===0,violations:r}}async getFilesFromContext(t){let e=[],r=t.projectRoot.value;if(t.includePatterns.length===0)return[];for(let i of t.includePatterns)t.excludePatterns.some(s=>i.includes(s)||s.includes(i))||e.push(`${r}/${i}`);return e}async checkEncryption(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeEncryption(r);for(let s of n.weakCrypto)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Weak or deprecated cryptographic algorithm detected",remediation:"Use strong encryption algorithms (AES-256, SHA-256 or higher)"});for(let s of n.unencryptedDataHandling)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Sensitive data handled without encryption verification",remediation:"Ensure data is encrypted before processing sensitive information"});return i}async checkAccessControl(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeAccessControl(r);for(let s of n.unprotectedRoutes)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Sensitive endpoint potentially missing authorization middleware",remediation:"Add authorization check before sensitive operations"});for(let s of n.hardcodedCredentials)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Hardcoded credentials detected",remediation:"Use environment variables or secure secret management"});return i}async checkLogging(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeLogging(r);for(let s of n.sensitiveOperationsWithoutLogging)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Sensitive operation without audit logging",remediation:"Add audit log entry for data modification operations"});for(let s of n.sensitiveDataInLogs)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Sensitive data being logged",remediation:"Remove or mask sensitive data before logging"});return i}async checkDataProtection(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeDataProtection(r);for(let s of n.unmaskedPii)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"PII field without masking or encryption decorator",remediation:"Apply data protection decorators to sensitive fields"});for(let s of n.missingValidation)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Data fields without input validation",remediation:"Add input validation for all data fields, especially PII"});return i}async checkSecurityControls(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeSecurityControls(r);for(let s of n.missingControls)i.push({ruleId:t.id,ruleName:t.title,location:{file:"project-wide",line:0,snippet:`Missing: ${s}`},details:`Security control not detected: ${s}`,remediation:`Implement ${s} to enhance security posture`});for(let s of n.vulnerabilities)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Security vulnerability detected",remediation:"Review and fix the security issue"});return i}estimateEffort(t){let e=["architecture","data-rights","incident-response"],r=["access-control","encryption","change-management"];return e.includes(t.category)?"major":r.includes(t.category)||t.checkType==="manual"?"moderate":"minor"}async scanFileForDataTypes(t,e){let r=[],i=await this.patternAnalyzer.scanForDataTypes([t.value],e);for(let n of e){let s=i.get(n)||[];for(let a of s)r.push({type:n,location:{file:a.file,line:a.line,context:a.snippet||this.getDataTypeContext(n)}})}return r}getDataTypeContext(t){return{pii:"User personal information field",phi:"Health-related data field",financial:"Payment/financial data field",credentials:"Authentication credential field",biometric:"Biometric data field"}[t]}checkDataTypeViolation(t){let e=t.location.context.toLowerCase(),i=[/encrypt/i,/hash/i,/mask/i,/redact/i,/validate/i,/sanitize/i,/bcrypt/i,/argon2/i,/aes/i].some(a=>a.test(e)),s=[/console\.(log|debug|info)/i,/JSON\.stringify/i,/\.toString\(\)/i,/plaintext/i,/unencrypted/i].some(a=>a.test(e));if(!i||s){let a={pii:"gdpr-art32-security",phi:"hipaa-164.312-transmission",financial:"pci-req3",credentials:"soc2-cc6.6",biometric:"gdpr-art9-special"},o={file:t.location.file,line:t.location.line,snippet:t.location.context},l=s?"Potentially exposed in logs or serialization":"No protective measures detected";return{ruleId:a[t.type],ruleName:`${t.type.toUpperCase()} Data Protection`,location:o,details:`${t.type.toUpperCase()} data found: ${l}`,remediation:`Apply appropriate security controls for ${t.type} data`}}return null}getDataTypeRecommendations(t,e){let r=`Found ${e} ${t.toUpperCase()} data locations`;return{pii:[r,"Implement data minimization principles","Ensure consent mechanisms are in place","Add data retention policies"],phi:[r,"Verify HIPAA safeguards are implemented","Ensure business associate agreements are in place","Implement minimum necessary access"],financial:[r,"Verify PCI-DSS compliance for payment data","Implement tokenization where possible","Ensure proper key management"],credentials:[r,"Use secure credential storage (vaults)","Implement credential rotation","Avoid hardcoded credentials"],biometric:[r,"Implement enhanced protection measures","Obtain explicit consent","Consider data localization requirements"]}[t]}async collectEvidence(t,e){let r=[],i=await this.getFilesFromContext(e);if(t.checkType==="static"&&i.length>0){switch(t.category){case"encryption":{let n=await this.patternAnalyzer.analyzeEncryption(i);n.hasEncryption&&r.push(`Encryption detected: ${n.encryptionLibraries.join(", ")||"standard crypto"}`),n.weakCrypto.length>0&&r.push(`Weak crypto found in ${n.weakCrypto.length} location(s)`),r.push(`Unencrypted data handling: ${n.unencryptedDataHandling.length} instance(s)`);break}case"access_control":{let n=await this.patternAnalyzer.analyzeAccessControl(i);r.push(`Auth middleware: ${n.hasAuthMiddleware?"present":"not found"}`),r.push(`Unprotected routes: ${n.unprotectedRoutes.length}`),r.push(`Hardcoded credentials: ${n.hardcodedCredentials.length}`);break}case"logging":{let n=await this.patternAnalyzer.analyzeLogging(i);r.push(`Audit logging: ${n.hasAuditLogging?"implemented":"not found"}`),r.push(`Sensitive data in logs: ${n.sensitiveDataInLogs.length} instance(s)`);break}case"data_protection":{let n=await this.patternAnalyzer.analyzeDataProtection(i);r.push(`PII fields detected: ${n.piiFields.length}`),r.push(`Unmasked PII: ${n.unmaskedPii.length} instance(s)`),r.push(`Missing validation: ${n.missingValidation.length} field(s)`);break}default:r.push(`Static analysis completed for ${t.category}`),r.push(`Code patterns reviewed: ${t.title}`)}r.push(`Files analyzed: ${i.length}`)}else t.checkType==="dynamic"?(r.push(`Dynamic check required for: ${t.title}`),r.push("Evidence collection pending dynamic analysis")):t.checkType==="manual"&&(r.push(`Manual verification required for: ${t.title}`),r.push(`Review scope: ${e.projectRoot.value}`));return r.push(`Rule ${t.id} verified at ${new Date().toISOString()}`),r}async storeReport(t){await this.memory.set(`compliance:report:${t.standardId}:${Date.now()}`,t,{namespace:"security-compliance",persist:!0})}};var sP={stateSize:10,actionSize:5,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0},dc=class extends ve{qNetwork;targetNetwork;replayBufferClass;dqnConfig;updateCount=0;actions=[];constructor(t={}){super("dqn","value-based"),this.dqnConfig={...sP,...t},this.initializeActions(),this.qNetwork=new J({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass=new At(this.config.replayBufferSize,!1)}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.targetNetwork.forward(e),i=this.argmax(r),n=this.actions[i];return{action:n,confidence:.7,value:r[i],reasoning:`DQN: ${n.type}`}}async trainCore(t){for(let i of t)this.replayBufferClass.add(i);if(!this.replayBufferClass.isReady(this.dqnConfig.minReplaySize))return this.getStats();let e=this.replayBufferClass.sample(this.config.batchSize),r=0;for(let i of e){let n=this.prepareState(i.state),s=this.prepareState(i.nextState),a=this.actionToIndex(i.action),o=this.qNetwork.forward(n),l;if(this.dqnConfig.doubleDQN&&!i.done){let d=this.qNetwork.forward(s),m=this.argmax(d),p=this.targetNetwork.forward(s);l=i.reward+this.config.discountFactor*p[m]}else{let d=this.targetNetwork.forward(s);l=i.reward+this.config.discountFactor*Math.max(...d)*(i.done?0:1)}let u=new Float32Array(o.length);for(let d=0;d<u.length;d++)u[d]=d===a?l:o[d];r+=Math.abs(this.qNetwork.train(n,u,new Fe))}return this.updateCount++,this.updateCount%this.dqnConfig.targetUpdateFreq===0&&(this.targetNetwork=this.qNetwork.clone()),{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/e.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural DQN for Parallel Execution Scheduling",capabilities:["Experience replay","Target network","Double DQN"],hyperparameters:{stateSize:this.dqnConfig.stateSize,actionSize:this.dqnConfig.actionSize,hiddenLayers:this.dqnConfig.hiddenLayers.join(",")},stats:this.stats}}prepareState(t){let e=t.features.slice(0,this.dqnConfig.stateSize);for(;e.length<this.dqnConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]/=r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"parallelize",value:2},{type:"parallelize",value:4},{type:"parallelize",value:8},{type:"sequential",value:1},{type:"skip",value:0}],this.dqnConfig.actionSize=this.actions.length,this.qNetwork=new J({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone()}actionToIndex(t){let e=`${t.type}:${JSON.stringify(t.value)}`;for(let r=0;r<this.actions.length;r++)if(`${this.actions[r].type}:${JSON.stringify(this.actions[r].value)}`===e)return r;return 0}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}async exportCustomData(){return{qNetwork:this.qNetwork.getParameters(),targetNetwork:this.targetNetwork.getParameters(),dqnConfig:this.dqnConfig,updateCount:this.updateCount}}async importCustomData(t){t.qNetwork&&this.qNetwork.setParameters(t.qNetwork),t.targetNetwork&&this.targetNetwork.setParameters(t.targetNetwork),t.dqnConfig&&(this.dqnConfig={...this.dqnConfig,...t.dqnConfig}),typeof t.updateCount=="number"&&(this.updateCount=t.updateCount),this.initialized=!0}async resetAlgorithm(){this.qNetwork=new J({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass.clear(),this.updateCount=0}};var aP={maxConcurrentWorkflows:3,defaultTimeout:3e5,publishEvents:!0,autoTriageVulnerabilities:!0,riskThreshold:.7,enableDQN:!0,enableFlashAttention:!0,enableConsensus:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},de=x.create("security-compliance"),gs=class extends ie{constructor(e,r,i,n={},s){let a={...aP,...n};super(e,"security-compliance",a,{verifyFindingTypes:["security-vulnerability","compliance-violation","credential-exposure"],...a.consensusMixinConfig});this.memory=r;this.agentCoordinator=i;this.securityGovernanceMixin=Np(this.domainName),this.securityScanner=new dt({memory:r,llmRouter:s}),this.securityAuditor=new _r(r),this.complianceValidator=new Vr(r)}memory;agentCoordinator;securityScanner;securityAuditor;complianceValidator;dqnAlgorithm;flashAttention;rlInitialized=!1;consensusEngine;securityGovernanceMixin;async onInitialize(){this.subscribeToEvents(),await this.loadWorkflowState(),(this.config.enableDQN||this.config.enableFlashAttention||this.config.enableConsensus)&&await this.initializeRLIntegrations()}async initializeRLIntegrations(){try{if(this.config.enableDQN&&(this.dqnAlgorithm=new dc({stateSize:8,actionSize:5,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0})),this.config.enableFlashAttention){let e="test-similarity";this.flashAttention=await tt(e,{dim:384,strategy:"flash",numHeads:8})}if(this.config.enableConsensus){let r=xr(!0).getAll();r.length>0?(this.consensusEngine=In({strategy:"weighted",models:r,engineConfig:{minModels:Math.min(2,r.length),defaultModelTimeout:6e4,...this.config.consensusEngineConfig}}),de.info(`Multi-Model Consensus initialized with ${r.length} providers`)):de.warn("No model providers available for consensus verification")}this.rlInitialized=!0}catch(e){throw de.error("Failed to initialize RL integrations:",e instanceof Error?e:void 0),e}}async onDispose(){await this.saveWorkflowState()}getActiveWorkflows(){return super.getActiveWorkflows()}async runSecurityAudit(e){let r=w();try{if(this.startWorkflow(r,"audit"),this.detectAuthCodeInScope(e)&&this.securityGovernanceMixin.isGovernanceEnabled()&&!(await this.securityGovernanceMixin.validateSecurityScanRequired(r,!0,void 0)).allowed&&this.securityGovernanceMixin.isStrictMode()&&de.info("Security audit for auth code registered with governance"),this.minCutMixin.shouldPauseOperations())return de.warn("Security audit paused: topology is in critical state"),this.failWorkflow(r,"Topology is in critical state"),g(new Error("Security audit paused: topology is in critical state"));if(this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&de.warn("Topology degraded, using conservative audit strategy"),!this.agentCoordinator.canSpawn())return g(new Error("Agent limit reached, cannot spawn security audit agents"));let n=await this.spawnSecurityAuditAgent(r,e);if(!n.success)return this.failWorkflow(r,n.error.message),g(n.error);this.addAgentToWorkflow(r,n.value);let s=e.tests||[];this.config.enableDQN&&this.dqnAlgorithm&&s.length>0&&(s=await this.prioritizeSecurityTests(e,s));let a={...e},o=await this.securityAuditor.runAudit(a);if(o.success){this.completeWorkflow(r);let l=this.extractVulnerabilitiesFromReport(o.value);this.config.enableFlashAttention&&this.flashAttention&&l.length>0&&await this.enhanceVulnerabilityAnalysis(l),this.config.enableDQN&&this.dqnAlgorithm&&await this.trainDQNWithAuditFeedback(e,o.value),this.config.publishEvents&&await this.publishSecurityAuditCompleted(o.value)}else this.failWorkflow(r,o.error.message);return await this.agentCoordinator.stop(n.value),o}catch(i){let n=y(i);return this.failWorkflow(r,n.message),{success:!1,error:n}}}async runSecurityScan(e,r){let i=w();try{if(this.startWorkflow(i,"scan"),this.minCutMixin.shouldPauseOperations())return de.warn("Security scan paused: topology is in critical state"),this.failWorkflow(i,"Topology is in critical state"),g(new Error("Security scan paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&de.warn("Topology degraded, proceeding with conservative scan strategy");let n;return r==="sast"?n=await this.securityScanner.scanFiles(e):r==="dast"?n=await this.securityScanner.scanUrl(e[0]?.value??""):n=await this.securityScanner.scanFiles(e),n.success?this.completeWorkflow(i):this.failWorkflow(i,n.error.message),n}catch(n){let s=y(n);return this.failWorkflow(i,s.message),{success:!1,error:s}}}async runComplianceValidation(e,r){let i=w();try{if(this.startWorkflow(i,"compliance"),this.minCutMixin.shouldPauseOperations())return de.warn("Compliance validation paused: topology is in critical state"),this.failWorkflow(i,"Topology is in critical state"),g(new Error("Compliance validation paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&de.warn("Topology degraded, proceeding with compliance validation");let s=(await this.complianceValidator.getAvailableStandards()).find(o=>o.id===e);if(!s)return g(new Error(`Unknown compliance standard: ${e}`));let a=await this.complianceValidator.validate(s,r);return a.success?(this.completeWorkflow(i),this.config.publishEvents&&await this.publishComplianceValidationCompleted(a.value)):this.failWorkflow(i,a.error.message),a}catch(n){let s=y(n);return this.failWorkflow(i,s.message),{success:!1,error:s}}}async assessSecurityPosture(){let e=w();try{if(this.startWorkflow(e,"posture"),this.minCutMixin.shouldPauseOperations())return de.warn("Security posture assessment paused: topology is in critical state"),this.failWorkflow(e,"Topology is in critical state"),g(new Error("Security posture assessment paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&de.warn("Topology degraded, proceeding with security posture assessment");let r=await this.securityAuditor.getSecurityPosture();if(r.success){this.completeWorkflow(e);let i={overallScore:r.value.overallScore,trend:r.value.trend,criticalVulnerabilities:r.value.criticalIssues,complianceStatus:new Map,lastAuditDate:r.value.lastAuditDate};return f(i)}else return this.failWorkflow(e,r.error.message),r}catch(r){let i=y(r);return this.failWorkflow(e,i.message),{success:!1,error:i}}}async runComplianceCheck(e){let r={projectRoot:he.create("."),includePatterns:["**/*.ts","**/*.js"],excludePatterns:["node_modules/**"]};return this.runComplianceValidation(e,r)}async getSecurityPosture(){return this.assessSecurityPosture()}async prioritizeSecurityTests(e,r){if(!this.dqnAlgorithm||!this.rlInitialized)return r;try{let i=await Promise.all(r.map(async n=>{let s={id:`test-${n}`,features:this.extractSecurityTestFeatures(e,n)},a=await this.dqnAlgorithm.predict(s);return{test:n,score:a.value||0}}));return i.sort((n,s)=>s.score-n.score),i.map(n=>n.test)}catch(i){return de.error("Failed to prioritize security tests:",i instanceof Error?i:void 0),r}}async trainDQNWithAuditFeedback(e,r){if(!(!this.dqnAlgorithm||!this.rlInitialized))try{let i=this.extractVulnerabilitiesFromReport(r),n={id:`audit-${r.auditId}-${Date.now()}`,features:this.extractAuditFeatures(e)},s={type:"run-audit",value:i.length},a=this.calculateAuditReward(r),o={state:n,action:s,reward:a,nextState:n,done:!0,timestamp:new Date};await this.dqnAlgorithm.train(o),de.info(`Trained security audit with reward: ${a.toFixed(3)}`)}catch(i){de.error("Failed to train DQN:",i instanceof Error?i:void 0)}}calculateAuditReward(e){let r=this.extractVulnerabilitiesFromReport(e);if(r.length===0)return .5;let i=.5,n=r.filter(a=>a.severity==="critical").length;i+=Math.min(.3,n*.1);let s=r.filter(a=>a.severity==="high").length;return i+=Math.min(.2,s*.05),i+=(e.overallRiskScore?.value??0)*.1,Math.max(0,Math.min(1,i))}extractSecurityTestFeatures(e,r){let i=e.targetUrl??"";return[i.includes("/api")?1:0,i.startsWith("http")?1:0,e.includeSAST?1:0,r.includes("auth")?1:0,r.includes("sql")?1:0,r.includes("xss")?1:0,r.includes("injection")?1:0,r.length/100]}extractAuditFeatures(e){let r=e.depth??"standard",i=r==="deep"?1:r==="standard"?.5:.25;return[e.includeSAST?1:0,e.includeDAST?1:0,i,(e.scanTypes?.length??0)/4,e.includeDependencies?1:0,e.includeSecrets?1:0,(e.complianceFrameworks?.length??0)/5,e.targetUrl?1:0]}async enhanceVulnerabilityAnalysis(e){if(!(!this.flashAttention||!this.rlInitialized||e.length===0))try{let r=e.map(u=>this.createVulnerabilityEmbedding(u)),i=r.length,n=r[0].length,s=new Float32Array(i*n),a=new Float32Array(i*n),o=new Float32Array(i*n);for(let u=0;u<i;u++)s.set(r[u],u*n),a.set(r[u],u*n),o.set(r[u],u*n);let l=await this.flashAttention.computeFlashAttention(s,a,o,i,n);for(let u=0;u<e.length;u++){let d=Array.from(l.slice(u*n,(u+1)*n));r[u].reduce((p,h,v)=>p+h*d[v],0)>.7&&de.info(`High self-attention for vulnerability ${e[u].id}`)}}catch(r){de.error("Failed to enhance vulnerability analysis:",r instanceof Error?r:void 0)}}createVulnerabilityEmbedding(e){let r=[],i=this.hashCode(e.category);r.push(i%1e3/1e3);let n={critical:1,high:.75,medium:.5,low:.25,informational:.1};r.push(n[e.severity]||.5);let s=this.hashCode(e.title);r.push(s%1e3/1e3),r.push(Math.min(1,e.description.length/500));let a=e.cveId?this.hashCode(e.cveId):0;r.push(a%1e3/1e3);let o=this.hashCode(e.description.slice(0,200));for(let l=r.length;l<384;l++)r.push(o*(l+1)%1e4/1e4);return r.slice(0,384)}hashCode(e){let r=0;for(let i=0;i<e.length;i++)r=(r<<5)-r+e.charCodeAt(i),r=r|0;return Math.abs(r)}async spawnSecurityAuditAgent(e,r){let i={name:`security-auditor-${e.slice(0,8)}`,domain:"security-compliance",type:"auditor",capabilities:["security-audit","vulnerability-scanning","compliance-check"],config:{workflowId:e,targetUrl:r.targetUrl,depth:r.depth}};return this.agentCoordinator.spawn(i)}extractVulnerabilitiesFromReport(e){let r=[];return e.sastResults?.vulnerabilities&&r.push(...e.sastResults.vulnerabilities),e.dastResults?.vulnerabilities&&r.push(...e.dastResults.vulnerabilities),e.dependencyResults?.vulnerabilities&&r.push(...e.dependencyResults.vulnerabilities),r}async publishSecurityAuditCompleted(e){let r=this.extractVulnerabilitiesFromReport(e),i=await this.verifyHighSeverityFindings(r);for(let n of i){let s={vulnId:n.id,cve:n.cveId,severity:n.severity,file:n.location.file,line:n.location.line,description:n.description,remediation:n.remediation.description},a=N(zc.SecurityAuditCompleted,"security-compliance",s);await this.eventBus.publish(a)}}async verifyHighSeverityFindings(e){if(!this.config.enableConsensus)return e;if(!this.isConsensusAvailable())return this.consensusEngine?this.verifyHighSeverityFindingsLegacy(e):e;let r=[],i=e.filter(a=>a.severity==="critical"||a.severity==="high"),n=e.filter(a=>a.severity!=="critical"&&a.severity!=="high");r.push(...n);for(let a of i)try{let o=U({id:a.id,type:"security-vulnerability",confidence:.8,description:`${a.title}: ${a.description}`,payload:{vulnerability:a,location:a.location},detectedBy:"security-scanner",severity:a.severity,context:{domain:this.domainName,cveId:a.cveId,category:a.category}});if(!this.consensusMixin.requiresConsensus(o)){r.push(a);continue}let l=await this.consensusMixin.verifyFinding(o);l.success&&l.value.verdict==="verified"?(de.info(`Consensus VERIFIED: ${a.title} (confidence: ${(l.value.confidence*100).toFixed(1)}%)`),r.push(a)):l.success&&l.value.verdict==="disputed"?(de.info(`Consensus DISPUTED: ${a.title} - including with lower confidence`),r.push(a)):de.info(`Consensus REJECTED: ${a.title} - likely false positive`)}catch{de.warn(`Consensus error verifying ${a.title}, including by default:`),r.push(a)}let s=i.length-r.filter(a=>a.severity==="critical"||a.severity==="high").length;return s>0&&de.info(`Consensus filtered out ${s} likely false positive(s)`),r}async verifyHighSeverityFindingsLegacy(e){if(!this.consensusEngine)return e;let r=[],i=e.filter(s=>s.severity==="critical"||s.severity==="high"),n=e.filter(s=>s.severity!=="critical"&&s.severity!=="high");r.push(...n);for(let s of i)try{let a={id:s.id,type:s.category,description:s.description,category:s.category,severity:s.severity,location:{file:s.location.file,line:s.location.line,column:s.location.column},evidence:[{type:"code-snippet",content:s.location.snippet||s.description}],cveId:s.cveId,remediation:s.remediation.description,detectedAt:new Date,detectedBy:"security-scanner"},o=await this.consensusEngine.verify(a);(o.success&&o.value.verdict==="verified"||o.success&&o.value.verdict==="disputed")&&r.push(s)}catch{r.push(s)}return r}async publishComplianceValidationCompleted(e){let r={standard:e.standardId,passed:e.complianceScore>=.8,violations:e.violations.length,findings:e.violations.map(n=>n.details).slice(0,10)},i=N(zc.ComplianceValidated,"security-compliance",r);await this.eventBus.publish(i)}detectAuthCodeInScope(e){let r=[/auth/i,/login/i,/password/i,/token/i,/session/i,/oauth/i,/jwt/i,/credential/i,/identity/i];if(e.targetUrl){for(let i of r)if(i.test(e.targetUrl))return!0}if(e.scanTypes){let i=["authentication","authorization","session-management"];for(let n of e.scanTypes)if(i.includes(n.toLowerCase()))return!0}if(e.complianceFrameworks){let i=["soc2","pci-dss","hipaa","iso27001"];for(let n of e.complianceFrameworks)if(i.includes(n.toLowerCase()))return!0}return!1}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this))}async handleTestRunCompleted(e){}async handleImpactAnalysis(e){}async loadWorkflowState(){let e=await this.memory.get("security-compliance:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("security-compliance:coordinator:workflows",e,{namespace:"security-compliance",persist:!0})}getHealthyRoutingDomains(){return this.minCutMixin.getHealthyRoutingDomains()}};k();var mc=class extends te{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;securityScanner=null;securityAuditor=null;complianceValidator=null;pluginConfig;get name(){return"security-compliance"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{runSecurityAudit:this.runSecurityAudit.bind(this),getSecurityPosture:this.getSecurityPosture.bind(this),runSASTScan:this.runSASTScan.bind(this),runDASTScan:this.runDASTScan.bind(this),runDependencyScan:this.runDependencyScan.bind(this),triageVulnerabilities:this.triageVulnerabilities.bind(this),runComplianceCheck:this.runComplianceCheck.bind(this),getAvailableStandards:this.getAvailableStandards.bind(this),analyzeComplianceGaps:this.analyzeComplianceGaps.bind(this),getCoordinator:()=>this.coordinator,getSecurityScanner:()=>this.securityScanner,getSecurityAuditor:()=>this.securityAuditor,getComplianceValidator:()=>this.complianceValidator}}getTaskHandlers(){return new Map([["security-audit",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.target??e.targetUrl;return r?this.coordinator.runSecurityAudit({includeSAST:e.includeSAST??!0,includeDAST:e.includeDAST??!1,includeDependencies:e.includeDependencies??!0,includeSecrets:e.includeSecrets??!0,targetUrl:r}):g(new Error("Invalid security-audit payload: missing target"))}],["compliance-check",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.standardId;return r?this.coordinator.runComplianceCheck(r):g(new Error("Invalid compliance-check payload: missing standardId"))}],["sast-scan",async e=>{if(!this.securityScanner)return g(new Error("Security scanner not initialized"));let r=e.files;if(!r||r.length===0)return g(new Error("Invalid sast-scan payload: missing files"));if(r.some(s=>typeof s=="string"?s.trim()==="":!(s instanceof he)))return g(new Error("Invalid sast-scan payload: files must be non-empty file paths"));let{accepted:i,skipped:n}=await Uh(r.map(s=>typeof s=="string"?s:s.value));return n.length>0?g(new Error(`Invalid sast-scan payload: these files cannot be scanned: ${n.map(s=>`${s.path} (${s.reason})`).join(", ")}. Pass regular files inside the project, at most ${sd/(1024*1024)} MB each.`)):this.securityScanner.scanFiles(i.map(s=>he.create(s)))}],["dast-scan",async e=>{if(!this.securityScanner)return g(new Error("Security scanner not initialized"));let r=e.targetUrl;return r?this.securityScanner.scanUrl(r):g(new Error("Invalid dast-scan payload: missing targetUrl"))}],["triage-vulnerabilities",async e=>{if(!this.securityAuditor)return g(new Error("Security auditor not initialized"));let r=e.vulnerabilities;return!r||r.length===0?g(new Error("Invalid triage-vulnerabilities payload: missing vulnerabilities")):this.securityAuditor.triageVulnerabilities(r)}]])}async onInitialize(){this.securityScanner=new dt({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.securityScanner),this.securityAuditor=new _r(this.memory,this.pluginConfig.securityAuditor),this.complianceValidator=new Vr(this.memory,this.pluginConfig.complianceValidator),this.coordinator=new gs(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.securityScanner=null,this.securityAuditor=null,this.complianceValidator=null}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.KnowledgeGraphUpdated",this.handleKnowledgeGraphUpdate.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGateEvaluated.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"code-intelligence.KnowledgeGraphUpdated":await this.handleKnowledgeGraphUpdate(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGateEvaluated(e);break;default:break}}async runSecurityAudit(e){this.ensureInitialized();try{let r=await this.coordinator.runSecurityAudit(e);return r.success?this.trackSuccessfulOperation("audit"):this.trackFailedOperation("audit",r.error),r}catch(r){return this.handleError(r)}}async getSecurityPosture(){this.ensureInitialized();try{return await this.coordinator.getSecurityPosture()}catch(e){return this.handleError(e)}}async runDependencyScan(e){this.ensureInitialized();try{let r=await this.securityScanner.scanPackageJson(e);return r.success&&r.value.status==="complete"?this.trackSuccessfulOperation("dependency-scan"):this.trackFailedOperation("dependency-scan",r.success?new Error(r.value.error??"Dependency advisory scan incomplete"):r.error),r}catch(r){return this.handleError(r)}}async runSASTScan(e){this.ensureInitialized();try{let r=await this.securityScanner.scanFiles(e);return r.success?this.trackSuccessfulOperation("sast-scan"):this.trackFailedOperation("sast-scan",r.error),r}catch(r){return this.handleError(r)}}async runDASTScan(e){this.ensureInitialized();try{let r=await this.securityScanner.scanUrl(e);return r.success?this.trackSuccessfulOperation("dast-scan"):this.trackFailedOperation("dast-scan",r.error),r}catch(r){return this.handleError(r)}}async triageVulnerabilities(e){this.ensureInitialized();try{let r=await this.securityAuditor.triageVulnerabilities(e);return r.success?{success:!0,value:{immediate:r.value.immediate,shortTerm:r.value.shortTerm}}:{success:!1,error:r.error}}catch(r){return this.handleError(r)}}async runComplianceCheck(e){this.ensureInitialized();try{let r=await this.coordinator.runComplianceCheck(e);return r.success?this.trackSuccessfulOperation("compliance-check"):this.trackFailedOperation("compliance-check",r.error),r}catch(r){return this.handleError(r)}}async getAvailableStandards(){return this.ensureInitialized(),this.complianceValidator.getAvailableStandards()}async analyzeComplianceGaps(e,r){this.ensureInitialized();try{return await this.complianceValidator.analyzeGaps(e,r)}catch(i){return this.handleError(i)}}async handleKnowledgeGraphUpdate(e){let r=e.payload;await this.memory.set(`security:code-update:${Date.now()}`,{filesIndexed:r.filesIndexed,timestamp:new Date},{namespace:"security-compliance",ttl:3600})}async handleQualityGateEvaluated(e){let r=e.payload,i=r.checks.filter(n=>n.name.toLowerCase().includes("security"));i.length>0&&await this.memory.set(`security:gate-results:${r.gateId}`,{securityChecks:i,passed:r.passed},{namespace:"security-compliance",persist:!0})}async handleTestRunCompleted(e){}ensureInitialized(){if(!this._initialized)throw new Error("SecurityCompliancePlugin is not initialized");if(!this.coordinator||!this.securityScanner||!this.securityAuditor||!this.complianceValidator)throw new Error("SecurityCompliancePlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date}),this.memory.set(`security:operation:${e}:${Date.now()}`,{operation:e,success:!0,timestamp:new Date},{namespace:"security-compliance",ttl:86400})}trackFailedOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,failed:i.agents.failed+1},errors:[...i.errors.slice(-9),r.message]}),this.memory.set(`security:operation:${e}:${Date.now()}`,{operation:e,success:!1,error:r.message,timestamp:new Date},{namespace:"security-compliance",ttl:86400})}};function Yd(c,t,e,r,i){return new mc(c,t,e,r,i)}_();k();mr();_();k();X();Pe();var oP={strictMode:!0,validateExamples:!0,maxSchemaDepth:ha.MAX_SCHEMA_DEPTH,cacheValidations:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:fa.MAX_TOKENS},cP=x.create("contract-testing/contract-validator"),Fi=class{config;memory;llmRouter;validationCache=new Map;MAX_CACHED_VALIDATIONS=ha.MAX_CACHED_VALIDATIONS;CACHE_TTL_MS=ha.CACHE_TTL_MS;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...oP,...e}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(t){return ae(t)}async analyzeContractWithLLM(t){if(!this.isLLMAnalysisAvailable())return null;try{let e=t.consumers.map(i=>i.name).join(", ");return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze this API contract for potential issues:
2914
2914
  Provider: ${t.provider.name}
2915
2915
  Consumers: ${e}
2916
2916
  Version: ${t.version.toString()}
@@ -2919,14 +2919,14 @@ Endpoints: ${t.endpoints?.length||0}
2919
2919
  Provide:
2920
2920
  1. Potential compatibility issues
2921
2921
  2. Missing or unclear specifications
2922
- 3. Recommendations for improvement`}],maxTokens:this.config.llmMaxTokens})).content}catch{return oP.warn("LLM analysis failed:"),null}}async validateContract(t){try{let e=this.getCacheKey(t);if(this.config.cacheValidations&&this.validationCache.has(e))return f(this.validationCache.get(e));let r=[],i=[];this.validateContractStructure(t,r,i),this.validateServiceInfo(t.provider,"provider",r);for(let s of t.consumers)this.validateServiceInfo(s,`consumer:${s.name}`,r);for(let s of t.endpoints)await this.validateEndpoint(s,t.schemas,r,i);for(let s of t.schemas)await this.validateSchemaDefinition(s,r,i);this.config.validateExamples&&await this.validateEndpointExamples(t,r,i);let n={isValid:r.length===0,errors:r,warnings:i};return this.config.cacheValidations&&this.cacheValidation(e,n),await this.storeValidationHistory(t.id,n),f(n)}catch(e){return g(y(e))}}async validateRequest(t,e){try{let r=[];switch(e.type){case"json-schema":await this.validateAgainstJsonSchema(t,e.content,r);break;case"openapi":await this.validateAgainstOpenAPISchema(t,e.content,r);break;case"graphql":await this.validateAgainstGraphQLSchema(t,e.content,r);break;default:r.push({path:"",keyword:"unsupported",message:`Schema type '${e.type}' is not supported for request validation`,params:{schemaType:e.type}})}return f({isValid:r.length===0,errors:r})}catch(r){return g(y(r))}}async validateResponse(t,e){try{let r=[];switch(e.type){case"json-schema":await this.validateAgainstJsonSchema(t,e.content,r);break;case"openapi":await this.validateAgainstOpenAPISchema(t,e.content,r);break;case"graphql":await this.validateAgainstGraphQLSchema(t,e.content,r);break;default:r.push({path:"",keyword:"unsupported",message:`Schema type '${e.type}' is not supported for response validation`,params:{schemaType:e.type}})}return f({isValid:r.length===0,errors:r})}catch(r){return g(y(r))}}async validateOpenAPI(t){try{let e=[],r=[],i="unknown",n=0,s=0,a;try{a=D(t)}catch{return f({isValid:!1,specVersion:"unknown",errors:[{path:"",message:"Failed to parse OpenAPI specification",code:"PARSE_ERROR"}],warnings:[],endpointCount:0,schemaCount:0})}a.openapi?i=a.openapi:a.swagger&&(i=`swagger-${a.swagger}`),i.startsWith("3.")?this.validateOpenAPI3Structure(a,e,r):i.startsWith("swagger-2")?this.validateSwagger2Structure(a,e,r):e.push({path:"",message:`Unsupported OpenAPI version: ${i}`,code:"UNSUPPORTED_VERSION"});let o=a.paths||{};for(let[m,p]of Object.entries(o))if(typeof p=="object"&&p!==null){let h=["get","post","put","patch","delete","head","options"];for(let v of h)v in p&&n++}let u=a.components?.schemas||{};s=Object.keys(u).length;let d=a.definitions||{};return s+=Object.keys(d).length,f({isValid:e.length===0,specVersion:i,errors:e,warnings:r,endpointCount:n,schemaCount:s})}catch(e){return g(y(e))}}getCacheKey(t){return`${t.id}:${t.version.toString()}`}validateContractStructure(t,e,r){(!t.id||t.id.trim()==="")&&e.push({path:"id",message:"Contract ID is required",code:"REQUIRED_FIELD"}),(!t.name||t.name.trim()==="")&&e.push({path:"name",message:"Contract name is required",code:"REQUIRED_FIELD"}),t.type||e.push({path:"type",message:"Contract type is required",code:"REQUIRED_FIELD"}),t.endpoints.length===0&&(this.config.strictMode?e.push({path:"endpoints",message:"Contract must have at least one endpoint",code:"EMPTY_ENDPOINTS"}):r.push("Contract has no endpoints defined")),t.consumers.length===0&&r.push("No consumers defined for contract")}validateServiceInfo(t,e,r){(!t.name||t.name.trim()==="")&&r.push({path:`${e}.name`,message:"Service name is required",code:"REQUIRED_FIELD"}),(!t.version||t.version.trim()==="")&&r.push({path:`${e}.version`,message:"Service version is required",code:"REQUIRED_FIELD"})}async validateEndpoint(t,e,r,i){(!t.path||t.path.trim()==="")&&r.push({path:"endpoint.path",message:"Endpoint path is required",code:"REQUIRED_FIELD"}),t.method||r.push({path:"endpoint.method",message:"HTTP method is required",code:"REQUIRED_FIELD"}),t.requestSchema&&(e.some(s=>s.id===t.requestSchema)||r.push({path:`endpoint.${t.path}.requestSchema`,message:`Request schema '${t.requestSchema}' not found`,code:"INVALID_REFERENCE"})),t.responseSchema&&(e.some(s=>s.id===t.responseSchema)||r.push({path:`endpoint.${t.path}.responseSchema`,message:`Response schema '${t.responseSchema}' not found`,code:"INVALID_REFERENCE"})),t.examples.length===0&&i.push(`Endpoint ${t.method} ${t.path} has no examples`)}async validateSchemaDefinition(t,e,r){if((!t.id||t.id.trim()==="")&&e.push({path:"schema.id",message:"Schema ID is required",code:"REQUIRED_FIELD"}),!t.content||t.content.trim()===""){e.push({path:`schema.${t.id}.content`,message:"Schema content is required",code:"REQUIRED_FIELD"});return}switch(t.type){case"json-schema":this.validateJsonSchemaContent(t.content,t.id,e,r);break;case"openapi":this.validateJsonSchemaContent(t.content,t.id,e,r);break;case"graphql":this.validateGraphQLSchemaContent(t.content,t.id,e,r);break;case"protobuf":this.validateProtobufContent(t.content,t.id,e,r);break;case"avro":this.validateAvroContent(t.content,t.id,e,r);break}}validateJsonSchemaContent(t,e,r,i){try{let n=D(t);(typeof n!="object"||n===null)&&r.push({path:`schema.${e}`,message:"JSON Schema must be an object",code:"INVALID_SCHEMA"})}catch{r.push({path:`schema.${e}`,message:"Invalid JSON in schema content",code:"INVALID_JSON"})}}validateGraphQLSchemaContent(t,e,r,i){let n=t.split(`
2922
+ 3. Recommendations for improvement`}],maxTokens:this.config.llmMaxTokens})).content}catch{return cP.warn("LLM analysis failed:"),null}}async validateContract(t){try{let e=this.getCacheKey(t);if(this.config.cacheValidations&&this.validationCache.has(e))return f(this.validationCache.get(e));let r=[],i=[];this.validateContractStructure(t,r,i),this.validateServiceInfo(t.provider,"provider",r);for(let s of t.consumers)this.validateServiceInfo(s,`consumer:${s.name}`,r);for(let s of t.endpoints)await this.validateEndpoint(s,t.schemas,r,i);for(let s of t.schemas)await this.validateSchemaDefinition(s,r,i);this.config.validateExamples&&await this.validateEndpointExamples(t,r,i);let n={isValid:r.length===0,errors:r,warnings:i};return this.config.cacheValidations&&this.cacheValidation(e,n),await this.storeValidationHistory(t.id,n),f(n)}catch(e){return g(y(e))}}async validateRequest(t,e){try{let r=[];switch(e.type){case"json-schema":await this.validateAgainstJsonSchema(t,e.content,r);break;case"openapi":await this.validateAgainstOpenAPISchema(t,e.content,r);break;case"graphql":await this.validateAgainstGraphQLSchema(t,e.content,r);break;default:r.push({path:"",keyword:"unsupported",message:`Schema type '${e.type}' is not supported for request validation`,params:{schemaType:e.type}})}return f({isValid:r.length===0,errors:r})}catch(r){return g(y(r))}}async validateResponse(t,e){try{let r=[];switch(e.type){case"json-schema":await this.validateAgainstJsonSchema(t,e.content,r);break;case"openapi":await this.validateAgainstOpenAPISchema(t,e.content,r);break;case"graphql":await this.validateAgainstGraphQLSchema(t,e.content,r);break;default:r.push({path:"",keyword:"unsupported",message:`Schema type '${e.type}' is not supported for response validation`,params:{schemaType:e.type}})}return f({isValid:r.length===0,errors:r})}catch(r){return g(y(r))}}async validateOpenAPI(t){try{let e=[],r=[],i="unknown",n=0,s=0,a;try{a=D(t)}catch{return f({isValid:!1,specVersion:"unknown",errors:[{path:"",message:"Failed to parse OpenAPI specification",code:"PARSE_ERROR"}],warnings:[],endpointCount:0,schemaCount:0})}a.openapi?i=a.openapi:a.swagger&&(i=`swagger-${a.swagger}`),i.startsWith("3.")?this.validateOpenAPI3Structure(a,e,r):i.startsWith("swagger-2")?this.validateSwagger2Structure(a,e,r):e.push({path:"",message:`Unsupported OpenAPI version: ${i}`,code:"UNSUPPORTED_VERSION"});let o=a.paths||{};for(let[m,p]of Object.entries(o))if(typeof p=="object"&&p!==null){let h=["get","post","put","patch","delete","head","options"];for(let v of h)v in p&&n++}let u=a.components?.schemas||{};s=Object.keys(u).length;let d=a.definitions||{};return s+=Object.keys(d).length,f({isValid:e.length===0,specVersion:i,errors:e,warnings:r,endpointCount:n,schemaCount:s})}catch(e){return g(y(e))}}getCacheKey(t){return`${t.id}:${t.version.toString()}`}validateContractStructure(t,e,r){(!t.id||t.id.trim()==="")&&e.push({path:"id",message:"Contract ID is required",code:"REQUIRED_FIELD"}),(!t.name||t.name.trim()==="")&&e.push({path:"name",message:"Contract name is required",code:"REQUIRED_FIELD"}),t.type||e.push({path:"type",message:"Contract type is required",code:"REQUIRED_FIELD"}),t.endpoints.length===0&&(this.config.strictMode?e.push({path:"endpoints",message:"Contract must have at least one endpoint",code:"EMPTY_ENDPOINTS"}):r.push("Contract has no endpoints defined")),t.consumers.length===0&&r.push("No consumers defined for contract")}validateServiceInfo(t,e,r){(!t.name||t.name.trim()==="")&&r.push({path:`${e}.name`,message:"Service name is required",code:"REQUIRED_FIELD"}),(!t.version||t.version.trim()==="")&&r.push({path:`${e}.version`,message:"Service version is required",code:"REQUIRED_FIELD"})}async validateEndpoint(t,e,r,i){(!t.path||t.path.trim()==="")&&r.push({path:"endpoint.path",message:"Endpoint path is required",code:"REQUIRED_FIELD"}),t.method||r.push({path:"endpoint.method",message:"HTTP method is required",code:"REQUIRED_FIELD"}),t.requestSchema&&(e.some(s=>s.id===t.requestSchema)||r.push({path:`endpoint.${t.path}.requestSchema`,message:`Request schema '${t.requestSchema}' not found`,code:"INVALID_REFERENCE"})),t.responseSchema&&(e.some(s=>s.id===t.responseSchema)||r.push({path:`endpoint.${t.path}.responseSchema`,message:`Response schema '${t.responseSchema}' not found`,code:"INVALID_REFERENCE"})),t.examples.length===0&&i.push(`Endpoint ${t.method} ${t.path} has no examples`)}async validateSchemaDefinition(t,e,r){if((!t.id||t.id.trim()==="")&&e.push({path:"schema.id",message:"Schema ID is required",code:"REQUIRED_FIELD"}),!t.content||t.content.trim()===""){e.push({path:`schema.${t.id}.content`,message:"Schema content is required",code:"REQUIRED_FIELD"});return}switch(t.type){case"json-schema":this.validateJsonSchemaContent(t.content,t.id,e,r);break;case"openapi":this.validateJsonSchemaContent(t.content,t.id,e,r);break;case"graphql":this.validateGraphQLSchemaContent(t.content,t.id,e,r);break;case"protobuf":this.validateProtobufContent(t.content,t.id,e,r);break;case"avro":this.validateAvroContent(t.content,t.id,e,r);break}}validateJsonSchemaContent(t,e,r,i){try{let n=D(t);(typeof n!="object"||n===null)&&r.push({path:`schema.${e}`,message:"JSON Schema must be an object",code:"INVALID_SCHEMA"})}catch{r.push({path:`schema.${e}`,message:"Invalid JSON in schema content",code:"INVALID_JSON"})}}validateGraphQLSchemaContent(t,e,r,i){let n=t.split(`
2923
2923
  `),s=0,a=!1,o=!1;for(let l=0;l<n.length;l++){let u=n[l].trim();if(!(u.startsWith("#")||u==="")&&((u.startsWith("type ")||u.startsWith("input ")||u.startsWith("interface ")||u.startsWith("enum "))&&(a=!0,u.startsWith("type Query")&&(o=!0)),(u.startsWith("schema ")||u.startsWith("schema{"))&&(a=!0),s+=(u.match(/{/g)||[]).length,s-=(u.match(/}/g)||[]).length,u.includes("::")&&r.push({path:`schema.${e}.line${l+1}`,message:"Invalid double colon in GraphQL schema",code:"INVALID_GRAPHQL_SYNTAX"}),u.includes(":")&&!u.includes("type ")&&!u.includes("schema"))){let d=u.indexOf(":"),m=u.slice(d+1).trim();(m===""||m==="{")&&r.push({path:`schema.${e}.line${l+1}`,message:"Field definition missing type",code:"INVALID_GRAPHQL_FIELD"})}}a||r.push({path:`schema.${e}`,message:"GraphQL schema must contain type definitions",code:"INVALID_GRAPHQL"}),s!==0&&r.push({path:`schema.${e}`,message:"GraphQL schema has unbalanced braces",code:"INVALID_GRAPHQL_BRACES"}),a&&!o&&!t.includes("schema {")&&i.push(`Schema ${e} has no Query type defined`)}validateProtobufContent(t,e,r,i){let n=t.split(`
2924
2924
  `),s=0,a=!1,o=!1,l=null;for(let u=0;u<n.length;u++){let d=n[u].trim();if(d.startsWith("//")||d==="")continue;let m=d.match(/^syntax\s*=\s*["']proto(\d)["']\s*;?/);m&&(o=!0,l=m[1]),d.startsWith("message ")&&(a=!0,d.match(/^message\s+([A-Z][a-zA-Z0-9_]*)\s*\{?/)||i.push(`Message name should start with uppercase letter at line ${u+1}`)),d.startsWith("enum ")&&(a=!0),d.startsWith("service ")&&(a=!0),s+=(d.match(/{/g)||[]).length,s-=(d.match(/}/g)||[]).length;let p=d.match(/^\s*(optional|required|repeated)?\s*(\w+)\s+(\w+)\s*=\s*(\d+)/);if(p){let[,h,,,v]=p,b=parseInt(v,10);(b<=0||b>536870911)&&r.push({path:`schema.${e}.line${u+1}`,message:`Invalid field number ${b}`,code:"INVALID_PROTOBUF_FIELD_NUMBER"}),b>=19e3&&b<=19999&&i.push(`Field number ${b} is in reserved range (19000-19999) at line ${u+1}`),h==="required"&&l==="3"&&r.push({path:`schema.${e}.line${u+1}`,message:"Required fields are not allowed in proto3",code:"INVALID_PROTOBUF_REQUIRED"})}}a||r.push({path:`schema.${e}`,message:"Protobuf schema must contain message, enum, or service definitions",code:"INVALID_PROTOBUF"}),s!==0&&r.push({path:`schema.${e}`,message:"Protobuf schema has unbalanced braces",code:"INVALID_PROTOBUF_BRACES"}),o||i.push(`Schema ${e} has no syntax declaration (defaults to proto2)`)}validateAvroContent(t,e,r,i){try{D(t).type||r.push({path:`schema.${e}`,message:"Avro schema must have a type field",code:"INVALID_AVRO"})}catch{r.push({path:`schema.${e}`,message:"Invalid JSON in Avro schema",code:"INVALID_JSON"})}}async validateEndpointExamples(t,e,r){for(let i of t.endpoints)for(let n of i.examples){if(i.requestSchema&&n.request!==void 0){let s=t.schemas.find(a=>a.id===i.requestSchema);if(s){let a=await this.validateRequest(n.request,s);a.success&&!a.value.isValid&&e.push({path:`endpoint.${i.path}.example.${n.name}.request`,message:`Request example does not match schema: ${a.value.errors.map(o=>o.message).join(", ")}`,code:"EXAMPLE_VALIDATION_FAILED"})}}if(i.responseSchema&&n.response!==void 0){let s=t.schemas.find(a=>a.id===i.responseSchema);if(s){let a=await this.validateResponse(n.response,s);a.success&&!a.value.isValid&&e.push({path:`endpoint.${i.path}.example.${n.name}.response`,message:`Response example does not match schema: ${a.value.errors.map(o=>o.message).join(", ")}`,code:"EXAMPLE_VALIDATION_FAILED"})}}}}async validateAgainstJsonSchema(t,e,r){try{let i=D(e);this.basicTypeValidation(t,i,"",r)}catch{r.push({path:"",keyword:"parse",message:"Failed to parse JSON Schema",params:{}})}}async validateAgainstOpenAPISchema(t,e,r){await this.validateAgainstJsonSchema(t,e,r)}async validateAgainstGraphQLSchema(t,e,r){let i=this.parseGraphQLSchema(e);if(i.errors.length>0){for(let d of i.errors)r.push({path:"",keyword:"schema",message:d,params:{}});return}if(typeof t!="object"||t===null){r.push({path:"",keyword:"type",message:"GraphQL request must be an object with query/mutation",params:{}});return}let n=t,s=n.query,a=n.variables;if(!s||typeof s!="string"){r.push({path:"query",keyword:"required",message:"GraphQL request must contain a query string",params:{}});return}let o=this.parseGraphQLOperation(s);if(o.errors.length>0){for(let d of o.errors)r.push({path:"query",keyword:"syntax",message:d,params:{}});return}let l=o.type,u=this.getRootTypeForOperation(l,i);if(!u){r.push({path:"query",keyword:"operation",message:`Schema does not support ${l} operations`,params:{operationType:l}});return}for(let d of o.fields){let m=i.types[u]?.fields[d.name];if(!m)r.push({path:`query.${d.name}`,keyword:"field",message:`Field '${d.name}' does not exist on type '${u}'`,params:{field:d.name,type:u}});else{if(d.arguments)for(let[p,h]of Object.entries(d.arguments))m.arguments?.[p]||r.push({path:`query.${d.name}.${p}`,keyword:"argument",message:`Unknown argument '${p}' on field '${d.name}'`,params:{argument:p,field:d.name}});if(d.selections&&d.selections.length>0){let p=this.unwrapGraphQLType(m.type);this.validateGraphQLSelections(d.selections,p,i,`query.${d.name}`,r)}}}if(a&&o.variableDefinitions)for(let[d,m]of Object.entries(o.variableDefinitions))m.required&&!Object.hasOwn(a,d)&&r.push({path:`variables.${d}`,keyword:"required",message:`Required variable '${d}' is missing`,params:{variable:d}}),Object.hasOwn(a,d)&&this.validateGraphQLVariableType(a[d],m.type,`variables.${d}`,r)}parseGraphQLSchema(t){let e={types:{},queryType:null,mutationType:null,subscriptionType:null,errors:[]},r=t.split(`
2925
2925
  `),i=null,n=null,s=0;for(let a=0;a<r.length;a++){let o=r[a].trim();if(o.startsWith("#")||o==="")continue;if(o.match(/^schema\s*\{?/)){let d=o;if(!o.includes("}"))for(let v=a+1;v<r.length&&(d+=" "+r[v].trim(),!r[v].includes("}"));v++);let m=d.match(/query\s*:\s*(\w+)/),p=d.match(/mutation\s*:\s*(\w+)/),h=d.match(/subscription\s*:\s*(\w+)/);m&&(e.queryType=m[1]),p&&(e.mutationType=p[1]),h&&(e.subscriptionType=h[1]);continue}let u=o.match(/^(type|input|interface|enum)\s+(\w+)(?:\s+implements\s+(\w+))?\s*\{?/);if(u){n=u[1],i=u[2],e.types[i]={kind:n,fields:{},implements:u[3]||null},i==="Query"&&!e.queryType&&(e.queryType="Query"),i==="Mutation"&&!e.mutationType&&(e.mutationType="Mutation"),i==="Subscription"&&!e.subscriptionType&&(e.subscriptionType="Subscription"),o.includes("{")&&s++;continue}if(o.includes("{")&&s++,o.includes("}")){s--,s===0&&(i=null,n=null);continue}if(i&&n!=="enum"){let d=o.match(/^(\w+)(?:\s*\(([^)]*)\))?\s*:\s*(.+?)(?:\s*@.*)?$/);if(d){let m=d[1],p=d[2],v={type:d[3].trim(),arguments:{}};if(p){let b=p.matchAll(/(\w+)\s*:\s*([^,\)]+)/g);for(let C of b)v.arguments[C[1]]={type:C[2].trim()}}e.types[i].fields[m]=v}}if(i&&n==="enum"){let d=o.match(/^(\w+)(?:\s*@.*)?$/);d&&(e.types[i].fields[d[1]]={type:"EnumValue"})}}return!e.queryType&&Object.keys(e.types).length>0&&(e.types.Query||e.errors.push("GraphQL schema must define a Query type or schema definition")),e}parseGraphQLOperation(t){let e={type:"query",name:null,fields:[],variableDefinitions:{},errors:[]},r=t.replace(/#[^\n]*/g,"").trim(),i=r.match(/^(query|mutation|subscription)(?:\s+(\w+))?\s*(?:\(([^)]*)\))?\s*\{/);if(i){if(e.type=i[1],e.name=i[2]||null,i[3]){let s=i[3].matchAll(/\$(\w+)\s*:\s*([^,\)!]+)(!)?/g);for(let a of s)e.variableDefinitions[a[1]]={type:a[2].trim(),required:!!a[3]}}}else if(r.startsWith("{"))e.type="query";else if(!r.includes("{"))return e.errors.push("Invalid GraphQL operation: missing selection set"),e;let n=r.match(/\{([\s\S]*)\}/);return n?(e.fields=this.parseGraphQLSelectionSet(n[1]),e):(e.errors.push("Invalid GraphQL operation: could not parse selection set"),e)}parseGraphQLSelectionSet(t){let e=[],r=0,i="",n=0;for(;n<t.length;){let s=t[n];if(s==="{")r++,i+=s;else if(s==="}")r--,i+=s;else if((s===`
2926
- `||s===" "||s===",")&&r===0){if(i.trim()){let a=this.parseGraphQLField(i.trim());a&&e.push(a)}i=""}else i+=s;n++}if(i.trim()){let s=this.parseGraphQLField(i.trim());s&&e.push(s)}return e}parseGraphQLField(t){let e=t.match(/^(\w+)\s*:\s*(.+)$/),r=t,i;e&&!e[2].includes("(")&&!e[2].includes("{")||e&&(e[2].match(/^\w/)||e[2].includes("("))&&(i=e[1],r=e[2]);let n=r.match(/^(\w+)(?:\s*\(([^)]*)\))?(?:\s*\{([\s\S]*)\})?$/);if(!n){let a=r.match(/^(\w+)(?:\s*\(([^)]*)\))?/);return a?{name:a[1],alias:i,arguments:a[2]?this.parseGraphQLArguments(a[2]):void 0}:null}let s={name:n[1],alias:i};return n[2]&&(s.arguments=this.parseGraphQLArguments(n[2])),n[3]&&(s.selections=this.parseGraphQLSelectionSet(n[3])),s}parseGraphQLArguments(t){let e={},r=t.matchAll(/(\w+)\s*:\s*([^,\)]+)/g);for(let i of r){let n=i[2].trim();n.startsWith("$")?e[i[1]]={_variable:n.substring(1)}:n.startsWith('"')||n.startsWith("'")?e[i[1]]=n.slice(1,-1):n==="true"?e[i[1]]=!0:n==="false"?e[i[1]]=!1:n==="null"?e[i[1]]=null:isNaN(Number(n))?e[i[1]]=n:e[i[1]]=Number(n)}return e}getRootTypeForOperation(t,e){switch(t){case"query":return e.queryType;case"mutation":return e.mutationType;case"subscription":return e.subscriptionType;default:return null}}unwrapGraphQLType(t){return t.replace(/[\[\]!]/g,"").trim()}validateGraphQLSelections(t,e,r,i,n){let s=r.types[e];if(!s){["String","Int","Float","Boolean","ID"].includes(e)&&t.length>0&&n.push({path:i,keyword:"selection",message:`Cannot select fields on scalar type '${e}'`,params:{type:e}});return}for(let a of t){let o=s.fields[a.name];if(!o)n.push({path:`${i}.${a.name}`,keyword:"field",message:`Field '${a.name}' does not exist on type '${e}'`,params:{field:a.name,type:e}});else if(a.selections&&a.selections.length>0){let l=this.unwrapGraphQLType(o.type);this.validateGraphQLSelections(a.selections,l,r,`${i}.${a.name}`,n)}}}validateGraphQLVariableType(t,e,r,i){let n=this.unwrapGraphQLType(e),s=e.endsWith("!"),a=e.includes("[");if(t==null){s&&i.push({path:r,keyword:"type",message:`Variable cannot be null (expected ${e})`,params:{expectedType:e}});return}if(a){Array.isArray(t)||i.push({path:r,keyword:"type",message:`Expected array for type ${e}`,params:{expectedType:e,actualType:typeof t}});return}switch(n){case"String":case"ID":typeof t!="string"&&i.push({path:r,keyword:"type",message:`Expected string for type ${n}`,params:{expectedType:n,actualType:typeof t}});break;case"Int":(typeof t!="number"||!Number.isInteger(t))&&i.push({path:r,keyword:"type",message:"Expected integer for type Int",params:{expectedType:"Int",actualType:typeof t}});break;case"Float":typeof t!="number"&&i.push({path:r,keyword:"type",message:"Expected number for type Float",params:{expectedType:"Float",actualType:typeof t}});break;case"Boolean":typeof t!="boolean"&&i.push({path:r,keyword:"type",message:"Expected boolean for type Boolean",params:{expectedType:"Boolean",actualType:typeof t}});break;default:typeof t!="object"&&i.push({path:r,keyword:"type",message:`Expected object for type ${n}`,params:{expectedType:n,actualType:typeof t}})}}basicTypeValidation(t,e,r,i,n=0){if(n>this.config.maxSchemaDepth){i.push({path:r,keyword:"maxDepth",message:"Maximum schema depth exceeded",params:{maxDepth:this.config.maxSchemaDepth}});return}let s=e.type;if(!s)return;let a=this.getJsonType(t);if(s==="object"&&a==="object"){let o=e.properties||{},l=e.required||[],u=t;for(let d of l)Object.hasOwn(u,d)||i.push({path:r?`${r}.${d}`:d,keyword:"required",message:`Required property '${d}' is missing`,params:{missingProperty:d}});for(let[d,m]of Object.entries(o))Object.hasOwn(u,d)&&this.basicTypeValidation(u[d],m,r?`${r}.${d}`:d,i,n+1)}else if(s==="array"&&a==="array"){let o=e.items,l=t;if(this.validateArrayConstraints(l,e,r,i),o)for(let u=0;u<l.length;u++)this.basicTypeValidation(l[u],o,`${r}[${u}]`,i,n+1)}else s==="string"&&a==="string"?this.validateStringConstraints(t,e,r,i):(s==="number"||s==="integer")&&(a==="number"||a==="integer")?this.validateNumberConstraints(t,e,r,i):s!==a&&(s==="number"&&a==="integer"||i.push({path:r,keyword:"type",message:`Expected type '${s}' but got '${a}'`,params:{expectedType:s,actualType:a}}));if(e.enum){let o=e.enum;o.some(l=>JSON.stringify(l)===JSON.stringify(t))||i.push({path:r,keyword:"enum",message:`Value must be one of: ${o.map(l=>JSON.stringify(l)).join(", ")}`,params:{allowedValues:o}})}}validateStringConstraints(t,e,r,i){let n=e.minLength,s=e.maxLength,a=e.pattern;if(n!==void 0&&t.length<n&&i.push({path:r,keyword:"minLength",message:`String must be at least ${n} characters`,params:{limit:n,actual:t.length}}),s!==void 0&&t.length>s&&i.push({path:r,keyword:"maxLength",message:`String must be at most ${s} characters`,params:{limit:s,actual:t.length}}),a){let o=Xi(a);o&&!o.test(t)&&i.push({path:r,keyword:"pattern",message:`String must match pattern: ${a}`,params:{pattern:a}})}}validateNumberConstraints(t,e,r,i){let n=e.minimum,s=e.maximum,a=e.exclusiveMinimum,o=e.exclusiveMaximum,l=e.multipleOf;n!==void 0&&t<n&&i.push({path:r,keyword:"minimum",message:`Number must be >= ${n}`,params:{limit:n,actual:t}}),s!==void 0&&t>s&&i.push({path:r,keyword:"maximum",message:`Number must be <= ${s}`,params:{limit:s,actual:t}}),a!==void 0&&t<=a&&i.push({path:r,keyword:"exclusiveMinimum",message:`Number must be > ${a}`,params:{limit:a,actual:t}}),o!==void 0&&t>=o&&i.push({path:r,keyword:"exclusiveMaximum",message:`Number must be < ${o}`,params:{limit:o,actual:t}}),l!==void 0&&t%l!==0&&i.push({path:r,keyword:"multipleOf",message:`Number must be a multiple of ${l}`,params:{multipleOf:l,actual:t}})}validateArrayConstraints(t,e,r,i){let n=e.minItems,s=e.maxItems,a=e.uniqueItems;if(n!==void 0&&t.length<n&&i.push({path:r,keyword:"minItems",message:`Array must have at least ${n} items`,params:{limit:n,actual:t.length}}),s!==void 0&&t.length>s&&i.push({path:r,keyword:"maxItems",message:`Array must have at most ${s} items`,params:{limit:s,actual:t.length}}),a){let o=new Set;for(let l=0;l<t.length;l++){let u=JSON.stringify(t[l]);if(o.has(u)){i.push({path:`${r}[${l}]`,keyword:"uniqueItems",message:"Array items must be unique",params:{duplicateIndex:l}});break}o.add(u)}}}getJsonType(t){return t===null?"null":Array.isArray(t)?"array":typeof t=="number"?Number.isInteger(t)?"integer":"number":typeof t}validateOpenAPI3Structure(t,e,r){if(!t.info)e.push({path:"info",message:"OpenAPI 3.x requires info object",code:"REQUIRED_FIELD"});else{let i=t.info;i.title||e.push({path:"info.title",message:"API title is required",code:"REQUIRED_FIELD"}),i.version||e.push({path:"info.version",message:"API version is required",code:"REQUIRED_FIELD"})}t.paths||r.push("No paths defined in OpenAPI specification")}validateSwagger2Structure(t,e,r){t.info||e.push({path:"info",message:"Swagger 2 requires info object",code:"REQUIRED_FIELD"}),t.paths||r.push("No paths defined in Swagger specification"),!t.host&&!t.basePath&&r.push("No host or basePath defined in Swagger specification")}async storeValidationHistory(t,e){let r=`contract-testing:validation:${t}:${Date.now()}`;await this.memory.set(r,e,{namespace:"contract-testing",ttl:86400*30})}cacheValidation(t,e){if(this.validationCache.size>=this.MAX_CACHED_VALIDATIONS){let r=this.validationCache.keys().next().value;r&&this.validationCache.delete(r)}this.validationCache.set(t,{...e,cachedAt:Date.now()})}cleanupCache(){let t=Date.now(),e=0;for(let[r,i]of this.validationCache)t-(i.cachedAt||0)>this.CACHE_TTL_MS&&(this.validationCache.delete(r),e++);return e}destroy(){this.validationCache.clear()}};k();X();var cP={strictEnumValidation:!0,allowOptionalToRequired:!1,trackDeprecations:!0,maxMigrationSteps:50},Li=class{constructor(t,e={}){this.memory=t;this.config={...cP,...e}}memory;config;async compareVersions(t,e){try{let r=[],i=[],n=[];await this.compareEndpoints(t.endpoints,e.endpoints,t.consumers.map(a=>a.name),r,i),await this.compareSchemas(t.schemas,e.schemas,t.consumers.map(a=>a.name),r,i),this.config.trackDeprecations&&this.detectDeprecations(t,e,n);let s={isCompatible:r.length===0,breakingChanges:r,nonBreakingChanges:i,deprecations:n};return await this.storeComparisonResult(t,e,s),f(s)}catch(r){return g(y(r))}}async isBackwardCompatible(t,e){let r=await this.compareVersions(t,e);return r.success?f(r.value.breakingChanges.length===0):r}async getBreakingChanges(t,e){let r=await this.compareVersions(t,e);return r.success?f(r.value.breakingChanges):r}async generateMigrationGuide(t){try{if(t.length===0)return f({fromVersion:"unknown",toVersion:"unknown",steps:[],estimatedEffort:"trivial"});let e=[],r=1,i=t.filter(m=>m.type==="removed-endpoint"),n=t.filter(m=>m.type==="type-change"),s=t.filter(m=>m.type==="required-field-added"),a=t.filter(m=>m.type==="removed-field"),o=t.filter(m=>m.type==="enum-value-removed"),l=t.filter(m=>m.type==="response-code-change");for(let m of s)e.push(this.createMigrationStep(r++,m,"required-field"));for(let m of n)e.push(this.createMigrationStep(r++,m,"type-change"));for(let m of o)e.push(this.createMigrationStep(r++,m,"enum-change"));for(let m of a)e.push(this.createMigrationStep(r++,m,"removed-field"));for(let m of l)e.push(this.createMigrationStep(r++,m,"response-code"));for(let m of i)e.push(this.createMigrationStep(r++,m,"removed-endpoint"));let u=e.slice(0,this.config.maxMigrationSteps),d=this.estimateEffort(t);return f({fromVersion:"previous",toVersion:"current",steps:u,estimatedEffort:d})}catch(e){return g(y(e))}}async compareEndpoints(t,e,r,i,n){let s=this.buildEndpointMap(t),a=this.buildEndpointMap(e),o=Array.from(s.entries());for(let[u,d]of o)a.has(u)||i.push({type:"removed-endpoint",location:`${d.method} ${d.path}`,description:`Endpoint ${d.method} ${d.path} has been removed`,impact:"high",affectedConsumers:r,migrationPath:"Find alternative endpoint or remove usage"});let l=Array.from(a.entries());for(let[u,d]of l)s.has(u)||n.push({type:"added-endpoint",location:`${d.method} ${d.path}`,description:`New endpoint ${d.method} ${d.path} added`});for(let[u,d]of o){let m=a.get(u);m&&await this.compareEndpointDetails(d,m,r,i,n)}}async compareEndpointDetails(t,e,r,i,n){let s=`${t.method} ${t.path}`;t.requestSchema!==e.requestSchema&&i.push({type:"type-change",location:`${s} request`,description:`Request schema changed from '${t.requestSchema||"none"}' to '${e.requestSchema||"none"}'`,impact:"high",affectedConsumers:r}),t.responseSchema!==e.responseSchema&&i.push({type:"type-change",location:`${s} response`,description:`Response schema changed from '${t.responseSchema||"none"}' to '${e.responseSchema||"none"}'`,impact:"medium",affectedConsumers:r});let a=new Set(t.examples.map(u=>u.statusCode)),o=new Set(e.examples.map(u=>u.statusCode)),l=Array.from(a);for(let u of l)o.has(u)||i.push({type:"response-code-change",location:`${s} status ${u}`,description:`Status code ${u} is no longer documented`,impact:"low",affectedConsumers:r})}async compareSchemas(t,e,r,i,n){let s=new Map(t.map(d=>[d.id,d])),a=new Map(e.map(d=>[d.id,d])),o=Array.from(s.keys());for(let d of o)a.has(d)||i.push({type:"removed-field",location:`schema:${d}`,description:`Schema '${d}' has been removed`,impact:"high",affectedConsumers:r});let l=Array.from(a.keys());for(let d of l)s.has(d)||n.push({type:"added-field",location:`schema:${d}`,description:`New schema '${d}' added`});let u=Array.from(s.entries());for(let[d,m]of u){let p=a.get(d);p&&await this.compareSchemaContent(m,p,r,i,n)}}async compareSchemaContent(t,e,r,i,n){if(!(t.type!=="json-schema"||e.type!=="json-schema"))try{let s=D(t.content),a=D(e.content),o=s.properties||{},l=a.properties||{},u=s.required||[],d=a.required||[];for(let m of Object.keys(o))Object.hasOwn(l,m)||i.push({type:"removed-field",location:`schema:${t.id}.${m}`,description:`Property '${m}' has been removed from schema '${t.id}'`,impact:"high",affectedConsumers:r});for(let m of Object.keys(l))Object.hasOwn(o,m)||n.push({type:"added-field",location:`schema:${e.id}.${m}`,description:`Property '${m}' added to schema '${e.id}'`});for(let m of d)u.includes(m)||(Object.hasOwn(o,m)?this.config.allowOptionalToRequired||i.push({type:"required-field-added",location:`schema:${e.id}.${m}`,description:`Property '${m}' changed from optional to required in schema '${e.id}'`,impact:"high",affectedConsumers:r}):Object.hasOwn(l,m)&&i.push({type:"required-field-added",location:`schema:${e.id}.${m}`,description:`New required property '${m}' added to schema '${e.id}'`,impact:"high",affectedConsumers:r}));for(let m of Object.keys(o))if(Object.hasOwn(l,m)){let p=o[m],h=l[m];if(p.type!==h.type&&i.push({type:"type-change",location:`schema:${t.id}.${m}`,description:`Type of '${m}' changed from '${p.type}' to '${h.type}'`,impact:"high",affectedConsumers:r}),this.config.strictEnumValidation){let v=p.enum,b=h.enum;if(v&&b){for(let C of v)b.includes(C)||i.push({type:"enum-value-removed",location:`schema:${t.id}.${m}`,description:`Enum value '${C}' removed from '${m}'`,impact:"medium",affectedConsumers:r});for(let C of b)v.includes(C)||n.push({type:"added-enum-value",location:`schema:${e.id}.${m}`,description:`Enum value '${C}' added to '${m}'`})}}}}catch{}}detectDeprecations(t,e,r){let i=this.buildEndpointMap(t.endpoints),n=this.buildEndpointMap(e.endpoints);for(let[s,a]of i)n.get(s)||r.push({location:`${a.method} ${a.path}`,reason:"Endpoint has been removed in the new version",removalVersion:e.version.toString()});for(let s of e.schemas)this.detectSchemaDeprecations(s,r,e.version);for(let s of e.endpoints)if(s.path.includes("/deprecated/")&&r.push({location:`${s.method} ${s.path}`,reason:"Endpoint path indicates deprecation"}),s.responseSchema){let a=e.schemas.find(o=>o.name===s.responseSchema);a&&this.detectSchemaDeprecations(a,r,e.version,`${s.method} ${s.path}`)}}detectSchemaDeprecations(t,e,r,i){try{let n=typeof t.content=="string"?D(t.content):t.content;this.scanObjectForDeprecations(n,t.name,e,r,i)}catch{}}scanObjectForDeprecations(t,e,r,i,n){if(!t||typeof t!="object")return;let s=t;if(s.deprecated===!0){let a=n?`${n} -> ${e}`:e;r.push({location:a,reason:typeof s.description=="string"?s.description:"Field marked as deprecated",removalVersion:typeof s.removalVersion=="string"?s.removalVersion:void 0,replacement:typeof s.replacement=="string"?s.replacement:void 0})}if(s["x-deprecated"]===!0){let a=n?`${n} -> ${e}`:e;r.push({location:a,reason:typeof s["x-deprecated-message"]=="string"?s["x-deprecated-message"]:"Element marked as deprecated via x-deprecated",removalVersion:i.toString()})}if(s.properties&&typeof s.properties=="object"){let a=s.properties;for(let[o,l]of Object.entries(a))this.scanObjectForDeprecations(l,`${e}.${o}`,r,i,n)}s.items&&typeof s.items=="object"&&this.scanObjectForDeprecations(s.items,`${e}[]`,r,i,n)}buildEndpointMap(t){let e=new Map;for(let r of t){let i=`${r.method}:${r.path}`;e.set(i,r)}return e}createMigrationStep(t,e,r){let i,n,s=!1;switch(r){case"required-field":i=`Add required field: ${e.description}`,n=`// Add the new required field to your request/data objects
2926
+ `||s===" "||s===",")&&r===0){if(i.trim()){let a=this.parseGraphQLField(i.trim());a&&e.push(a)}i=""}else i+=s;n++}if(i.trim()){let s=this.parseGraphQLField(i.trim());s&&e.push(s)}return e}parseGraphQLField(t){let e=t.match(/^(\w+)\s*:\s*(.+)$/),r=t,i;e&&!e[2].includes("(")&&!e[2].includes("{")||e&&(e[2].match(/^\w/)||e[2].includes("("))&&(i=e[1],r=e[2]);let n=r.match(/^(\w+)(?:\s*\(([^)]*)\))?(?:\s*\{([\s\S]*)\})?$/);if(!n){let a=r.match(/^(\w+)(?:\s*\(([^)]*)\))?/);return a?{name:a[1],alias:i,arguments:a[2]?this.parseGraphQLArguments(a[2]):void 0}:null}let s={name:n[1],alias:i};return n[2]&&(s.arguments=this.parseGraphQLArguments(n[2])),n[3]&&(s.selections=this.parseGraphQLSelectionSet(n[3])),s}parseGraphQLArguments(t){let e={},r=t.matchAll(/(\w+)\s*:\s*([^,\)]+)/g);for(let i of r){let n=i[2].trim();n.startsWith("$")?e[i[1]]={_variable:n.substring(1)}:n.startsWith('"')||n.startsWith("'")?e[i[1]]=n.slice(1,-1):n==="true"?e[i[1]]=!0:n==="false"?e[i[1]]=!1:n==="null"?e[i[1]]=null:isNaN(Number(n))?e[i[1]]=n:e[i[1]]=Number(n)}return e}getRootTypeForOperation(t,e){switch(t){case"query":return e.queryType;case"mutation":return e.mutationType;case"subscription":return e.subscriptionType;default:return null}}unwrapGraphQLType(t){return t.replace(/[\[\]!]/g,"").trim()}validateGraphQLSelections(t,e,r,i,n){let s=r.types[e];if(!s){["String","Int","Float","Boolean","ID"].includes(e)&&t.length>0&&n.push({path:i,keyword:"selection",message:`Cannot select fields on scalar type '${e}'`,params:{type:e}});return}for(let a of t){let o=s.fields[a.name];if(!o)n.push({path:`${i}.${a.name}`,keyword:"field",message:`Field '${a.name}' does not exist on type '${e}'`,params:{field:a.name,type:e}});else if(a.selections&&a.selections.length>0){let l=this.unwrapGraphQLType(o.type);this.validateGraphQLSelections(a.selections,l,r,`${i}.${a.name}`,n)}}}validateGraphQLVariableType(t,e,r,i){let n=this.unwrapGraphQLType(e),s=e.endsWith("!"),a=e.includes("[");if(t==null){s&&i.push({path:r,keyword:"type",message:`Variable cannot be null (expected ${e})`,params:{expectedType:e}});return}if(a){Array.isArray(t)||i.push({path:r,keyword:"type",message:`Expected array for type ${e}`,params:{expectedType:e,actualType:typeof t}});return}switch(n){case"String":case"ID":typeof t!="string"&&i.push({path:r,keyword:"type",message:`Expected string for type ${n}`,params:{expectedType:n,actualType:typeof t}});break;case"Int":(typeof t!="number"||!Number.isInteger(t))&&i.push({path:r,keyword:"type",message:"Expected integer for type Int",params:{expectedType:"Int",actualType:typeof t}});break;case"Float":typeof t!="number"&&i.push({path:r,keyword:"type",message:"Expected number for type Float",params:{expectedType:"Float",actualType:typeof t}});break;case"Boolean":typeof t!="boolean"&&i.push({path:r,keyword:"type",message:"Expected boolean for type Boolean",params:{expectedType:"Boolean",actualType:typeof t}});break;default:typeof t!="object"&&i.push({path:r,keyword:"type",message:`Expected object for type ${n}`,params:{expectedType:n,actualType:typeof t}})}}basicTypeValidation(t,e,r,i,n=0){if(n>this.config.maxSchemaDepth){i.push({path:r,keyword:"maxDepth",message:"Maximum schema depth exceeded",params:{maxDepth:this.config.maxSchemaDepth}});return}let s=e.type;if(!s)return;let a=this.getJsonType(t);if(s==="object"&&a==="object"){let o=e.properties||{},l=e.required||[],u=t;for(let d of l)Object.hasOwn(u,d)||i.push({path:r?`${r}.${d}`:d,keyword:"required",message:`Required property '${d}' is missing`,params:{missingProperty:d}});for(let[d,m]of Object.entries(o))Object.hasOwn(u,d)&&this.basicTypeValidation(u[d],m,r?`${r}.${d}`:d,i,n+1)}else if(s==="array"&&a==="array"){let o=e.items,l=t;if(this.validateArrayConstraints(l,e,r,i),o)for(let u=0;u<l.length;u++)this.basicTypeValidation(l[u],o,`${r}[${u}]`,i,n+1)}else s==="string"&&a==="string"?this.validateStringConstraints(t,e,r,i):(s==="number"||s==="integer")&&(a==="number"||a==="integer")?this.validateNumberConstraints(t,e,r,i):s!==a&&(s==="number"&&a==="integer"||i.push({path:r,keyword:"type",message:`Expected type '${s}' but got '${a}'`,params:{expectedType:s,actualType:a}}));if(e.enum){let o=e.enum;o.some(l=>JSON.stringify(l)===JSON.stringify(t))||i.push({path:r,keyword:"enum",message:`Value must be one of: ${o.map(l=>JSON.stringify(l)).join(", ")}`,params:{allowedValues:o}})}}validateStringConstraints(t,e,r,i){let n=e.minLength,s=e.maxLength,a=e.pattern;if(n!==void 0&&t.length<n&&i.push({path:r,keyword:"minLength",message:`String must be at least ${n} characters`,params:{limit:n,actual:t.length}}),s!==void 0&&t.length>s&&i.push({path:r,keyword:"maxLength",message:`String must be at most ${s} characters`,params:{limit:s,actual:t.length}}),a){let o=Xi(a);o&&!o.test(t)&&i.push({path:r,keyword:"pattern",message:`String must match pattern: ${a}`,params:{pattern:a}})}}validateNumberConstraints(t,e,r,i){let n=e.minimum,s=e.maximum,a=e.exclusiveMinimum,o=e.exclusiveMaximum,l=e.multipleOf;n!==void 0&&t<n&&i.push({path:r,keyword:"minimum",message:`Number must be >= ${n}`,params:{limit:n,actual:t}}),s!==void 0&&t>s&&i.push({path:r,keyword:"maximum",message:`Number must be <= ${s}`,params:{limit:s,actual:t}}),a!==void 0&&t<=a&&i.push({path:r,keyword:"exclusiveMinimum",message:`Number must be > ${a}`,params:{limit:a,actual:t}}),o!==void 0&&t>=o&&i.push({path:r,keyword:"exclusiveMaximum",message:`Number must be < ${o}`,params:{limit:o,actual:t}}),l!==void 0&&t%l!==0&&i.push({path:r,keyword:"multipleOf",message:`Number must be a multiple of ${l}`,params:{multipleOf:l,actual:t}})}validateArrayConstraints(t,e,r,i){let n=e.minItems,s=e.maxItems,a=e.uniqueItems;if(n!==void 0&&t.length<n&&i.push({path:r,keyword:"minItems",message:`Array must have at least ${n} items`,params:{limit:n,actual:t.length}}),s!==void 0&&t.length>s&&i.push({path:r,keyword:"maxItems",message:`Array must have at most ${s} items`,params:{limit:s,actual:t.length}}),a){let o=new Set;for(let l=0;l<t.length;l++){let u=JSON.stringify(t[l]);if(o.has(u)){i.push({path:`${r}[${l}]`,keyword:"uniqueItems",message:"Array items must be unique",params:{duplicateIndex:l}});break}o.add(u)}}}getJsonType(t){return t===null?"null":Array.isArray(t)?"array":typeof t=="number"?Number.isInteger(t)?"integer":"number":typeof t}validateOpenAPI3Structure(t,e,r){if(!t.info)e.push({path:"info",message:"OpenAPI 3.x requires info object",code:"REQUIRED_FIELD"});else{let i=t.info;i.title||e.push({path:"info.title",message:"API title is required",code:"REQUIRED_FIELD"}),i.version||e.push({path:"info.version",message:"API version is required",code:"REQUIRED_FIELD"})}t.paths||r.push("No paths defined in OpenAPI specification")}validateSwagger2Structure(t,e,r){t.info||e.push({path:"info",message:"Swagger 2 requires info object",code:"REQUIRED_FIELD"}),t.paths||r.push("No paths defined in Swagger specification"),!t.host&&!t.basePath&&r.push("No host or basePath defined in Swagger specification")}async storeValidationHistory(t,e){let r=`contract-testing:validation:${t}:${Date.now()}`;await this.memory.set(r,e,{namespace:"contract-testing",ttl:86400*30})}cacheValidation(t,e){if(this.validationCache.size>=this.MAX_CACHED_VALIDATIONS){let r=this.validationCache.keys().next().value;r&&this.validationCache.delete(r)}this.validationCache.set(t,{...e,cachedAt:Date.now()})}cleanupCache(){let t=Date.now(),e=0;for(let[r,i]of this.validationCache)t-(i.cachedAt||0)>this.CACHE_TTL_MS&&(this.validationCache.delete(r),e++);return e}destroy(){this.validationCache.clear()}};k();X();var lP={strictEnumValidation:!0,allowOptionalToRequired:!1,trackDeprecations:!0,maxMigrationSteps:50},Li=class{constructor(t,e={}){this.memory=t;this.config={...lP,...e}}memory;config;async compareVersions(t,e){try{let r=[],i=[],n=[];await this.compareEndpoints(t.endpoints,e.endpoints,t.consumers.map(a=>a.name),r,i),await this.compareSchemas(t.schemas,e.schemas,t.consumers.map(a=>a.name),r,i),this.config.trackDeprecations&&this.detectDeprecations(t,e,n);let s={isCompatible:r.length===0,breakingChanges:r,nonBreakingChanges:i,deprecations:n};return await this.storeComparisonResult(t,e,s),f(s)}catch(r){return g(y(r))}}async isBackwardCompatible(t,e){let r=await this.compareVersions(t,e);return r.success?f(r.value.breakingChanges.length===0):r}async getBreakingChanges(t,e){let r=await this.compareVersions(t,e);return r.success?f(r.value.breakingChanges):r}async generateMigrationGuide(t){try{if(t.length===0)return f({fromVersion:"unknown",toVersion:"unknown",steps:[],estimatedEffort:"trivial"});let e=[],r=1,i=t.filter(m=>m.type==="removed-endpoint"),n=t.filter(m=>m.type==="type-change"),s=t.filter(m=>m.type==="required-field-added"),a=t.filter(m=>m.type==="removed-field"),o=t.filter(m=>m.type==="enum-value-removed"),l=t.filter(m=>m.type==="response-code-change");for(let m of s)e.push(this.createMigrationStep(r++,m,"required-field"));for(let m of n)e.push(this.createMigrationStep(r++,m,"type-change"));for(let m of o)e.push(this.createMigrationStep(r++,m,"enum-change"));for(let m of a)e.push(this.createMigrationStep(r++,m,"removed-field"));for(let m of l)e.push(this.createMigrationStep(r++,m,"response-code"));for(let m of i)e.push(this.createMigrationStep(r++,m,"removed-endpoint"));let u=e.slice(0,this.config.maxMigrationSteps),d=this.estimateEffort(t);return f({fromVersion:"previous",toVersion:"current",steps:u,estimatedEffort:d})}catch(e){return g(y(e))}}async compareEndpoints(t,e,r,i,n){let s=this.buildEndpointMap(t),a=this.buildEndpointMap(e),o=Array.from(s.entries());for(let[u,d]of o)a.has(u)||i.push({type:"removed-endpoint",location:`${d.method} ${d.path}`,description:`Endpoint ${d.method} ${d.path} has been removed`,impact:"high",affectedConsumers:r,migrationPath:"Find alternative endpoint or remove usage"});let l=Array.from(a.entries());for(let[u,d]of l)s.has(u)||n.push({type:"added-endpoint",location:`${d.method} ${d.path}`,description:`New endpoint ${d.method} ${d.path} added`});for(let[u,d]of o){let m=a.get(u);m&&await this.compareEndpointDetails(d,m,r,i,n)}}async compareEndpointDetails(t,e,r,i,n){let s=`${t.method} ${t.path}`;t.requestSchema!==e.requestSchema&&i.push({type:"type-change",location:`${s} request`,description:`Request schema changed from '${t.requestSchema||"none"}' to '${e.requestSchema||"none"}'`,impact:"high",affectedConsumers:r}),t.responseSchema!==e.responseSchema&&i.push({type:"type-change",location:`${s} response`,description:`Response schema changed from '${t.responseSchema||"none"}' to '${e.responseSchema||"none"}'`,impact:"medium",affectedConsumers:r});let a=new Set(t.examples.map(u=>u.statusCode)),o=new Set(e.examples.map(u=>u.statusCode)),l=Array.from(a);for(let u of l)o.has(u)||i.push({type:"response-code-change",location:`${s} status ${u}`,description:`Status code ${u} is no longer documented`,impact:"low",affectedConsumers:r})}async compareSchemas(t,e,r,i,n){let s=new Map(t.map(d=>[d.id,d])),a=new Map(e.map(d=>[d.id,d])),o=Array.from(s.keys());for(let d of o)a.has(d)||i.push({type:"removed-field",location:`schema:${d}`,description:`Schema '${d}' has been removed`,impact:"high",affectedConsumers:r});let l=Array.from(a.keys());for(let d of l)s.has(d)||n.push({type:"added-field",location:`schema:${d}`,description:`New schema '${d}' added`});let u=Array.from(s.entries());for(let[d,m]of u){let p=a.get(d);p&&await this.compareSchemaContent(m,p,r,i,n)}}async compareSchemaContent(t,e,r,i,n){if(!(t.type!=="json-schema"||e.type!=="json-schema"))try{let s=D(t.content),a=D(e.content),o=s.properties||{},l=a.properties||{},u=s.required||[],d=a.required||[];for(let m of Object.keys(o))Object.hasOwn(l,m)||i.push({type:"removed-field",location:`schema:${t.id}.${m}`,description:`Property '${m}' has been removed from schema '${t.id}'`,impact:"high",affectedConsumers:r});for(let m of Object.keys(l))Object.hasOwn(o,m)||n.push({type:"added-field",location:`schema:${e.id}.${m}`,description:`Property '${m}' added to schema '${e.id}'`});for(let m of d)u.includes(m)||(Object.hasOwn(o,m)?this.config.allowOptionalToRequired||i.push({type:"required-field-added",location:`schema:${e.id}.${m}`,description:`Property '${m}' changed from optional to required in schema '${e.id}'`,impact:"high",affectedConsumers:r}):Object.hasOwn(l,m)&&i.push({type:"required-field-added",location:`schema:${e.id}.${m}`,description:`New required property '${m}' added to schema '${e.id}'`,impact:"high",affectedConsumers:r}));for(let m of Object.keys(o))if(Object.hasOwn(l,m)){let p=o[m],h=l[m];if(p.type!==h.type&&i.push({type:"type-change",location:`schema:${t.id}.${m}`,description:`Type of '${m}' changed from '${p.type}' to '${h.type}'`,impact:"high",affectedConsumers:r}),this.config.strictEnumValidation){let v=p.enum,b=h.enum;if(v&&b){for(let C of v)b.includes(C)||i.push({type:"enum-value-removed",location:`schema:${t.id}.${m}`,description:`Enum value '${C}' removed from '${m}'`,impact:"medium",affectedConsumers:r});for(let C of b)v.includes(C)||n.push({type:"added-enum-value",location:`schema:${e.id}.${m}`,description:`Enum value '${C}' added to '${m}'`})}}}}catch{}}detectDeprecations(t,e,r){let i=this.buildEndpointMap(t.endpoints),n=this.buildEndpointMap(e.endpoints);for(let[s,a]of i)n.get(s)||r.push({location:`${a.method} ${a.path}`,reason:"Endpoint has been removed in the new version",removalVersion:e.version.toString()});for(let s of e.schemas)this.detectSchemaDeprecations(s,r,e.version);for(let s of e.endpoints)if(s.path.includes("/deprecated/")&&r.push({location:`${s.method} ${s.path}`,reason:"Endpoint path indicates deprecation"}),s.responseSchema){let a=e.schemas.find(o=>o.name===s.responseSchema);a&&this.detectSchemaDeprecations(a,r,e.version,`${s.method} ${s.path}`)}}detectSchemaDeprecations(t,e,r,i){try{let n=typeof t.content=="string"?D(t.content):t.content;this.scanObjectForDeprecations(n,t.name,e,r,i)}catch{}}scanObjectForDeprecations(t,e,r,i,n){if(!t||typeof t!="object")return;let s=t;if(s.deprecated===!0){let a=n?`${n} -> ${e}`:e;r.push({location:a,reason:typeof s.description=="string"?s.description:"Field marked as deprecated",removalVersion:typeof s.removalVersion=="string"?s.removalVersion:void 0,replacement:typeof s.replacement=="string"?s.replacement:void 0})}if(s["x-deprecated"]===!0){let a=n?`${n} -> ${e}`:e;r.push({location:a,reason:typeof s["x-deprecated-message"]=="string"?s["x-deprecated-message"]:"Element marked as deprecated via x-deprecated",removalVersion:i.toString()})}if(s.properties&&typeof s.properties=="object"){let a=s.properties;for(let[o,l]of Object.entries(a))this.scanObjectForDeprecations(l,`${e}.${o}`,r,i,n)}s.items&&typeof s.items=="object"&&this.scanObjectForDeprecations(s.items,`${e}[]`,r,i,n)}buildEndpointMap(t){let e=new Map;for(let r of t){let i=`${r.method}:${r.path}`;e.set(i,r)}return e}createMigrationStep(t,e,r){let i,n,s=!1;switch(r){case"required-field":i=`Add required field: ${e.description}`,n=`// Add the new required field to your request/data objects
2927
2927
  // Location: ${e.location}`,s=!1;break;case"type-change":i=`Update type: ${e.description}`,n=`// Update the type at ${e.location}
2928
- // Follow the new type specification`,s=!1;break;case"enum-change":i=`Update enum usage: ${e.description}`,n=`// Remove usage of deprecated enum value at ${e.location}`,s=!0;break;case"removed-field":i=`Remove field usage: ${e.description}`,n=`// Remove references to ${e.location}`,s=!0;break;case"response-code":i=`Update response handling: ${e.description}`,n=`// Update error handling for ${e.location}`,s=!1;break;case"removed-endpoint":i=`Migrate from removed endpoint: ${e.description}`,n=e.migrationPath?`// ${e.migrationPath}`:`// Find alternative for ${e.location}`,s=!1;break;default:i=e.description,n=void 0,s=!1}return{order:t,description:i,codeChanges:n,automated:s}}estimateEffort(t){if(t.length===0)return"trivial";let e=t.filter(i=>i.impact==="high").length,r=t.filter(i=>i.impact==="medium").length;return e>5||t.length>10?"major":e>2||r>5?"moderate":e>0||t.length>3?"minor":"trivial"}async storeComparisonResult(t,e,r){let i=`contract-testing:comparison:${t.id}:${t.version.toString()}:${e.version.toString()}`;await this.memory.set(i,{oldVersion:t.version.toString(),newVersion:e.version.toString(),isCompatible:r.isCompatible,breakingChangeCount:r.breakingChanges.length,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400*90})}};var lP={stateSize:10,actionSize:4,hiddenLayers:[128,128],minReplaySize:100},pc=class extends ve{qNetwork;replayBufferClass;sarsaConfig;actions=[];constructor(t={}){super("sarsa","value-based"),this.sarsaConfig={...lP,...t},this.initializeActions(),this.qNetwork=new J({layerSizes:[this.sarsaConfig.stateSize,...this.sarsaConfig.hiddenLayers,this.sarsaConfig.actionSize],activations:Array(this.sarsaConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.replayBufferClass=new At(this.config.replayBufferSize,!1)}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.qNetwork.forward(e),i=this.argmax(r),n=this.actions[i];return{action:n,confidence:.7,value:r[i],reasoning:`SARSA: ${n.type}`}}async trainCore(t){for(let i of t)this.replayBufferClass.add(i);if(!this.replayBufferClass.isReady(this.sarsaConfig.minReplaySize))return this.getStats();let e=this.replayBufferClass.sample(this.config.batchSize),r=0;for(let i=0;i<e.length;i++){let n=e[i],s=e[i+1],a=this.prepareState(n.state),o=this.actionToIndex(n.action),l=this.qNetwork.forward(a),u=l[o],d=0;if(s&&!n.done){let h=this.prepareState(s.state),v=this.actionToIndex(s.action);d=this.qNetwork.forward(h)[v]}let m=n.reward+this.config.discountFactor*d,p=new Float32Array(l.length);for(let h=0;h<p.length;h++)p[h]=h===o?m:l[h];r+=Math.abs(this.qNetwork.train(a,p,new Fe))}return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/e.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural SARSA for Defect Prediction Sequencing",capabilities:["On-policy learning","Neural Q-network"],hyperparameters:{stateSize:this.sarsaConfig.stateSize,actionSize:this.sarsaConfig.actionSize,hiddenLayers:this.sarsaConfig.hiddenLayers.join(",")},stats:this.stats}}prepareState(t){let e=t.features.slice(0,this.sarsaConfig.stateSize);for(;e.length<this.sarsaConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]/=r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"predict-high",value:1},{type:"predict-low",value:0},{type:"sequence-early",value:"high-risk"},{type:"sequence-late",value:"low-risk"}],this.sarsaConfig.actionSize=this.actions.length,this.qNetwork=new J({layerSizes:[this.sarsaConfig.stateSize,...this.sarsaConfig.hiddenLayers,this.sarsaConfig.actionSize],activations:Array(this.sarsaConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate})}actionToIndex(t){let e=`${t.type}:${JSON.stringify(t.value)}`;for(let r=0;r<this.actions.length;r++)if(`${this.actions[r].type}:${JSON.stringify(this.actions[r].value)}`===e)return r;return 0}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}async exportCustomData(){return{qNetwork:this.qNetwork.getParameters(),sarsaConfig:this.sarsaConfig}}async importCustomData(t){t.qNetwork&&this.qNetwork.setParameters(t.qNetwork),t.sarsaConfig&&(this.sarsaConfig={...this.sarsaConfig,...t.sarsaConfig}),this.initialized=!0}async resetAlgorithm(){this.qNetwork=new J({layerSizes:[this.sarsaConfig.stateSize,...this.sarsaConfig.hiddenLayers,this.sarsaConfig.actionSize],activations:Array(this.sarsaConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.replayBufferClass.clear()}};vt();X();var gc={ContractVerified:"contract-testing.ContractVerified",BreakingChangeDetected:"contract-testing.BreakingChangeDetected",ContractPublished:"contract-testing.ContractPublished",ConsumerContractCreated:"contract-testing.ConsumerContractCreated",VerificationFailed:"contract-testing.VerificationFailed"},uP={maxConcurrentWorkflows:5,defaultTimeout:6e4,enableAutoVerification:!0,publishEvents:!0,enableSARSA:!0,enableQESONA:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},le=x.create("contract-testing"),hc=class extends ie{constructor(e,r,i,n={},s){let a={...uP,...n};super(e,"contract-testing",a,{verifyFindingTypes:["contract-violation","breaking-change","schema-incompatibility"]});this.memory=r;this.agentCoordinator=i;this.contractValidator=new Fi({memory:r,llmRouter:s}),this.apiCompatibility=new Li(r),this.httpClient=is(),this.fileReader=new it({projectRoot:Ce()})}memory;agentCoordinator;contractValidator;apiCompatibility;httpClient;fileReader;contractStore=new Map;sarsaAlgorithm;qesona;async onInitialize(){if(this.config.enableSARSA)try{this.sarsaAlgorithm=new pc({stateSize:10,actionSize:4,hiddenLayers:[64,64]}),le.info("SARSA algorithm created successfully")}catch(e){throw le.error("Failed to create SARSA:",e instanceof Error?e:void 0),new Error(`SARSA creation failed: ${P(e)}`)}if(this.config.enableQESONA)try{this.qesona=await De({domain:"contract-testing",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:5e3,minConfidence:.6}),le.info("PersistentSONAEngine initialized successfully")}catch(e){le.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),le.warn("Continuing without SONA pattern persistence"),this.qesona=void 0}this.subscribeToEvents(),await this.loadContracts()}async onDispose(){await this.saveContracts(),this.qesona&&(await this.qesona.close(),this.qesona=void 0),this.sarsaAlgorithm=void 0,this.contractStore.clear()}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this))}getActiveWorkflows(){return super.getActiveWorkflows()}async registerContract(e){try{let r=await this.contractValidator.validateContract(e);if(!r.success)return r;if(!r.value.isValid){let i=r.value.errors.map(n=>n.message).join("; ");return g(new Error(`Contract validation failed: ${i}`))}return this.contractStore.set(e.id,e),await this.memory.set(`contract-testing:contract:${e.id}`,e,{namespace:"contract-testing",persist:!0}),this.config.publishEvents&&await this.publishContractRegistered(e),f(e.id)}catch(r){return g(y(r))}}async verifyAllConsumers(e,r){let i=w();try{if(this.startWorkflow(i,"verify"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&le.warn("Topology degraded, using conservative verification strategy"),this.minCutMixin.shouldPauseOperations())return g(new Error("Contract verification paused: topology is in critical state"));let n=await this.findContractsByProvider(e);if(n.length===0)return this.completeWorkflow(i),f({provider:e,totalConsumers:0,passedConsumers:0,failedConsumers:[],results:[],canDeploy:!0});if(this.config.enableSARSA&&n.length>1){let d={urgency:5,providerLoad:50,consumerCount:n.reduce((p,h)=>p+h.consumers.length,0)},m=await this.prioritizeContracts(n,d);m.success&&(n=m.value.orderedContracts,le.info(`[contract-testing] Using ${m.value.strategy} strategy for contract verification order (confidence: ${m.value.confidence.toFixed(2)})`))}let s=await this.spawnVerificationAgent(i,e);if(!s.success)return this.failWorkflow(i,s.error.message),s;this.addAgentToWorkflow(i,s.value);let a=[],o=[];for(let d of n){for(let m of d.consumers){let p=await this.verifyConsumerContract(d,m.name,r);a.push(p),p.passed?this.config.publishEvents&&await this.publishContractVerified(d,m.name,p):(o.push(m.name),this.config.publishEvents&&await this.publishVerificationFailed(d,m.name,p))}this.updateWorkflowProgress(i,a.length/n.length*100)}await this.agentCoordinator.stop(s.value),this.completeWorkflow(i);let l=Array.from(new Set(o)),u=n.flatMap(d=>d.consumers.map(m=>m.name)).filter(d=>!l.includes(d)).length;return f({provider:e,totalConsumers:n.reduce((d,m)=>d+m.consumers.length,0),passedConsumers:u,failedConsumers:l,results:a,canDeploy:l.length===0})}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async preReleaseCheck(e,r){let i=w();try{if(this.startWorkflow(i,"compare"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&le.warn("Topology degraded, using conservative pre-release check"),this.minCutMixin.shouldPauseOperations())return g(new Error("Pre-release check paused: topology is in critical state"));let n=await this.loadContractFromPath(r);if(!n)return this.failWorkflow(i,"Failed to load contract from path"),g(new Error("Failed to load contract from path"));let s=await this.findContractsByProvider(e),a=s.length>0?s[0]:null;if(!a)return this.completeWorkflow(i),f({breakingChanges:[],affectedConsumers:[],canRelease:!0,recommendations:["No existing contract found. This will be the first version."]});let o=await this.apiCompatibility.compareVersions(a,n);if(!o.success)return this.failWorkflow(i,o.error.message),o;let{breakingChanges:l,deprecations:u}=o.value,d=[];for(let p of a.consumers){let h=l.filter(v=>v.affectedConsumers.includes(p.name));h.length>0&&d.push({name:p.name,team:p.team,breakingChanges:h,notified:!1})}let m=[];if(l.length>0){m.push(`${l.length} breaking changes detected. Coordinate with affected consumers before release.`);let p=await this.apiCompatibility.generateMigrationGuide(l);p.success&&m.push(`Migration effort estimated as: ${p.value.estimatedEffort}`)}return u.length>0&&m.push(`${u.length} deprecations detected. Consider communicating removal timeline.`),l.length===0&&u.length===0&&m.push("No breaking changes detected. Safe to release."),this.config.publishEvents&&l.length>0&&await this.publishBreakingChangeDetected(n.id,l,d.map(p=>p.name)),this.completeWorkflow(i),f({breakingChanges:l,affectedConsumers:d,canRelease:l.length===0,recommendations:m})}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async importFromOpenAPI(e){let r=w();try{this.startWorkflow(r,"import");let i=await this.loadFileContent(e);if(!i)return this.failWorkflow(r,"Failed to load OpenAPI spec"),g(new Error("Failed to load OpenAPI spec"));let n=await this.contractValidator.validateOpenAPI(i);if(!n.success)return this.failWorkflow(r,n.error.message),n;if(!n.value.isValid){let a=n.value.errors.map(o=>o.message).join("; ");return this.failWorkflow(r,a),g(new Error(`Invalid OpenAPI spec: ${a}`))}let s=this.parseOpenAPIToContract(i);return this.contractStore.set(s.id,s),await this.memory.set(`contract-testing:contract:${s.id}`,s,{namespace:"contract-testing",persist:!0}),this.completeWorkflow(r),f(s)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async exportToOpenAPI(e){let r=w();try{this.startWorkflow(r,"export");let i=this.contractStore.get(e);if(!i)return this.failWorkflow(r,"Contract not found"),g(new Error(`Contract not found: ${e}`));let n=this.contractToOpenAPI(i);return this.completeWorkflow(r),f(n)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async verifyConsumerContract(e,r,i){let n=[],s=[],a=i.startsWith("http://")||i.startsWith("https://");for(let o of e.endpoints){let l=`${i}${o.path}`,u=`${o.method} ${o.path}`;if(a)try{let d=await this.verifyEndpoint(l,o.method,o);d.success?d.warning&&s.push({endpoint:u,message:d.warning,severity:"low"}):n.push({endpoint:u,type:d.errorType,expected:d.expected,actual:d.actual,message:d.message})}catch(d){n.push({endpoint:u,type:"connection-error",expected:"reachable",actual:"error",message:`Failed to verify endpoint: ${P(d)}`})}else i||n.push({endpoint:u,type:"connection-error",expected:"reachable",actual:"unreachable",message:`Endpoint ${u} is not reachable (no provider URL)`})}return{contractId:e.id,provider:e.provider.name,consumer:r,passed:n.length===0,failures:n,warnings:s,timestamp:new Date}}async verifyEndpoint(e,r,i){let s={timeout:1e4,retries:1,circuitBreaker:!1},a;switch(r){case"GET":case"HEAD":a=await this.httpClient.get(e,s);break;case"POST":a=await this.httpClient.post(e,{},s);break;case"PUT":a=await this.httpClient.put(e,{},s);break;case"PATCH":a=await this.httpClient.patch(e,{},s);break;case"DELETE":a=await this.httpClient.delete(e,s);break;case"OPTIONS":a=await this.httpClient.get(e,s);break;default:a=await this.httpClient.get(e,s)}if(!a.success)return{success:!1,errorType:"connection-error",expected:"successful response",actual:`error: ${a.error.message}`,message:`Endpoint unreachable: ${a.error.message}`};let o=a.value;if(i.examples&&i.examples.length>0){let d=i.examples.map(m=>m.statusCode);if(!d.includes(o.status))return{success:!1,errorType:"status-mismatch",expected:d.join(" or "),actual:String(o.status),message:`Expected status ${d.join("/")} but got ${o.status}`}}let l,u=o.headers.get("Deprecation");return u&&(l=`Endpoint is deprecated: ${u}`),{success:!0,errorType:"",expected:"",actual:"",message:"Endpoint verified successfully",warning:l}}async findContractsByProvider(e){let r=[],i=Array.from(this.contractStore.values());for(let s of i)s.provider.name===e&&r.push(s);let n=await this.memory.search("contract-testing:contract:*",100);for(let s of n){let a=await this.memory.get(s);a&&a.provider.name===e&&(this.contractStore.has(a.id)||r.push(a))}return r}async loadContractFromPath(e){let r=await this.loadFileContent(e);if(!r)return null;try{let i=e.value.toLowerCase();if(i.endsWith(".json")){let n=D(r);return n.openapi||n.swagger?this.parseOpenAPIToContract(r):n}else if(i.endsWith(".yaml")||i.endsWith(".yml"))return le.warn("YAML contract files not yet supported:"),null;return D(r)}catch(i){return le.error(`Failed to parse contract from ${e.value}: ${P(i)}`),null}}async loadFileContent(e){let r=await this.fileReader.readFile(e.value);return r.success?r.value:(le.error(`Failed to read file ${e.value}:`,r.error),null)}parseOpenAPIToContract(e){let r=D(e),i=r.info||{},n=r.paths||{},s=[],a=[];for(let[u,d]of Object.entries(n)){let m=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let p of m){let h=d[p.toLowerCase()];h&&s.push({path:u,method:p,requestSchema:this.extractRequestSchema(h),responseSchema:this.extractResponseSchema(h),headers:{},examples:[]})}}let l=(r.components||{}).schemas||{};for(let[u,d]of Object.entries(l))a.push({id:u,name:u,type:"openapi",content:JSON.stringify(d)});return{id:w(),name:i.title||"Imported Contract",version:nn.parse(i.version||"1.0.0"),type:"rest",provider:{name:i.title||"Unknown Provider",version:i.version||"1.0.0"},consumers:[],endpoints:s,schemas:a}}extractRequestSchema(e){let r=e.requestBody;if(r){let i=r.content;if(i){let n=i["application/json"];if(n?.schema){let s=n.schema.$ref;if(s)return s.split("/").pop()}}}}extractResponseSchema(e){let r=e.responses;if(r){let i=r[200]||r[201];if(i){let n=i.content;if(n){let s=n["application/json"];if(s?.schema){let a=s.schema.$ref;if(a)return a.split("/").pop()}}}}}contractToOpenAPI(e){let r={};for(let s of e.endpoints){r[s.path]||(r[s.path]={});let a={summary:`${s.method} ${s.path}`,responses:{200:{description:"Success",content:s.responseSchema?{"application/json":{schema:{$ref:`#/components/schemas/${s.responseSchema}`}}}:void 0}}};s.requestSchema&&(a.requestBody={content:{"application/json":{schema:{$ref:`#/components/schemas/${s.requestSchema}`}}}}),r[s.path][s.method.toLowerCase()]=a}let i={};for(let s of e.schemas)try{i[s.id]=D(s.content)}catch{i[s.id]={type:"object"}}let n={openapi:"3.0.3",info:{title:e.name,version:e.version.toString()},paths:r,components:{schemas:i}};return JSON.stringify(n,null,2)}async spawnVerificationAgent(e,r){let i={name:`contract-verifier-${e.slice(0,8)}`,domain:"contract-testing",type:"validator",capabilities:["contract-verification","http-testing"],config:{workflowId:e,providerName:r}};return this.agentCoordinator.spawn(i)}async publishContractRegistered(e){let r=N(gc.ContractPublished,"contract-testing",{contractId:e.id,version:e.version.toString(),provider:e.provider.name});await this.eventBus.publish(r)}async publishContractVerified(e,r,i){let n=N(gc.ContractVerified,"contract-testing",{contractId:e.id,provider:e.provider.name,consumer:r,passed:i.passed,failureCount:i.failures.length});await this.eventBus.publish(n)}async publishVerificationFailed(e,r,i){let n=N(gc.VerificationFailed,"contract-testing",{contractId:e.id,provider:e.provider.name,consumer:r,failures:i.failures.map(s=>({endpoint:s.endpoint,type:s.type,message:s.message}))});await this.eventBus.publish(n)}async publishBreakingChangeDetected(e,r,i){let n=N(gc.BreakingChangeDetected,"contract-testing",{contractId:e,changes:r,affectedConsumers:i});await this.eventBus.publish(n)}async prioritizeContracts(e,r){if(!this.sarsaAlgorithm||!this.config.enableSARSA)return f({orderedContracts:e,strategy:"default",confidence:1});if(e.length===0)return f({orderedContracts:[],strategy:"empty",confidence:1});try{let i={id:`contract-priority-${Date.now()}`,features:[r.urgency/10,r.providerLoad/100,r.consumerCount/50,e.length/100,e.filter(u=>u.version.major>=2).length/Math.max(1,e.length),e.reduce((u,d)=>u+d.endpoints.length,0)/1e3,e.reduce((u,d)=>u+d.consumers.length,0)/100,e.filter(u=>u.type==="graphql").length/Math.max(1,e.length),e.filter(u=>u.type==="rest").length/Math.max(1,e.length),e.filter(u=>u.schemas.length>5).length/Math.max(1,e.length)]},n=await this.sarsaAlgorithm.predict(i),s=[...e],a="default";switch(n.action.type){case"sequence-early":s.sort((u,d)=>{let m=u.version.major*10+u.version.minor+u.endpoints.length*.1;return d.version.major*10+d.version.minor+d.endpoints.length*.1-m}),a="high-risk-first";break;case"sequence-late":s.sort((u,d)=>{let m=u.version.major*10+u.version.minor+u.endpoints.length*.1,p=d.version.major*10+d.version.minor+d.endpoints.length*.1;return m-p}),a="low-risk-first";break;case"predict-high":s.sort((u,d)=>d.consumers.length-u.consumers.length),a="high-consumer-first";break;default:a="default";break}let o=await this.calculateOrderingReward(s,r),l=n.action;return await this.sarsaAlgorithm.train({state:i,action:l,reward:o,nextState:i,done:!0}),le.info(`[contract-testing] SARSA prioritized ${e.length} contracts using ${a} strategy (confidence: ${n.confidence.toFixed(2)})`),f({orderedContracts:s,strategy:a,confidence:n.confidence})}catch(i){return le.error("SARSA prioritization failed:",i instanceof Error?i:void 0),f({orderedContracts:e,strategy:"fallback",confidence:.5})}}async calculateOrderingReward(e,r){let i=.5,n=e.slice(0,Math.ceil(e.length/3)),s=n.reduce((a,o)=>a+o.consumers.length,0)/n.length;if(i+=Math.min(.3,s/50),r.urgency>7){let a=n.filter(o=>o.version.major===0).length;i+=Math.min(.2,a/n.length)}return r.providerLoad>80&&(i-=.1),Math.max(0,Math.min(1,i))}async storeContractPattern(e,r,i){if(!(!this.qesona||!this.config.enableQESONA))try{let n={id:`contract-${e.id}`,features:[e.version.major/10,e.version.minor/10,e.endpoints.length/100,e.consumers.length/50,e.schemas.length/50,e.type==="rest"?1:0,e.type==="graphql"?1:0,e.endpoints.filter(a=>a.method==="GET").length/100,e.endpoints.filter(a=>a.method==="POST").length/100,e.endpoints.filter(a=>a.responseSchema).length/100]};if(dr()&&this.qesona.isThreeLoopEnabled()){this.qesona.instantAdapt([e.endpoints.length/100,e.consumers.length/50,e.schemas.length/50,i,r?1:0,e.version.major/10]);try{if(this.qesona.recordOutcome(r?i:-i),this.qesona.shouldConsolidate())try{this.qesona.backgroundConsolidate()}catch{}}catch{}}let s={type:r?"validate":"reject",value:i};this.qesona.createPattern(n,s,{reward:r?i:-i,success:r,quality:i},"test-generation","contract-testing",{contractId:e.id,provider:e.provider.name,version:e.version.toString()}),le.info(`Stored pattern for contract ${e.id} (success: ${r}, quality: ${i.toFixed(2)})`)}catch(n){le.error("Failed to store contract pattern:",n instanceof Error?n:void 0)}}async adaptContractPatterns(e){if(!this.qesona||!this.config.enableQESONA)return{shouldValidate:!0,confidence:.5,strategy:"default"};try{let r={id:`contract-${e.id}`,features:[e.version.major/10,e.version.minor/10,e.endpoints.length/100,e.consumers.length/50,e.schemas.length/50,e.type==="rest"?1:0,e.type==="graphql"?1:0,e.endpoints.filter(n=>n.method==="GET").length/100,e.endpoints.filter(n=>n.method==="POST").length/100,e.endpoints.filter(n=>n.responseSchema).length/100]},i=await this.qesona.adaptPattern(r,"test-generation","contract-testing");if(i.success&&i.pattern){let n=i.pattern.outcome.success,s=i.pattern.action.type;return le.info(`[contract-testing] QESONA adapted pattern for ${e.id}: shouldValidate=${n}, confidence=${i.similarity.toFixed(2)}`),{shouldValidate:n,confidence:i.similarity,strategy:s}}return{shouldValidate:!0,confidence:.5,strategy:"default"}}catch(r){return le.error("QESONA pattern adaptation failed:",r instanceof Error?r:void 0),{shouldValidate:!0,confidence:.5,strategy:"default"}}}async handleImpactAnalysis(e){let i=e.payload.changedFiles.filter(n=>n.includes("contract")||n.includes("api")||n.includes("openapi"));i.length>0&&this.config.enableAutoVerification&&await this.memory.set(`contract-testing:pending-verification:${Date.now()}`,{changedFiles:i,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:3600})}async loadContracts(){let e=await this.memory.search("contract-testing:contract:*",100);for(let r of e){let i=await this.memory.get(r);i&&this.contractStore.set(i.id,i)}}async saveContracts(){let e=Array.from(this.contractStore.entries());for(let[r,i]of e)await this.memory.set(`contract-testing:contract:${r}`,i,{namespace:"contract-testing",persist:!0})}async verifyContractViolation(e,r){let i=U({id:w(),type:"contract-violation",confidence:r,description:`Verify contract violation: ${e.consumer} -> ${e.provider} (${e.endpoint}, ${e.type})`,payload:e,detectedBy:"contract-testing-coordinator",severity:r>.9?"critical":"high"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(le.info("Contract violation verified by consensus"),!0):(le.warn(`Contract violation NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyBreakingChange(e,r){let i=U({id:w(),type:"breaking-change",confidence:r,description:`Verify breaking change: ${e.path} (${e.type}) affecting ${e.affectedConsumers.length} consumers`,payload:e,detectedBy:"contract-testing-coordinator",severity:"critical"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(le.info(`Breaking change at '${e.path}' verified by consensus`),!0):(le.warn(`Breaking change NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifySchemaIncompatibility(e,r){let i=U({id:w(),type:"schema-incompatibility",confidence:r,description:`Verify schema incompatibility: ${e.schema}.${e.field} (expected ${e.expected}, got ${e.actual})`,payload:e,detectedBy:"contract-testing-coordinator",severity:r>.85?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(le.info("Schema incompatibility verified by consensus"),!0):(le.warn(`Schema incompatibility NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}};k();k();X();var dP={strictMode:!1,allowAdditionalProperties:!0,maxRecursionDepth:10,inferenceMinSamples:3},fc=class{constructor(t,e={}){this.memory=t;this.config={...dP,...e}}memory;config;async validateJsonSchema(t,e){try{let r=[];this.validateValue(t,e,"",r,0);let i={isValid:r.length===0,errors:r};return f(i)}catch(r){return g(y(r))}}async validateGraphQLSchema(t){try{let e=[],r=0,i=0,n=0,s=t.split(`
2929
- `),a=!1,o=!1,l=!1,u=0;for(let d=0;d<s.length;d++){let m=s[d].trim();if(!(m.startsWith("#")||m==="")){if(m.startsWith("type ")){let p=m.split(/\s+/)[1]?.replace(/{.*/,"").trim();p==="Query"?o=!0:p==="Mutation"?l=!0:r++,a=!0}u+=(m.match(/{/g)||[]).length,u-=(m.match(/}/g)||[]).length,o&&m.includes(":")&&!m.startsWith("type")&&i++,l&&m.includes(":")&&!m.startsWith("type")&&n++,u===0&&a&&(a=!1,o=!1,l=!1),m.includes("::")&&e.push({message:"Invalid double colon in type definition",locations:[{line:d+1,column:m.indexOf("::")+1}]})}}return u!==0&&e.push({message:"Unbalanced braces in schema",locations:[{line:s.length,column:1}]}),!t.includes("type Query")&&!t.includes("schema {")&&e.push({message:"GraphQL schema must have a Query type or schema definition",locations:[{line:1,column:1}]}),f({isValid:e.length===0,errors:e,typeCount:r,queryCount:i,mutationCount:n})}catch(e){return g(y(e))}}async compareSchemas(t,e){try{let r=[],i=[],n=[];if(t.type!==e.type)return f({isCompatible:!1,additions:[],removals:[],modifications:[{path:"type",oldType:t.type,newType:e.type,isBreaking:!0}]});switch(t.type){case"json-schema":case"openapi":this.compareJsonSchemas(t.content,e.content,r,i,n);break;case"graphql":this.compareGraphQLSchemas(t.content,e.content,r,i,n);break;case"protobuf":this.compareProtobufSchemas(t.content,e.content,r,i,n);break;case"avro":this.compareAvroSchemas(t.content,e.content,r,i,n);break}let s=n.some(a=>a.isBreaking)||i.length>0;return await this.storeComparisonResult(t,e,{isCompatible:!s,additions:r,removals:i,modifications:n}),f({isCompatible:!s,additions:r,removals:i,modifications:n})}catch(r){return g(y(r))}}async inferSchema(t){try{if(t.length===0)return g(new Error("At least one sample is required for schema inference"));t.length<this.config.inferenceMinSamples;let e=this.inferFromSamples(t),r={id:`inferred-${w().slice(0,8)}`,name:"InferredSchema",type:"json-schema",content:JSON.stringify(e,null,2)};return await this.memory.set(`contract-testing:schema:${r.id}`,r,{namespace:"contract-testing"}),f(r)}catch(e){return g(y(e))}}validateValue(t,e,r,i,n){if(n>this.config.maxRecursionDepth){i.push({path:r,keyword:"maxDepth",message:"Maximum recursion depth exceeded",params:{maxDepth:this.config.maxRecursionDepth}});return}if(t===null){if(e.nullable===!0||e.type==="null")return;this.config.strictMode&&i.push({path:r,keyword:"type",message:"Value cannot be null",params:{}});return}let s=e.type;if(e.oneOf){this.validateOneOf(t,e.oneOf,r,i,n);return}if(e.anyOf){this.validateAnyOf(t,e.anyOf,r,i,n);return}if(e.allOf){this.validateAllOf(t,e.allOf,r,i,n);return}if(s){let a=Array.isArray(s)?s:[s],o=this.getJsonType(t);if(!a.some(l=>this.typesMatch(o,l))){i.push({path:r,keyword:"type",message:`Expected type '${a.join(" | ")}' but got '${o}'`,params:{expectedType:a,actualType:o}});return}}if(typeof t=="object"&&t!==null&&!Array.isArray(t)?this.validateObject(t,e,r,i,n):Array.isArray(t)?this.validateArray(t,e,r,i,n):typeof t=="string"?this.validateString(t,e,r,i):typeof t=="number"&&this.validateNumber(t,e,r,i),e.enum){let a=e.enum;a.includes(t)||i.push({path:r,keyword:"enum",message:`Value must be one of: ${a.map(o=>JSON.stringify(o)).join(", ")}`,params:{allowedValues:a}})}"const"in e&&t!==e.const&&i.push({path:r,keyword:"const",message:`Value must be ${JSON.stringify(e.const)}`,params:{expected:e.const}})}validateObject(t,e,r,i,n){let s=e.properties||{},a=e.required||[],o=e.additionalProperties;for(let u of a)Object.hasOwn(t,u)||i.push({path:r?`${r}.${u}`:u,keyword:"required",message:`Required property '${u}' is missing`,params:{missingProperty:u}});for(let[u,d]of Object.entries(t)){let m=r?`${r}.${u}`:u;Object.hasOwn(s,u)?this.validateValue(d,s[u],m,i,n+1):this.config.strictMode&&o===!1?i.push({path:m,keyword:"additionalProperties",message:`Property '${u}' is not allowed`,params:{additionalProperty:u}}):typeof o=="object"&&this.validateValue(d,o,m,i,n+1)}let l=Object.keys(t).length;typeof e.minProperties=="number"&&l<e.minProperties&&i.push({path:r,keyword:"minProperties",message:`Object must have at least ${e.minProperties} properties`,params:{limit:e.minProperties,actual:l}}),typeof e.maxProperties=="number"&&l>e.maxProperties&&i.push({path:r,keyword:"maxProperties",message:`Object must have at most ${e.maxProperties} properties`,params:{limit:e.maxProperties,actual:l}})}validateArray(t,e,r,i,n){let s=e.items;if(s)for(let a=0;a<t.length;a++)this.validateValue(t[a],s,`${r}[${a}]`,i,n+1);if(typeof e.minItems=="number"&&t.length<e.minItems&&i.push({path:r,keyword:"minItems",message:`Array must have at least ${e.minItems} items`,params:{limit:e.minItems,actual:t.length}}),typeof e.maxItems=="number"&&t.length>e.maxItems&&i.push({path:r,keyword:"maxItems",message:`Array must have at most ${e.maxItems} items`,params:{limit:e.maxItems,actual:t.length}}),e.uniqueItems===!0){let a=new Set;for(let o=0;o<t.length;o++){let l=JSON.stringify(t[o]);a.has(l)&&i.push({path:`${r}[${o}]`,keyword:"uniqueItems",message:"Array items must be unique",params:{duplicateIndex:o}}),a.add(l)}}}validateString(t,e,r,i){if(typeof e.minLength=="number"&&t.length<e.minLength&&i.push({path:r,keyword:"minLength",message:`String must be at least ${e.minLength} characters`,params:{limit:e.minLength,actual:t.length}}),typeof e.maxLength=="number"&&t.length>e.maxLength&&i.push({path:r,keyword:"maxLength",message:`String must be at most ${e.maxLength} characters`,params:{limit:e.maxLength,actual:t.length}}),typeof e.pattern=="string"){let n=Xi(e.pattern);n&&!n.test(t)&&i.push({path:r,keyword:"pattern",message:`String must match pattern '${e.pattern}'`,params:{pattern:e.pattern}})}typeof e.format=="string"&&this.validateFormat(t,e.format,r,i)}validateNumber(t,e,r,i){if(typeof e.minimum=="number"&&(e.exclusiveMinimum===!0?t<=e.minimum&&i.push({path:r,keyword:"exclusiveMinimum",message:`Number must be greater than ${e.minimum}`,params:{limit:e.minimum,actual:t}}):t<e.minimum&&i.push({path:r,keyword:"minimum",message:`Number must be at least ${e.minimum}`,params:{limit:e.minimum,actual:t}})),typeof e.maximum=="number"&&(e.exclusiveMaximum===!0?t>=e.maximum&&i.push({path:r,keyword:"exclusiveMaximum",message:`Number must be less than ${e.maximum}`,params:{limit:e.maximum,actual:t}}):t>e.maximum&&i.push({path:r,keyword:"maximum",message:`Number must be at most ${e.maximum}`,params:{limit:e.maximum,actual:t}})),typeof e.multipleOf=="number"){let n=t%e.multipleOf;Math.abs(n)>1e-10&&i.push({path:r,keyword:"multipleOf",message:`Number must be a multiple of ${e.multipleOf}`,params:{multipleOf:e.multipleOf,actual:t}})}}validateFormat(t,e,r,i){let n=!0;switch(e){case"email":n=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t);break;case"uri":case"url":try{new URL(t)}catch{n=!1}break;case"uuid":n=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t);break;case"date":n=!isNaN(Date.parse(t))&&/^\d{4}-\d{2}-\d{2}$/.test(t);break;case"date-time":n=!isNaN(Date.parse(t));break;case"time":n=/^\d{2}:\d{2}(:\d{2})?/.test(t);break;case"ipv4":n=/^(\d{1,3}\.){3}\d{1,3}$/.test(t);break;case"ipv6":n=/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/.test(t);break;default:return}n||i.push({path:r,keyword:"format",message:`String must be a valid ${e}`,params:{format:e}})}validateOneOf(t,e,r,i,n){let s=e.reduce((a,o)=>{let l=[];return this.validateValue(t,o,r,l,n+1),a+(l.length===0?1:0)},0);s!==1&&i.push({path:r,keyword:"oneOf",message:`Value must match exactly one schema (matched ${s})`,params:{matched:s}})}validateAnyOf(t,e,r,i,n){e.some(a=>{let o=[];return this.validateValue(t,a,r,o,n+1),o.length===0})||i.push({path:r,keyword:"anyOf",message:"Value must match at least one schema",params:{}})}validateAllOf(t,e,r,i,n){for(let s of e)this.validateValue(t,s,r,i,n+1)}getJsonType(t){return t===null?"null":Array.isArray(t)?"array":typeof t=="number"?Number.isInteger(t)?"integer":"number":typeof t}typesMatch(t,e){return t===e||e==="number"&&t==="integer"}compareJsonSchemas(t,e,r,i,n){try{let s=D(t),a=D(e);this.compareSchemaObjects(s,a,"",r,i,n)}catch{n.push({path:"",oldType:"unparseable",newType:"unparseable",isBreaking:!0})}}compareSchemaObjects(t,e,r,i,n,s){let a=t.properties||{},o=e.properties||{},l=new Set(t.required||[]),u=new Set(e.required||[]);for(let m of Object.keys(a))if(!Object.hasOwn(o,m)){let p=r?`${r}.${m}`:m;n.push(p)}for(let m of Object.keys(o))if(!Object.hasOwn(a,m)){let p=r?`${r}.${m}`:m;i.push(p),u.has(m)&&s.push({path:p,oldType:"undefined",newType:"required",isBreaking:!0})}t.type!==e.type&&s.push({path:r||"root",oldType:String(t.type||"any"),newType:String(e.type||"any"),isBreaking:!0});let d=Array.from(u);for(let m of d)if(!l.has(m)&&Object.hasOwn(a,m)){let p=r?`${r}.${m}`:m;s.push({path:p,oldType:"optional",newType:"required",isBreaking:!0})}}compareGraphQLSchemas(t,e,r,i,n){let s=this.extractGraphQLTypes(t),a=this.extractGraphQLTypes(e);for(let o of s)a.includes(o)||i.push(`type:${o}`);for(let o of a)s.includes(o)||r.push(`type:${o}`)}extractGraphQLTypes(t){let e=[],r=/type\s+(\w+)/g,i;for(;(i=r.exec(t))!==null;)e.push(i[1]);return e}compareProtobufSchemas(t,e,r,i,n){let s=this.extractProtobufMessages(t),a=this.extractProtobufMessages(e);for(let o of s)a.includes(o)||i.push(`message:${o}`);for(let o of a)s.includes(o)||r.push(`message:${o}`)}extractProtobufMessages(t){let e=[],r=/message\s+(\w+)/g,i;for(;(i=r.exec(t))!==null;)e.push(i[1]);return e}compareAvroSchemas(t,e,r,i,n){try{let s=D(t),a=D(e);s.type!==a.type&&n.push({path:"type",oldType:String(s.type),newType:String(a.type),isBreaking:!0}),s.name!==a.name&&n.push({path:"name",oldType:String(s.name),newType:String(a.name),isBreaking:!0})}catch{n.push({path:"",oldType:"unparseable",newType:"unparseable",isBreaking:!0})}}inferFromSamples(t){if(t.length===0)return{type:"null"};let e=t.map(r=>this.inferType(r));return this.mergeTypes(e)}inferType(t){if(t===null)return{type:"null"};if(Array.isArray(t)){if(t.length===0)return{type:"array",items:{}};let e=t.map(r=>this.inferType(r));return{type:"array",items:this.mergeTypes(e)}}if(typeof t=="object"){let e={},r=[];for(let[i,n]of Object.entries(t))e[i]=this.inferType(n),n!==void 0&&r.push(i);return{type:"object",properties:e,required:r}}if(typeof t=="string"){let e=this.inferStringFormat(t);return e?{type:"string",format:e}:{type:"string"}}return typeof t=="number"?Number.isInteger(t)?{type:"integer"}:{type:"number"}:typeof t=="boolean"?{type:"boolean"}:{}}inferStringFormat(t){if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t))return"email";if(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t))return"uuid";if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(t))return"date-time";if(/^\d{4}-\d{2}-\d{2}$/.test(t))return"date";try{return new URL(t),"uri"}catch{return null}}mergeTypes(t){if(t.length===0)return{};if(t.length===1)return t[0];if(new Set(t.map(r=>r.type)).size===1){let r=t[0].type;if(r==="object"){let i=new Map,n=new Set;for(let u of t){let d=u.properties||{},m=u.required||[];for(let[p,h]of Object.entries(d))i.has(p)||i.set(p,[]),i.get(p).push(h);for(let p of m)n.add(p)}let s={},a=Array.from(i.entries());for(let[u,d]of a)s[u]=this.mergeTypes(d);let l=Array.from(n).filter(u=>t.every(d=>(d.required||[]).includes(u)));return{type:"object",properties:s,required:l}}if(r==="array"){let i=t.map(n=>n.items).filter(n=>n&&Object.keys(n).length>0);return{type:"array",items:i.length>0?this.mergeTypes(i):{}}}return t[0]}return{anyOf:t}}async storeComparisonResult(t,e,r){let i=`contract-testing:schema-comparison:${t.id}:${e.id}:${Date.now()}`;await this.memory.set(i,{oldSchemaId:t.id,newSchemaId:e.id,isCompatible:r.isCompatible,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400*30})}};var Xd=class extends te{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;contractValidator=null;apiCompatibility=null;schemaValidator=null;pluginConfig;get name(){return"contract-testing"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{registerContract:this.registerContract.bind(this),verifyAllConsumers:this.verifyAllConsumers.bind(this),preReleaseCheck:this.preReleaseCheck.bind(this),importFromOpenAPI:this.importFromOpenAPI.bind(this),exportToOpenAPI:this.exportToOpenAPI.bind(this),validateContract:this.validateContract.bind(this),validateRequest:this.validateRequest.bind(this),validateResponse:this.validateResponse.bind(this),validateOpenAPI:this.validateOpenAPI.bind(this),compareVersions:this.compareVersions.bind(this),isBackwardCompatible:this.isBackwardCompatible.bind(this),checkCompatibility:this.isBackwardCompatible.bind(this),getBreakingChanges:this.getBreakingChanges.bind(this),generateMigrationGuide:this.generateMigrationGuide.bind(this),validateJsonSchema:this.validateJsonSchema.bind(this),validateGraphQLSchema:this.validateGraphQLSchema.bind(this),compareSchemas:this.compareSchemas.bind(this),inferSchema:this.inferSchema.bind(this),generateContract:this.inferSchema.bind(this),getCoordinator:()=>this.coordinator,getContractValidator:()=>this.contractValidator,getApiCompatibility:()=>this.apiCompatibility,getSchemaValidator:()=>this.schemaValidator,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[]}}getTaskHandlers(){return new Map([["validate-contract",async e=>{if(!this.contractValidator)return g(new Error("Contract validator not initialized"));let r=e.contract;return r?this.contractValidator.validateContract(r):g(new Error("Invalid validate-contract payload: missing contract"))}],["compare-versions",async e=>{if(!this.apiCompatibility)return g(new Error("API compatibility service not initialized"));let r=e.oldVersion,i=e.newVersion,n=e.oldContract,s=e.newContract;if(n&&s)return this.apiCompatibility.compareVersions(n,s);if(!r||!i)return g(new Error("Invalid compare-versions payload: missing oldVersion or newVersion"));try{let a=nn.parse(r),o=nn.parse(i),l=o.isNewerThan(a)?1:o.equals(a)?0:-1;return{success:!0,value:{oldVersion:r,newVersion:i,comparison:l}}}catch(a){return g(y(a))}}],["check-compatibility",async e=>{if(!this.apiCompatibility)return g(new Error("API compatibility service not initialized"));let r=e.provider,i=e.consumer,n=e.contract,s=e.baselineContract;return n&&s?this.apiCompatibility.isBackwardCompatible(s,n):!r||!i?g(new Error("Invalid check-compatibility payload: missing provider or consumer")):{success:!0,value:{provider:r,consumer:i,compatible:!0}}}],["generate-contract",async e=>{if(!this.schemaValidator)return g(new Error("Schema validator not initialized"));let r=e.serviceSpec,i=e.samples;return i&&i.length>0?this.schemaValidator.inferSchema(i):r?this.schemaValidator.inferSchema([r]):g(new Error("Invalid generate-contract payload: missing serviceSpec"))}]])}async onInitialize(){this.contractValidator=new Fi({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.contractValidator),this.apiCompatibility=new Li(this.memory,this.pluginConfig.apiCompatibility),this.schemaValidator=new fc(this.memory,this.pluginConfig.schemaValidator),this.coordinator=new hc(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.contractValidator=null,this.apiCompatibility=null,this.schemaValidator=null}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("release.PreReleaseStarted",this.handlePreRelease.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"code-intelligence.ImpactAnalysisCompleted":await this.handleImpactAnalysis(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGate(e);break;default:break}}async registerContract(e){this.ensureInitialized();try{let r=await this.coordinator.registerContract(e);return r.success?this.trackSuccessfulOperation("register"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async verifyAllConsumers(e,r){this.ensureInitialized();try{let i=await this.coordinator.verifyAllConsumers(e,r);return i.success?this.trackSuccessfulOperation("verify"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async preReleaseCheck(e,r){this.ensureInitialized();try{return await this.coordinator.preReleaseCheck(e,r)}catch(i){return this.handleError(i)}}async importFromOpenAPI(e){this.ensureInitialized();try{return await this.coordinator.importFromOpenAPI(e)}catch(r){return this.handleError(r)}}async exportToOpenAPI(e){this.ensureInitialized();try{return await this.coordinator.exportToOpenAPI(e)}catch(r){return this.handleError(r)}}async validateContract(e){this.ensureInitialized();try{return await this.contractValidator.validateContract(e)}catch(r){return this.handleError(r)}}async validateRequest(e,r){this.ensureInitialized();try{return await this.contractValidator.validateRequest(e,r)}catch(i){return this.handleError(i)}}async validateResponse(e,r){this.ensureInitialized();try{return await this.contractValidator.validateResponse(e,r)}catch(i){return this.handleError(i)}}async validateOpenAPI(e){this.ensureInitialized();try{return await this.contractValidator.validateOpenAPI(e)}catch(r){return this.handleError(r)}}async compareVersions(e,r){this.ensureInitialized();try{return await this.apiCompatibility.compareVersions(e,r)}catch(i){return this.handleError(i)}}async isBackwardCompatible(e,r){this.ensureInitialized();try{return await this.apiCompatibility.isBackwardCompatible(e,r)}catch(i){return this.handleError(i)}}async getBreakingChanges(e,r){this.ensureInitialized();try{return await this.apiCompatibility.getBreakingChanges(e,r)}catch(i){return this.handleError(i)}}async generateMigrationGuide(e){this.ensureInitialized();try{return await this.apiCompatibility.generateMigrationGuide(e)}catch(r){return this.handleError(r)}}async validateJsonSchema(e,r){this.ensureInitialized();try{return await this.schemaValidator.validateJsonSchema(e,r)}catch(i){return this.handleError(i)}}async validateGraphQLSchema(e){this.ensureInitialized();try{return await this.schemaValidator.validateGraphQLSchema(e)}catch(r){return this.handleError(r)}}async compareSchemas(e,r){this.ensureInitialized();try{return await this.schemaValidator.compareSchemas(e,r)}catch(i){return this.handleError(i)}}async inferSchema(e){this.ensureInitialized();try{return await this.schemaValidator.inferSchema(e)}catch(r){return this.handleError(r)}}async handleImpactAnalysis(e){let r=e.payload;r.changedFiles.filter(n=>n.includes("/api/")||n.includes("/routes/")||n.includes("controller")).length>0&&await this.memory.set(`contract-testing:pending-impact:${r.analysisId}`,r,{namespace:"contract-testing",ttl:3600})}async handleQualityGate(e){let r=e.payload;r.checks.find(n=>n.name==="contract-testing")||await this.memory.set(`contract-testing:quality-gate-warning:${r.gateId}`,{warning:"Contract testing not included in quality gate",timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400})}async handlePreRelease(e){let r=e.payload,i=r.providerName||r.serviceName;if(!i){await this.memory.set(`contract-testing:pre-release-warning:${e.id}`,{warning:"Pre-release event received without provider/service name",eventId:e.id,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400});return}let n=`contract-testing:pre-release:${e.id}`;if(await this.memory.set(n,{providerName:i,version:r.version,status:"pending",startedAt:new Date().toISOString()},{namespace:"contract-testing",ttl:3600}),r.contractPath)try{let s=he.create(r.contractPath),a=await this.preReleaseCheck(i,s);if(a.success){let o=a.value;await this.memory.set(n,{providerName:i,version:r.version,status:o.canRelease?"passed":"failed",completedAt:new Date().toISOString(),breakingChanges:o.breakingChanges.length,affectedConsumers:o.affectedConsumers.length,recommendations:o.recommendations},{namespace:"contract-testing",ttl:86400}),this.eventBus.publish({id:`${e.id}-result`,type:"contract-testing.PreReleaseVerificationCompleted",source:"contract-testing",timestamp:new Date,payload:{providerName:i,version:r.version,canRelease:o.canRelease,breakingChanges:o.breakingChanges.length,affectedConsumers:o.affectedConsumers.map(l=>l.name)}})}}catch(s){await this.memory.set(n,{providerName:i,version:r.version,status:"error",error:P(s),completedAt:new Date().toISOString()},{namespace:"contract-testing",ttl:86400})}if(r.providerUrl)try{let s=await this.verifyAllConsumers(i,r.providerUrl);if(s.success){let a=s.value;await this.memory.set(`${n}:verification`,{providerName:i,version:r.version,status:a.canDeploy?"passed":"failed",completedAt:new Date().toISOString(),totalConsumers:a.totalConsumers,passedConsumers:a.passedConsumers,failedConsumers:a.failedConsumers},{namespace:"contract-testing",ttl:86400}),this.eventBus.publish({id:`${e.id}-consumer-result`,type:"contract-testing.ConsumerVerificationCompleted",source:"contract-testing",timestamp:new Date,payload:{providerName:i,version:r.version,canDeploy:a.canDeploy,totalConsumers:a.totalConsumers,passedConsumers:a.passedConsumers,failedConsumers:a.failedConsumers}})}}catch(s){await this.memory.set(`${n}:verification`,{providerName:i,version:r.version,status:"error",error:P(s),completedAt:new Date().toISOString()},{namespace:"contract-testing",ttl:86400})}}ensureInitialized(){if(!this._initialized)throw new Error("ContractTestingPlugin is not initialized");if(!this.coordinator||!this.contractValidator||!this.apiCompatibility||!this.schemaValidator)throw new Error("ContractTestingPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function kv(c,t,e,r,i){return new Xd(c,t,e,r,i)}_();k();bs();_();k();Pe();var mP={baselineDirectory:".visual-tests/baselines",diffDirectory:".visual-tests/diffs",defaultViewport:{width:1280,height:720,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},diffThreshold:.1,antialiasDetection:!0,captureTimeout:3e4,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},Dv=x.create("visual-accessibility/visual-tester"),Zd=class{config;memory;llmRouter;vibiumClient=null;browserAvailable=null;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...mP,...e}}setVibiumClient(t){this.vibiumClient=t,this.browserAvailable=null}getVibiumClient(){return this.vibiumClient}async isBrowserAvailable(){if(this.browserAvailable!==null)return this.browserAvailable;if(!this.vibiumClient)return this.browserAvailable=!1,!1;try{return this.browserAvailable=await this.vibiumClient.isAvailable(),this.browserAvailable}catch{return this.browserAvailable=!1,!1}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(t){return ae(t)}async captureScreenshot(t,e){try{let r=e?.viewport||this.config.defaultViewport,i=w(),n=new Date,s=this.hashUrl(t),a=`${r.width}x${r.height}`,o=he.create(`${this.config.baselineDirectory}/${s}_${a}_${i}.png`),l=this.estimateLoadTime(t,r),u={browser:"chromium",os:process.platform,selector:void 0,fullPage:e?.fullPage??!1,loadTime:l},d={id:i,url:t,viewport:r,timestamp:n,path:o,metadata:u};return await this.storeScreenshotMetadata(d),f(d)}catch(r){return g(y(r))}}async captureElement(t,e,r){try{let i=r?.viewport||this.config.defaultViewport,n=w(),s=new Date,a=he.create(`${this.config.baselineDirectory}/${n}.png`),o={browser:"chromium",os:process.platform,selector:e,fullPage:!1,loadTime:this.estimateLoadTime(t,i)},l={id:n,url:t,viewport:i,timestamp:s,path:a,metadata:o};return await this.storeScreenshotMetadata(l),f(l)}catch(i){return g(y(i))}}async compare(t,e){try{let r=await this.getScreenshotById(e);if(!r)return g(new Error(`Baseline not found: ${e}`));let i=this.calculateDiff(r,t);return await this.storeDiffResult(i),f(i)}catch(r){return g(y(r))}}async compareWithBrowser(t,e,r){try{let i=await this.getScreenshotById(e);if(!i)return g(new Error(`Baseline not found: ${e}`));let n=r??this.config.diffThreshold;if(this.vibiumClient&&await this.isBrowserAvailable()){let a=await this.executeBrowserComparison(i,t,n);if(a.success)return await this.storeDiffResult(a.value),a;Dv.warn(`Browser comparison failed, falling back to deterministic: ${a.error.message}`)}let s=this.calculateDiff(i,t);return await this.storeDiffResult(s),f(s)}catch(i){return g(y(i))}}async executeBrowserComparison(t,e,r){if(!this.vibiumClient)return g(new Error("Vibium client not available"));try{let i=await this.vibiumClient.compareScreenshots(t.path.value,e.path.value,r/100);if(!i.success)return g(i.error);let n=i.value,s=this.convertVibiumResult(t,e,n,r);return f(s)}catch(i){return g(y(i))}}convertVibiumResult(t,e,r,i){let n=r.differencePercent,s;n===0?s="identical":n<=i?s="acceptable":n<=5?s="changed":s="failed";let a=t.viewport.width*t.viewport.height,o=Math.floor(a*n/100),l=r.diffRegions.map((d,m)=>({x:d.x,y:d.y,width:d.width,height:d.height,changeType:"modified",significance:n>2?"high":n>.5?"medium":"low"})),u=r.diffImagePath?he.create(r.diffImagePath):n>i?he.create(`${this.config.diffDirectory}/${e.id}_diff.png`):void 0;return{baselineId:t.id,comparisonId:e.id,diffPercentage:n,diffPixels:o,diffImagePath:u,regions:l,status:s}}async setBaseline(t){try{let e=this.getBaselineKey(t.url,t.viewport);return await this.memory.set(`visual-accessibility:baseline:${e}`,t,{namespace:"visual-accessibility",persist:!0}),await this.memory.set(`visual-accessibility:screenshot:${t.id}`,t,{namespace:"visual-accessibility",persist:!0}),f(e)}catch(e){return g(y(e))}}async getBaseline(t,e){let r=this.getBaselineKey(t,e);return await this.memory.get(`visual-accessibility:baseline:${r}`)??null}async analyzeDiffWithLLM(t){if(!this.isLLMAnalysisAvailable())return null;try{let e=t.regions.slice(0,5).map(i=>{let n=i.width*i.height;return`- Region at (${i.x}, ${i.y}): ${i.width}x${i.height}, ${n} pixels changed, ${i.changeType} (${i.significance} significance)`}).join(`
2928
+ // Follow the new type specification`,s=!1;break;case"enum-change":i=`Update enum usage: ${e.description}`,n=`// Remove usage of deprecated enum value at ${e.location}`,s=!0;break;case"removed-field":i=`Remove field usage: ${e.description}`,n=`// Remove references to ${e.location}`,s=!0;break;case"response-code":i=`Update response handling: ${e.description}`,n=`// Update error handling for ${e.location}`,s=!1;break;case"removed-endpoint":i=`Migrate from removed endpoint: ${e.description}`,n=e.migrationPath?`// ${e.migrationPath}`:`// Find alternative for ${e.location}`,s=!1;break;default:i=e.description,n=void 0,s=!1}return{order:t,description:i,codeChanges:n,automated:s}}estimateEffort(t){if(t.length===0)return"trivial";let e=t.filter(i=>i.impact==="high").length,r=t.filter(i=>i.impact==="medium").length;return e>5||t.length>10?"major":e>2||r>5?"moderate":e>0||t.length>3?"minor":"trivial"}async storeComparisonResult(t,e,r){let i=`contract-testing:comparison:${t.id}:${t.version.toString()}:${e.version.toString()}`;await this.memory.set(i,{oldVersion:t.version.toString(),newVersion:e.version.toString(),isCompatible:r.isCompatible,breakingChangeCount:r.breakingChanges.length,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400*90})}};var uP={stateSize:10,actionSize:4,hiddenLayers:[128,128],minReplaySize:100},pc=class extends ve{qNetwork;replayBufferClass;sarsaConfig;actions=[];constructor(t={}){super("sarsa","value-based"),this.sarsaConfig={...uP,...t},this.initializeActions(),this.qNetwork=new J({layerSizes:[this.sarsaConfig.stateSize,...this.sarsaConfig.hiddenLayers,this.sarsaConfig.actionSize],activations:Array(this.sarsaConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.replayBufferClass=new At(this.config.replayBufferSize,!1)}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.qNetwork.forward(e),i=this.argmax(r),n=this.actions[i];return{action:n,confidence:.7,value:r[i],reasoning:`SARSA: ${n.type}`}}async trainCore(t){for(let i of t)this.replayBufferClass.add(i);if(!this.replayBufferClass.isReady(this.sarsaConfig.minReplaySize))return this.getStats();let e=this.replayBufferClass.sample(this.config.batchSize),r=0;for(let i=0;i<e.length;i++){let n=e[i],s=e[i+1],a=this.prepareState(n.state),o=this.actionToIndex(n.action),l=this.qNetwork.forward(a),u=l[o],d=0;if(s&&!n.done){let h=this.prepareState(s.state),v=this.actionToIndex(s.action);d=this.qNetwork.forward(h)[v]}let m=n.reward+this.config.discountFactor*d,p=new Float32Array(l.length);for(let h=0;h<p.length;h++)p[h]=h===o?m:l[h];r+=Math.abs(this.qNetwork.train(a,p,new Fe))}return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/e.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural SARSA for Defect Prediction Sequencing",capabilities:["On-policy learning","Neural Q-network"],hyperparameters:{stateSize:this.sarsaConfig.stateSize,actionSize:this.sarsaConfig.actionSize,hiddenLayers:this.sarsaConfig.hiddenLayers.join(",")},stats:this.stats}}prepareState(t){let e=t.features.slice(0,this.sarsaConfig.stateSize);for(;e.length<this.sarsaConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]/=r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"predict-high",value:1},{type:"predict-low",value:0},{type:"sequence-early",value:"high-risk"},{type:"sequence-late",value:"low-risk"}],this.sarsaConfig.actionSize=this.actions.length,this.qNetwork=new J({layerSizes:[this.sarsaConfig.stateSize,...this.sarsaConfig.hiddenLayers,this.sarsaConfig.actionSize],activations:Array(this.sarsaConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate})}actionToIndex(t){let e=`${t.type}:${JSON.stringify(t.value)}`;for(let r=0;r<this.actions.length;r++)if(`${this.actions[r].type}:${JSON.stringify(this.actions[r].value)}`===e)return r;return 0}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}async exportCustomData(){return{qNetwork:this.qNetwork.getParameters(),sarsaConfig:this.sarsaConfig}}async importCustomData(t){t.qNetwork&&this.qNetwork.setParameters(t.qNetwork),t.sarsaConfig&&(this.sarsaConfig={...this.sarsaConfig,...t.sarsaConfig}),this.initialized=!0}async resetAlgorithm(){this.qNetwork=new J({layerSizes:[this.sarsaConfig.stateSize,...this.sarsaConfig.hiddenLayers,this.sarsaConfig.actionSize],activations:Array(this.sarsaConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.replayBufferClass.clear()}};vt();X();var gc={ContractVerified:"contract-testing.ContractVerified",BreakingChangeDetected:"contract-testing.BreakingChangeDetected",ContractPublished:"contract-testing.ContractPublished",ConsumerContractCreated:"contract-testing.ConsumerContractCreated",VerificationFailed:"contract-testing.VerificationFailed"},dP={maxConcurrentWorkflows:5,defaultTimeout:6e4,enableAutoVerification:!0,publishEvents:!0,enableSARSA:!0,enableQESONA:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},le=x.create("contract-testing"),hc=class extends ie{constructor(e,r,i,n={},s){let a={...dP,...n};super(e,"contract-testing",a,{verifyFindingTypes:["contract-violation","breaking-change","schema-incompatibility"]});this.memory=r;this.agentCoordinator=i;this.contractValidator=new Fi({memory:r,llmRouter:s}),this.apiCompatibility=new Li(r),this.httpClient=is(),this.fileReader=new it({projectRoot:Ce()})}memory;agentCoordinator;contractValidator;apiCompatibility;httpClient;fileReader;contractStore=new Map;sarsaAlgorithm;qesona;async onInitialize(){if(this.config.enableSARSA)try{this.sarsaAlgorithm=new pc({stateSize:10,actionSize:4,hiddenLayers:[64,64]}),le.info("SARSA algorithm created successfully")}catch(e){throw le.error("Failed to create SARSA:",e instanceof Error?e:void 0),new Error(`SARSA creation failed: ${P(e)}`)}if(this.config.enableQESONA)try{this.qesona=await De({domain:"contract-testing",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:5e3,minConfidence:.6}),le.info("PersistentSONAEngine initialized successfully")}catch(e){le.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),le.warn("Continuing without SONA pattern persistence"),this.qesona=void 0}this.subscribeToEvents(),await this.loadContracts()}async onDispose(){await this.saveContracts(),this.qesona&&(await this.qesona.close(),this.qesona=void 0),this.sarsaAlgorithm=void 0,this.contractStore.clear()}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this))}getActiveWorkflows(){return super.getActiveWorkflows()}async registerContract(e){try{let r=await this.contractValidator.validateContract(e);if(!r.success)return r;if(!r.value.isValid){let i=r.value.errors.map(n=>n.message).join("; ");return g(new Error(`Contract validation failed: ${i}`))}return this.contractStore.set(e.id,e),await this.memory.set(`contract-testing:contract:${e.id}`,e,{namespace:"contract-testing",persist:!0}),this.config.publishEvents&&await this.publishContractRegistered(e),f(e.id)}catch(r){return g(y(r))}}async verifyAllConsumers(e,r){let i=w();try{if(this.startWorkflow(i,"verify"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&le.warn("Topology degraded, using conservative verification strategy"),this.minCutMixin.shouldPauseOperations())return g(new Error("Contract verification paused: topology is in critical state"));let n=await this.findContractsByProvider(e);if(n.length===0)return this.completeWorkflow(i),f({provider:e,totalConsumers:0,passedConsumers:0,failedConsumers:[],results:[],canDeploy:!0});if(this.config.enableSARSA&&n.length>1){let d={urgency:5,providerLoad:50,consumerCount:n.reduce((p,h)=>p+h.consumers.length,0)},m=await this.prioritizeContracts(n,d);m.success&&(n=m.value.orderedContracts,le.info(`[contract-testing] Using ${m.value.strategy} strategy for contract verification order (confidence: ${m.value.confidence.toFixed(2)})`))}let s=await this.spawnVerificationAgent(i,e);if(!s.success)return this.failWorkflow(i,s.error.message),s;this.addAgentToWorkflow(i,s.value);let a=[],o=[];for(let d of n){for(let m of d.consumers){let p=await this.verifyConsumerContract(d,m.name,r);a.push(p),p.passed?this.config.publishEvents&&await this.publishContractVerified(d,m.name,p):(o.push(m.name),this.config.publishEvents&&await this.publishVerificationFailed(d,m.name,p))}this.updateWorkflowProgress(i,a.length/n.length*100)}await this.agentCoordinator.stop(s.value),this.completeWorkflow(i);let l=Array.from(new Set(o)),u=n.flatMap(d=>d.consumers.map(m=>m.name)).filter(d=>!l.includes(d)).length;return f({provider:e,totalConsumers:n.reduce((d,m)=>d+m.consumers.length,0),passedConsumers:u,failedConsumers:l,results:a,canDeploy:l.length===0})}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async preReleaseCheck(e,r){let i=w();try{if(this.startWorkflow(i,"compare"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&le.warn("Topology degraded, using conservative pre-release check"),this.minCutMixin.shouldPauseOperations())return g(new Error("Pre-release check paused: topology is in critical state"));let n=await this.loadContractFromPath(r);if(!n)return this.failWorkflow(i,"Failed to load contract from path"),g(new Error("Failed to load contract from path"));let s=await this.findContractsByProvider(e),a=s.length>0?s[0]:null;if(!a)return this.completeWorkflow(i),f({breakingChanges:[],affectedConsumers:[],canRelease:!0,recommendations:["No existing contract found. This will be the first version."]});let o=await this.apiCompatibility.compareVersions(a,n);if(!o.success)return this.failWorkflow(i,o.error.message),o;let{breakingChanges:l,deprecations:u}=o.value,d=[];for(let p of a.consumers){let h=l.filter(v=>v.affectedConsumers.includes(p.name));h.length>0&&d.push({name:p.name,team:p.team,breakingChanges:h,notified:!1})}let m=[];if(l.length>0){m.push(`${l.length} breaking changes detected. Coordinate with affected consumers before release.`);let p=await this.apiCompatibility.generateMigrationGuide(l);p.success&&m.push(`Migration effort estimated as: ${p.value.estimatedEffort}`)}return u.length>0&&m.push(`${u.length} deprecations detected. Consider communicating removal timeline.`),l.length===0&&u.length===0&&m.push("No breaking changes detected. Safe to release."),this.config.publishEvents&&l.length>0&&await this.publishBreakingChangeDetected(n.id,l,d.map(p=>p.name)),this.completeWorkflow(i),f({breakingChanges:l,affectedConsumers:d,canRelease:l.length===0,recommendations:m})}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async importFromOpenAPI(e){let r=w();try{this.startWorkflow(r,"import");let i=await this.loadFileContent(e);if(!i)return this.failWorkflow(r,"Failed to load OpenAPI spec"),g(new Error("Failed to load OpenAPI spec"));let n=await this.contractValidator.validateOpenAPI(i);if(!n.success)return this.failWorkflow(r,n.error.message),n;if(!n.value.isValid){let a=n.value.errors.map(o=>o.message).join("; ");return this.failWorkflow(r,a),g(new Error(`Invalid OpenAPI spec: ${a}`))}let s=this.parseOpenAPIToContract(i);return this.contractStore.set(s.id,s),await this.memory.set(`contract-testing:contract:${s.id}`,s,{namespace:"contract-testing",persist:!0}),this.completeWorkflow(r),f(s)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async exportToOpenAPI(e){let r=w();try{this.startWorkflow(r,"export");let i=this.contractStore.get(e);if(!i)return this.failWorkflow(r,"Contract not found"),g(new Error(`Contract not found: ${e}`));let n=this.contractToOpenAPI(i);return this.completeWorkflow(r),f(n)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async verifyConsumerContract(e,r,i){let n=[],s=[],a=i.startsWith("http://")||i.startsWith("https://");for(let o of e.endpoints){let l=`${i}${o.path}`,u=`${o.method} ${o.path}`;if(a)try{let d=await this.verifyEndpoint(l,o.method,o);d.success?d.warning&&s.push({endpoint:u,message:d.warning,severity:"low"}):n.push({endpoint:u,type:d.errorType,expected:d.expected,actual:d.actual,message:d.message})}catch(d){n.push({endpoint:u,type:"connection-error",expected:"reachable",actual:"error",message:`Failed to verify endpoint: ${P(d)}`})}else i||n.push({endpoint:u,type:"connection-error",expected:"reachable",actual:"unreachable",message:`Endpoint ${u} is not reachable (no provider URL)`})}return{contractId:e.id,provider:e.provider.name,consumer:r,passed:n.length===0,failures:n,warnings:s,timestamp:new Date}}async verifyEndpoint(e,r,i){let s={timeout:1e4,retries:1,circuitBreaker:!1},a;switch(r){case"GET":case"HEAD":a=await this.httpClient.get(e,s);break;case"POST":a=await this.httpClient.post(e,{},s);break;case"PUT":a=await this.httpClient.put(e,{},s);break;case"PATCH":a=await this.httpClient.patch(e,{},s);break;case"DELETE":a=await this.httpClient.delete(e,s);break;case"OPTIONS":a=await this.httpClient.get(e,s);break;default:a=await this.httpClient.get(e,s)}if(!a.success)return{success:!1,errorType:"connection-error",expected:"successful response",actual:`error: ${a.error.message}`,message:`Endpoint unreachable: ${a.error.message}`};let o=a.value;if(i.examples&&i.examples.length>0){let d=i.examples.map(m=>m.statusCode);if(!d.includes(o.status))return{success:!1,errorType:"status-mismatch",expected:d.join(" or "),actual:String(o.status),message:`Expected status ${d.join("/")} but got ${o.status}`}}let l,u=o.headers.get("Deprecation");return u&&(l=`Endpoint is deprecated: ${u}`),{success:!0,errorType:"",expected:"",actual:"",message:"Endpoint verified successfully",warning:l}}async findContractsByProvider(e){let r=[],i=Array.from(this.contractStore.values());for(let s of i)s.provider.name===e&&r.push(s);let n=await this.memory.search("contract-testing:contract:*",100);for(let s of n){let a=await this.memory.get(s);a&&a.provider.name===e&&(this.contractStore.has(a.id)||r.push(a))}return r}async loadContractFromPath(e){let r=await this.loadFileContent(e);if(!r)return null;try{let i=e.value.toLowerCase();if(i.endsWith(".json")){let n=D(r);return n.openapi||n.swagger?this.parseOpenAPIToContract(r):n}else if(i.endsWith(".yaml")||i.endsWith(".yml"))return le.warn("YAML contract files not yet supported:"),null;return D(r)}catch(i){return le.error(`Failed to parse contract from ${e.value}: ${P(i)}`),null}}async loadFileContent(e){let r=await this.fileReader.readFile(e.value);return r.success?r.value:(le.error(`Failed to read file ${e.value}:`,r.error),null)}parseOpenAPIToContract(e){let r=D(e),i=r.info||{},n=r.paths||{},s=[],a=[];for(let[u,d]of Object.entries(n)){let m=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let p of m){let h=d[p.toLowerCase()];h&&s.push({path:u,method:p,requestSchema:this.extractRequestSchema(h),responseSchema:this.extractResponseSchema(h),headers:{},examples:[]})}}let l=(r.components||{}).schemas||{};for(let[u,d]of Object.entries(l))a.push({id:u,name:u,type:"openapi",content:JSON.stringify(d)});return{id:w(),name:i.title||"Imported Contract",version:nn.parse(i.version||"1.0.0"),type:"rest",provider:{name:i.title||"Unknown Provider",version:i.version||"1.0.0"},consumers:[],endpoints:s,schemas:a}}extractRequestSchema(e){let r=e.requestBody;if(r){let i=r.content;if(i){let n=i["application/json"];if(n?.schema){let s=n.schema.$ref;if(s)return s.split("/").pop()}}}}extractResponseSchema(e){let r=e.responses;if(r){let i=r[200]||r[201];if(i){let n=i.content;if(n){let s=n["application/json"];if(s?.schema){let a=s.schema.$ref;if(a)return a.split("/").pop()}}}}}contractToOpenAPI(e){let r={};for(let s of e.endpoints){r[s.path]||(r[s.path]={});let a={summary:`${s.method} ${s.path}`,responses:{200:{description:"Success",content:s.responseSchema?{"application/json":{schema:{$ref:`#/components/schemas/${s.responseSchema}`}}}:void 0}}};s.requestSchema&&(a.requestBody={content:{"application/json":{schema:{$ref:`#/components/schemas/${s.requestSchema}`}}}}),r[s.path][s.method.toLowerCase()]=a}let i={};for(let s of e.schemas)try{i[s.id]=D(s.content)}catch{i[s.id]={type:"object"}}let n={openapi:"3.0.3",info:{title:e.name,version:e.version.toString()},paths:r,components:{schemas:i}};return JSON.stringify(n,null,2)}async spawnVerificationAgent(e,r){let i={name:`contract-verifier-${e.slice(0,8)}`,domain:"contract-testing",type:"validator",capabilities:["contract-verification","http-testing"],config:{workflowId:e,providerName:r}};return this.agentCoordinator.spawn(i)}async publishContractRegistered(e){let r=N(gc.ContractPublished,"contract-testing",{contractId:e.id,version:e.version.toString(),provider:e.provider.name});await this.eventBus.publish(r)}async publishContractVerified(e,r,i){let n=N(gc.ContractVerified,"contract-testing",{contractId:e.id,provider:e.provider.name,consumer:r,passed:i.passed,failureCount:i.failures.length});await this.eventBus.publish(n)}async publishVerificationFailed(e,r,i){let n=N(gc.VerificationFailed,"contract-testing",{contractId:e.id,provider:e.provider.name,consumer:r,failures:i.failures.map(s=>({endpoint:s.endpoint,type:s.type,message:s.message}))});await this.eventBus.publish(n)}async publishBreakingChangeDetected(e,r,i){let n=N(gc.BreakingChangeDetected,"contract-testing",{contractId:e,changes:r,affectedConsumers:i});await this.eventBus.publish(n)}async prioritizeContracts(e,r){if(!this.sarsaAlgorithm||!this.config.enableSARSA)return f({orderedContracts:e,strategy:"default",confidence:1});if(e.length===0)return f({orderedContracts:[],strategy:"empty",confidence:1});try{let i={id:`contract-priority-${Date.now()}`,features:[r.urgency/10,r.providerLoad/100,r.consumerCount/50,e.length/100,e.filter(u=>u.version.major>=2).length/Math.max(1,e.length),e.reduce((u,d)=>u+d.endpoints.length,0)/1e3,e.reduce((u,d)=>u+d.consumers.length,0)/100,e.filter(u=>u.type==="graphql").length/Math.max(1,e.length),e.filter(u=>u.type==="rest").length/Math.max(1,e.length),e.filter(u=>u.schemas.length>5).length/Math.max(1,e.length)]},n=await this.sarsaAlgorithm.predict(i),s=[...e],a="default";switch(n.action.type){case"sequence-early":s.sort((u,d)=>{let m=u.version.major*10+u.version.minor+u.endpoints.length*.1;return d.version.major*10+d.version.minor+d.endpoints.length*.1-m}),a="high-risk-first";break;case"sequence-late":s.sort((u,d)=>{let m=u.version.major*10+u.version.minor+u.endpoints.length*.1,p=d.version.major*10+d.version.minor+d.endpoints.length*.1;return m-p}),a="low-risk-first";break;case"predict-high":s.sort((u,d)=>d.consumers.length-u.consumers.length),a="high-consumer-first";break;default:a="default";break}let o=await this.calculateOrderingReward(s,r),l=n.action;return await this.sarsaAlgorithm.train({state:i,action:l,reward:o,nextState:i,done:!0}),le.info(`[contract-testing] SARSA prioritized ${e.length} contracts using ${a} strategy (confidence: ${n.confidence.toFixed(2)})`),f({orderedContracts:s,strategy:a,confidence:n.confidence})}catch(i){return le.error("SARSA prioritization failed:",i instanceof Error?i:void 0),f({orderedContracts:e,strategy:"fallback",confidence:.5})}}async calculateOrderingReward(e,r){let i=.5,n=e.slice(0,Math.ceil(e.length/3)),s=n.reduce((a,o)=>a+o.consumers.length,0)/n.length;if(i+=Math.min(.3,s/50),r.urgency>7){let a=n.filter(o=>o.version.major===0).length;i+=Math.min(.2,a/n.length)}return r.providerLoad>80&&(i-=.1),Math.max(0,Math.min(1,i))}async storeContractPattern(e,r,i){if(!(!this.qesona||!this.config.enableQESONA))try{let n={id:`contract-${e.id}`,features:[e.version.major/10,e.version.minor/10,e.endpoints.length/100,e.consumers.length/50,e.schemas.length/50,e.type==="rest"?1:0,e.type==="graphql"?1:0,e.endpoints.filter(a=>a.method==="GET").length/100,e.endpoints.filter(a=>a.method==="POST").length/100,e.endpoints.filter(a=>a.responseSchema).length/100]};if(dr()&&this.qesona.isThreeLoopEnabled()){this.qesona.instantAdapt([e.endpoints.length/100,e.consumers.length/50,e.schemas.length/50,i,r?1:0,e.version.major/10]);try{if(this.qesona.recordOutcome(r?i:-i),this.qesona.shouldConsolidate())try{this.qesona.backgroundConsolidate()}catch{}}catch{}}let s={type:r?"validate":"reject",value:i};this.qesona.createPattern(n,s,{reward:r?i:-i,success:r,quality:i},"test-generation","contract-testing",{contractId:e.id,provider:e.provider.name,version:e.version.toString()}),le.info(`Stored pattern for contract ${e.id} (success: ${r}, quality: ${i.toFixed(2)})`)}catch(n){le.error("Failed to store contract pattern:",n instanceof Error?n:void 0)}}async adaptContractPatterns(e){if(!this.qesona||!this.config.enableQESONA)return{shouldValidate:!0,confidence:.5,strategy:"default"};try{let r={id:`contract-${e.id}`,features:[e.version.major/10,e.version.minor/10,e.endpoints.length/100,e.consumers.length/50,e.schemas.length/50,e.type==="rest"?1:0,e.type==="graphql"?1:0,e.endpoints.filter(n=>n.method==="GET").length/100,e.endpoints.filter(n=>n.method==="POST").length/100,e.endpoints.filter(n=>n.responseSchema).length/100]},i=await this.qesona.adaptPattern(r,"test-generation","contract-testing");if(i.success&&i.pattern){let n=i.pattern.outcome.success,s=i.pattern.action.type;return le.info(`[contract-testing] QESONA adapted pattern for ${e.id}: shouldValidate=${n}, confidence=${i.similarity.toFixed(2)}`),{shouldValidate:n,confidence:i.similarity,strategy:s}}return{shouldValidate:!0,confidence:.5,strategy:"default"}}catch(r){return le.error("QESONA pattern adaptation failed:",r instanceof Error?r:void 0),{shouldValidate:!0,confidence:.5,strategy:"default"}}}async handleImpactAnalysis(e){let i=e.payload.changedFiles.filter(n=>n.includes("contract")||n.includes("api")||n.includes("openapi"));i.length>0&&this.config.enableAutoVerification&&await this.memory.set(`contract-testing:pending-verification:${Date.now()}`,{changedFiles:i,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:3600})}async loadContracts(){let e=await this.memory.search("contract-testing:contract:*",100);for(let r of e){let i=await this.memory.get(r);i&&this.contractStore.set(i.id,i)}}async saveContracts(){let e=Array.from(this.contractStore.entries());for(let[r,i]of e)await this.memory.set(`contract-testing:contract:${r}`,i,{namespace:"contract-testing",persist:!0})}async verifyContractViolation(e,r){let i=U({id:w(),type:"contract-violation",confidence:r,description:`Verify contract violation: ${e.consumer} -> ${e.provider} (${e.endpoint}, ${e.type})`,payload:e,detectedBy:"contract-testing-coordinator",severity:r>.9?"critical":"high"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(le.info("Contract violation verified by consensus"),!0):(le.warn(`Contract violation NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyBreakingChange(e,r){let i=U({id:w(),type:"breaking-change",confidence:r,description:`Verify breaking change: ${e.path} (${e.type}) affecting ${e.affectedConsumers.length} consumers`,payload:e,detectedBy:"contract-testing-coordinator",severity:"critical"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(le.info(`Breaking change at '${e.path}' verified by consensus`),!0):(le.warn(`Breaking change NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifySchemaIncompatibility(e,r){let i=U({id:w(),type:"schema-incompatibility",confidence:r,description:`Verify schema incompatibility: ${e.schema}.${e.field} (expected ${e.expected}, got ${e.actual})`,payload:e,detectedBy:"contract-testing-coordinator",severity:r>.85?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(le.info("Schema incompatibility verified by consensus"),!0):(le.warn(`Schema incompatibility NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}};k();k();X();var mP={strictMode:!1,allowAdditionalProperties:!0,maxRecursionDepth:10,inferenceMinSamples:3},fc=class{constructor(t,e={}){this.memory=t;this.config={...mP,...e}}memory;config;async validateJsonSchema(t,e){try{let r=[];this.validateValue(t,e,"",r,0);let i={isValid:r.length===0,errors:r};return f(i)}catch(r){return g(y(r))}}async validateGraphQLSchema(t){try{let e=[],r=0,i=0,n=0,s=t.split(`
2929
+ `),a=!1,o=!1,l=!1,u=0;for(let d=0;d<s.length;d++){let m=s[d].trim();if(!(m.startsWith("#")||m==="")){if(m.startsWith("type ")){let p=m.split(/\s+/)[1]?.replace(/{.*/,"").trim();p==="Query"?o=!0:p==="Mutation"?l=!0:r++,a=!0}u+=(m.match(/{/g)||[]).length,u-=(m.match(/}/g)||[]).length,o&&m.includes(":")&&!m.startsWith("type")&&i++,l&&m.includes(":")&&!m.startsWith("type")&&n++,u===0&&a&&(a=!1,o=!1,l=!1),m.includes("::")&&e.push({message:"Invalid double colon in type definition",locations:[{line:d+1,column:m.indexOf("::")+1}]})}}return u!==0&&e.push({message:"Unbalanced braces in schema",locations:[{line:s.length,column:1}]}),!t.includes("type Query")&&!t.includes("schema {")&&e.push({message:"GraphQL schema must have a Query type or schema definition",locations:[{line:1,column:1}]}),f({isValid:e.length===0,errors:e,typeCount:r,queryCount:i,mutationCount:n})}catch(e){return g(y(e))}}async compareSchemas(t,e){try{let r=[],i=[],n=[];if(t.type!==e.type)return f({isCompatible:!1,additions:[],removals:[],modifications:[{path:"type",oldType:t.type,newType:e.type,isBreaking:!0}]});switch(t.type){case"json-schema":case"openapi":this.compareJsonSchemas(t.content,e.content,r,i,n);break;case"graphql":this.compareGraphQLSchemas(t.content,e.content,r,i,n);break;case"protobuf":this.compareProtobufSchemas(t.content,e.content,r,i,n);break;case"avro":this.compareAvroSchemas(t.content,e.content,r,i,n);break}let s=n.some(a=>a.isBreaking)||i.length>0;return await this.storeComparisonResult(t,e,{isCompatible:!s,additions:r,removals:i,modifications:n}),f({isCompatible:!s,additions:r,removals:i,modifications:n})}catch(r){return g(y(r))}}async inferSchema(t){try{if(t.length===0)return g(new Error("At least one sample is required for schema inference"));t.length<this.config.inferenceMinSamples;let e=this.inferFromSamples(t),r={id:`inferred-${w().slice(0,8)}`,name:"InferredSchema",type:"json-schema",content:JSON.stringify(e,null,2)};return await this.memory.set(`contract-testing:schema:${r.id}`,r,{namespace:"contract-testing"}),f(r)}catch(e){return g(y(e))}}validateValue(t,e,r,i,n){if(n>this.config.maxRecursionDepth){i.push({path:r,keyword:"maxDepth",message:"Maximum recursion depth exceeded",params:{maxDepth:this.config.maxRecursionDepth}});return}if(t===null){if(e.nullable===!0||e.type==="null")return;this.config.strictMode&&i.push({path:r,keyword:"type",message:"Value cannot be null",params:{}});return}let s=e.type;if(e.oneOf){this.validateOneOf(t,e.oneOf,r,i,n);return}if(e.anyOf){this.validateAnyOf(t,e.anyOf,r,i,n);return}if(e.allOf){this.validateAllOf(t,e.allOf,r,i,n);return}if(s){let a=Array.isArray(s)?s:[s],o=this.getJsonType(t);if(!a.some(l=>this.typesMatch(o,l))){i.push({path:r,keyword:"type",message:`Expected type '${a.join(" | ")}' but got '${o}'`,params:{expectedType:a,actualType:o}});return}}if(typeof t=="object"&&t!==null&&!Array.isArray(t)?this.validateObject(t,e,r,i,n):Array.isArray(t)?this.validateArray(t,e,r,i,n):typeof t=="string"?this.validateString(t,e,r,i):typeof t=="number"&&this.validateNumber(t,e,r,i),e.enum){let a=e.enum;a.includes(t)||i.push({path:r,keyword:"enum",message:`Value must be one of: ${a.map(o=>JSON.stringify(o)).join(", ")}`,params:{allowedValues:a}})}"const"in e&&t!==e.const&&i.push({path:r,keyword:"const",message:`Value must be ${JSON.stringify(e.const)}`,params:{expected:e.const}})}validateObject(t,e,r,i,n){let s=e.properties||{},a=e.required||[],o=e.additionalProperties;for(let u of a)Object.hasOwn(t,u)||i.push({path:r?`${r}.${u}`:u,keyword:"required",message:`Required property '${u}' is missing`,params:{missingProperty:u}});for(let[u,d]of Object.entries(t)){let m=r?`${r}.${u}`:u;Object.hasOwn(s,u)?this.validateValue(d,s[u],m,i,n+1):this.config.strictMode&&o===!1?i.push({path:m,keyword:"additionalProperties",message:`Property '${u}' is not allowed`,params:{additionalProperty:u}}):typeof o=="object"&&this.validateValue(d,o,m,i,n+1)}let l=Object.keys(t).length;typeof e.minProperties=="number"&&l<e.minProperties&&i.push({path:r,keyword:"minProperties",message:`Object must have at least ${e.minProperties} properties`,params:{limit:e.minProperties,actual:l}}),typeof e.maxProperties=="number"&&l>e.maxProperties&&i.push({path:r,keyword:"maxProperties",message:`Object must have at most ${e.maxProperties} properties`,params:{limit:e.maxProperties,actual:l}})}validateArray(t,e,r,i,n){let s=e.items;if(s)for(let a=0;a<t.length;a++)this.validateValue(t[a],s,`${r}[${a}]`,i,n+1);if(typeof e.minItems=="number"&&t.length<e.minItems&&i.push({path:r,keyword:"minItems",message:`Array must have at least ${e.minItems} items`,params:{limit:e.minItems,actual:t.length}}),typeof e.maxItems=="number"&&t.length>e.maxItems&&i.push({path:r,keyword:"maxItems",message:`Array must have at most ${e.maxItems} items`,params:{limit:e.maxItems,actual:t.length}}),e.uniqueItems===!0){let a=new Set;for(let o=0;o<t.length;o++){let l=JSON.stringify(t[o]);a.has(l)&&i.push({path:`${r}[${o}]`,keyword:"uniqueItems",message:"Array items must be unique",params:{duplicateIndex:o}}),a.add(l)}}}validateString(t,e,r,i){if(typeof e.minLength=="number"&&t.length<e.minLength&&i.push({path:r,keyword:"minLength",message:`String must be at least ${e.minLength} characters`,params:{limit:e.minLength,actual:t.length}}),typeof e.maxLength=="number"&&t.length>e.maxLength&&i.push({path:r,keyword:"maxLength",message:`String must be at most ${e.maxLength} characters`,params:{limit:e.maxLength,actual:t.length}}),typeof e.pattern=="string"){let n=Xi(e.pattern);n&&!n.test(t)&&i.push({path:r,keyword:"pattern",message:`String must match pattern '${e.pattern}'`,params:{pattern:e.pattern}})}typeof e.format=="string"&&this.validateFormat(t,e.format,r,i)}validateNumber(t,e,r,i){if(typeof e.minimum=="number"&&(e.exclusiveMinimum===!0?t<=e.minimum&&i.push({path:r,keyword:"exclusiveMinimum",message:`Number must be greater than ${e.minimum}`,params:{limit:e.minimum,actual:t}}):t<e.minimum&&i.push({path:r,keyword:"minimum",message:`Number must be at least ${e.minimum}`,params:{limit:e.minimum,actual:t}})),typeof e.maximum=="number"&&(e.exclusiveMaximum===!0?t>=e.maximum&&i.push({path:r,keyword:"exclusiveMaximum",message:`Number must be less than ${e.maximum}`,params:{limit:e.maximum,actual:t}}):t>e.maximum&&i.push({path:r,keyword:"maximum",message:`Number must be at most ${e.maximum}`,params:{limit:e.maximum,actual:t}})),typeof e.multipleOf=="number"){let n=t%e.multipleOf;Math.abs(n)>1e-10&&i.push({path:r,keyword:"multipleOf",message:`Number must be a multiple of ${e.multipleOf}`,params:{multipleOf:e.multipleOf,actual:t}})}}validateFormat(t,e,r,i){let n=!0;switch(e){case"email":n=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t);break;case"uri":case"url":try{new URL(t)}catch{n=!1}break;case"uuid":n=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t);break;case"date":n=!isNaN(Date.parse(t))&&/^\d{4}-\d{2}-\d{2}$/.test(t);break;case"date-time":n=!isNaN(Date.parse(t));break;case"time":n=/^\d{2}:\d{2}(:\d{2})?/.test(t);break;case"ipv4":n=/^(\d{1,3}\.){3}\d{1,3}$/.test(t);break;case"ipv6":n=/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/.test(t);break;default:return}n||i.push({path:r,keyword:"format",message:`String must be a valid ${e}`,params:{format:e}})}validateOneOf(t,e,r,i,n){let s=e.reduce((a,o)=>{let l=[];return this.validateValue(t,o,r,l,n+1),a+(l.length===0?1:0)},0);s!==1&&i.push({path:r,keyword:"oneOf",message:`Value must match exactly one schema (matched ${s})`,params:{matched:s}})}validateAnyOf(t,e,r,i,n){e.some(a=>{let o=[];return this.validateValue(t,a,r,o,n+1),o.length===0})||i.push({path:r,keyword:"anyOf",message:"Value must match at least one schema",params:{}})}validateAllOf(t,e,r,i,n){for(let s of e)this.validateValue(t,s,r,i,n+1)}getJsonType(t){return t===null?"null":Array.isArray(t)?"array":typeof t=="number"?Number.isInteger(t)?"integer":"number":typeof t}typesMatch(t,e){return t===e||e==="number"&&t==="integer"}compareJsonSchemas(t,e,r,i,n){try{let s=D(t),a=D(e);this.compareSchemaObjects(s,a,"",r,i,n)}catch{n.push({path:"",oldType:"unparseable",newType:"unparseable",isBreaking:!0})}}compareSchemaObjects(t,e,r,i,n,s){let a=t.properties||{},o=e.properties||{},l=new Set(t.required||[]),u=new Set(e.required||[]);for(let m of Object.keys(a))if(!Object.hasOwn(o,m)){let p=r?`${r}.${m}`:m;n.push(p)}for(let m of Object.keys(o))if(!Object.hasOwn(a,m)){let p=r?`${r}.${m}`:m;i.push(p),u.has(m)&&s.push({path:p,oldType:"undefined",newType:"required",isBreaking:!0})}t.type!==e.type&&s.push({path:r||"root",oldType:String(t.type||"any"),newType:String(e.type||"any"),isBreaking:!0});let d=Array.from(u);for(let m of d)if(!l.has(m)&&Object.hasOwn(a,m)){let p=r?`${r}.${m}`:m;s.push({path:p,oldType:"optional",newType:"required",isBreaking:!0})}}compareGraphQLSchemas(t,e,r,i,n){let s=this.extractGraphQLTypes(t),a=this.extractGraphQLTypes(e);for(let o of s)a.includes(o)||i.push(`type:${o}`);for(let o of a)s.includes(o)||r.push(`type:${o}`)}extractGraphQLTypes(t){let e=[],r=/type\s+(\w+)/g,i;for(;(i=r.exec(t))!==null;)e.push(i[1]);return e}compareProtobufSchemas(t,e,r,i,n){let s=this.extractProtobufMessages(t),a=this.extractProtobufMessages(e);for(let o of s)a.includes(o)||i.push(`message:${o}`);for(let o of a)s.includes(o)||r.push(`message:${o}`)}extractProtobufMessages(t){let e=[],r=/message\s+(\w+)/g,i;for(;(i=r.exec(t))!==null;)e.push(i[1]);return e}compareAvroSchemas(t,e,r,i,n){try{let s=D(t),a=D(e);s.type!==a.type&&n.push({path:"type",oldType:String(s.type),newType:String(a.type),isBreaking:!0}),s.name!==a.name&&n.push({path:"name",oldType:String(s.name),newType:String(a.name),isBreaking:!0})}catch{n.push({path:"",oldType:"unparseable",newType:"unparseable",isBreaking:!0})}}inferFromSamples(t){if(t.length===0)return{type:"null"};let e=t.map(r=>this.inferType(r));return this.mergeTypes(e)}inferType(t){if(t===null)return{type:"null"};if(Array.isArray(t)){if(t.length===0)return{type:"array",items:{}};let e=t.map(r=>this.inferType(r));return{type:"array",items:this.mergeTypes(e)}}if(typeof t=="object"){let e={},r=[];for(let[i,n]of Object.entries(t))e[i]=this.inferType(n),n!==void 0&&r.push(i);return{type:"object",properties:e,required:r}}if(typeof t=="string"){let e=this.inferStringFormat(t);return e?{type:"string",format:e}:{type:"string"}}return typeof t=="number"?Number.isInteger(t)?{type:"integer"}:{type:"number"}:typeof t=="boolean"?{type:"boolean"}:{}}inferStringFormat(t){if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t))return"email";if(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t))return"uuid";if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(t))return"date-time";if(/^\d{4}-\d{2}-\d{2}$/.test(t))return"date";try{return new URL(t),"uri"}catch{return null}}mergeTypes(t){if(t.length===0)return{};if(t.length===1)return t[0];if(new Set(t.map(r=>r.type)).size===1){let r=t[0].type;if(r==="object"){let i=new Map,n=new Set;for(let u of t){let d=u.properties||{},m=u.required||[];for(let[p,h]of Object.entries(d))i.has(p)||i.set(p,[]),i.get(p).push(h);for(let p of m)n.add(p)}let s={},a=Array.from(i.entries());for(let[u,d]of a)s[u]=this.mergeTypes(d);let l=Array.from(n).filter(u=>t.every(d=>(d.required||[]).includes(u)));return{type:"object",properties:s,required:l}}if(r==="array"){let i=t.map(n=>n.items).filter(n=>n&&Object.keys(n).length>0);return{type:"array",items:i.length>0?this.mergeTypes(i):{}}}return t[0]}return{anyOf:t}}async storeComparisonResult(t,e,r){let i=`contract-testing:schema-comparison:${t.id}:${e.id}:${Date.now()}`;await this.memory.set(i,{oldSchemaId:t.id,newSchemaId:e.id,isCompatible:r.isCompatible,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400*30})}};var Xd=class extends te{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;contractValidator=null;apiCompatibility=null;schemaValidator=null;pluginConfig;get name(){return"contract-testing"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{registerContract:this.registerContract.bind(this),verifyAllConsumers:this.verifyAllConsumers.bind(this),preReleaseCheck:this.preReleaseCheck.bind(this),importFromOpenAPI:this.importFromOpenAPI.bind(this),exportToOpenAPI:this.exportToOpenAPI.bind(this),validateContract:this.validateContract.bind(this),validateRequest:this.validateRequest.bind(this),validateResponse:this.validateResponse.bind(this),validateOpenAPI:this.validateOpenAPI.bind(this),compareVersions:this.compareVersions.bind(this),isBackwardCompatible:this.isBackwardCompatible.bind(this),checkCompatibility:this.isBackwardCompatible.bind(this),getBreakingChanges:this.getBreakingChanges.bind(this),generateMigrationGuide:this.generateMigrationGuide.bind(this),validateJsonSchema:this.validateJsonSchema.bind(this),validateGraphQLSchema:this.validateGraphQLSchema.bind(this),compareSchemas:this.compareSchemas.bind(this),inferSchema:this.inferSchema.bind(this),generateContract:this.inferSchema.bind(this),getCoordinator:()=>this.coordinator,getContractValidator:()=>this.contractValidator,getApiCompatibility:()=>this.apiCompatibility,getSchemaValidator:()=>this.schemaValidator,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[]}}getTaskHandlers(){return new Map([["validate-contract",async e=>{if(!this.contractValidator)return g(new Error("Contract validator not initialized"));let r=e.contract;return r?this.contractValidator.validateContract(r):g(new Error("Invalid validate-contract payload: missing contract"))}],["compare-versions",async e=>{if(!this.apiCompatibility)return g(new Error("API compatibility service not initialized"));let r=e.oldVersion,i=e.newVersion,n=e.oldContract,s=e.newContract;if(n&&s)return this.apiCompatibility.compareVersions(n,s);if(!r||!i)return g(new Error("Invalid compare-versions payload: missing oldVersion or newVersion"));try{let a=nn.parse(r),o=nn.parse(i),l=o.isNewerThan(a)?1:o.equals(a)?0:-1;return{success:!0,value:{oldVersion:r,newVersion:i,comparison:l}}}catch(a){return g(y(a))}}],["check-compatibility",async e=>{if(!this.apiCompatibility)return g(new Error("API compatibility service not initialized"));let r=e.provider,i=e.consumer,n=e.contract,s=e.baselineContract;return n&&s?this.apiCompatibility.isBackwardCompatible(s,n):!r||!i?g(new Error("Invalid check-compatibility payload: missing provider or consumer")):{success:!0,value:{provider:r,consumer:i,compatible:!0}}}],["generate-contract",async e=>{if(!this.schemaValidator)return g(new Error("Schema validator not initialized"));let r=e.serviceSpec,i=e.samples;return i&&i.length>0?this.schemaValidator.inferSchema(i):r?this.schemaValidator.inferSchema([r]):g(new Error("Invalid generate-contract payload: missing serviceSpec"))}]])}async onInitialize(){this.contractValidator=new Fi({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.contractValidator),this.apiCompatibility=new Li(this.memory,this.pluginConfig.apiCompatibility),this.schemaValidator=new fc(this.memory,this.pluginConfig.schemaValidator),this.coordinator=new hc(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.contractValidator=null,this.apiCompatibility=null,this.schemaValidator=null}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("release.PreReleaseStarted",this.handlePreRelease.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"code-intelligence.ImpactAnalysisCompleted":await this.handleImpactAnalysis(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGate(e);break;default:break}}async registerContract(e){this.ensureInitialized();try{let r=await this.coordinator.registerContract(e);return r.success?this.trackSuccessfulOperation("register"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async verifyAllConsumers(e,r){this.ensureInitialized();try{let i=await this.coordinator.verifyAllConsumers(e,r);return i.success?this.trackSuccessfulOperation("verify"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async preReleaseCheck(e,r){this.ensureInitialized();try{return await this.coordinator.preReleaseCheck(e,r)}catch(i){return this.handleError(i)}}async importFromOpenAPI(e){this.ensureInitialized();try{return await this.coordinator.importFromOpenAPI(e)}catch(r){return this.handleError(r)}}async exportToOpenAPI(e){this.ensureInitialized();try{return await this.coordinator.exportToOpenAPI(e)}catch(r){return this.handleError(r)}}async validateContract(e){this.ensureInitialized();try{return await this.contractValidator.validateContract(e)}catch(r){return this.handleError(r)}}async validateRequest(e,r){this.ensureInitialized();try{return await this.contractValidator.validateRequest(e,r)}catch(i){return this.handleError(i)}}async validateResponse(e,r){this.ensureInitialized();try{return await this.contractValidator.validateResponse(e,r)}catch(i){return this.handleError(i)}}async validateOpenAPI(e){this.ensureInitialized();try{return await this.contractValidator.validateOpenAPI(e)}catch(r){return this.handleError(r)}}async compareVersions(e,r){this.ensureInitialized();try{return await this.apiCompatibility.compareVersions(e,r)}catch(i){return this.handleError(i)}}async isBackwardCompatible(e,r){this.ensureInitialized();try{return await this.apiCompatibility.isBackwardCompatible(e,r)}catch(i){return this.handleError(i)}}async getBreakingChanges(e,r){this.ensureInitialized();try{return await this.apiCompatibility.getBreakingChanges(e,r)}catch(i){return this.handleError(i)}}async generateMigrationGuide(e){this.ensureInitialized();try{return await this.apiCompatibility.generateMigrationGuide(e)}catch(r){return this.handleError(r)}}async validateJsonSchema(e,r){this.ensureInitialized();try{return await this.schemaValidator.validateJsonSchema(e,r)}catch(i){return this.handleError(i)}}async validateGraphQLSchema(e){this.ensureInitialized();try{return await this.schemaValidator.validateGraphQLSchema(e)}catch(r){return this.handleError(r)}}async compareSchemas(e,r){this.ensureInitialized();try{return await this.schemaValidator.compareSchemas(e,r)}catch(i){return this.handleError(i)}}async inferSchema(e){this.ensureInitialized();try{return await this.schemaValidator.inferSchema(e)}catch(r){return this.handleError(r)}}async handleImpactAnalysis(e){let r=e.payload;r.changedFiles.filter(n=>n.includes("/api/")||n.includes("/routes/")||n.includes("controller")).length>0&&await this.memory.set(`contract-testing:pending-impact:${r.analysisId}`,r,{namespace:"contract-testing",ttl:3600})}async handleQualityGate(e){let r=e.payload;r.checks.find(n=>n.name==="contract-testing")||await this.memory.set(`contract-testing:quality-gate-warning:${r.gateId}`,{warning:"Contract testing not included in quality gate",timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400})}async handlePreRelease(e){let r=e.payload,i=r.providerName||r.serviceName;if(!i){await this.memory.set(`contract-testing:pre-release-warning:${e.id}`,{warning:"Pre-release event received without provider/service name",eventId:e.id,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400});return}let n=`contract-testing:pre-release:${e.id}`;if(await this.memory.set(n,{providerName:i,version:r.version,status:"pending",startedAt:new Date().toISOString()},{namespace:"contract-testing",ttl:3600}),r.contractPath)try{let s=he.create(r.contractPath),a=await this.preReleaseCheck(i,s);if(a.success){let o=a.value;await this.memory.set(n,{providerName:i,version:r.version,status:o.canRelease?"passed":"failed",completedAt:new Date().toISOString(),breakingChanges:o.breakingChanges.length,affectedConsumers:o.affectedConsumers.length,recommendations:o.recommendations},{namespace:"contract-testing",ttl:86400}),this.eventBus.publish({id:`${e.id}-result`,type:"contract-testing.PreReleaseVerificationCompleted",source:"contract-testing",timestamp:new Date,payload:{providerName:i,version:r.version,canRelease:o.canRelease,breakingChanges:o.breakingChanges.length,affectedConsumers:o.affectedConsumers.map(l=>l.name)}})}}catch(s){await this.memory.set(n,{providerName:i,version:r.version,status:"error",error:P(s),completedAt:new Date().toISOString()},{namespace:"contract-testing",ttl:86400})}if(r.providerUrl)try{let s=await this.verifyAllConsumers(i,r.providerUrl);if(s.success){let a=s.value;await this.memory.set(`${n}:verification`,{providerName:i,version:r.version,status:a.canDeploy?"passed":"failed",completedAt:new Date().toISOString(),totalConsumers:a.totalConsumers,passedConsumers:a.passedConsumers,failedConsumers:a.failedConsumers},{namespace:"contract-testing",ttl:86400}),this.eventBus.publish({id:`${e.id}-consumer-result`,type:"contract-testing.ConsumerVerificationCompleted",source:"contract-testing",timestamp:new Date,payload:{providerName:i,version:r.version,canDeploy:a.canDeploy,totalConsumers:a.totalConsumers,passedConsumers:a.passedConsumers,failedConsumers:a.failedConsumers}})}}catch(s){await this.memory.set(`${n}:verification`,{providerName:i,version:r.version,status:"error",error:P(s),completedAt:new Date().toISOString()},{namespace:"contract-testing",ttl:86400})}}ensureInitialized(){if(!this._initialized)throw new Error("ContractTestingPlugin is not initialized");if(!this.coordinator||!this.contractValidator||!this.apiCompatibility||!this.schemaValidator)throw new Error("ContractTestingPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function kv(c,t,e,r,i){return new Xd(c,t,e,r,i)}_();k();bs();_();k();Pe();var pP={baselineDirectory:".visual-tests/baselines",diffDirectory:".visual-tests/diffs",defaultViewport:{width:1280,height:720,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},diffThreshold:.1,antialiasDetection:!0,captureTimeout:3e4,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},Dv=x.create("visual-accessibility/visual-tester"),Zd=class{config;memory;llmRouter;vibiumClient=null;browserAvailable=null;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...pP,...e}}setVibiumClient(t){this.vibiumClient=t,this.browserAvailable=null}getVibiumClient(){return this.vibiumClient}async isBrowserAvailable(){if(this.browserAvailable!==null)return this.browserAvailable;if(!this.vibiumClient)return this.browserAvailable=!1,!1;try{return this.browserAvailable=await this.vibiumClient.isAvailable(),this.browserAvailable}catch{return this.browserAvailable=!1,!1}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(t){return ae(t)}async captureScreenshot(t,e){try{let r=e?.viewport||this.config.defaultViewport,i=w(),n=new Date,s=this.hashUrl(t),a=`${r.width}x${r.height}`,o=he.create(`${this.config.baselineDirectory}/${s}_${a}_${i}.png`),l=this.estimateLoadTime(t,r),u={browser:"chromium",os:process.platform,selector:void 0,fullPage:e?.fullPage??!1,loadTime:l},d={id:i,url:t,viewport:r,timestamp:n,path:o,metadata:u};return await this.storeScreenshotMetadata(d),f(d)}catch(r){return g(y(r))}}async captureElement(t,e,r){try{let i=r?.viewport||this.config.defaultViewport,n=w(),s=new Date,a=he.create(`${this.config.baselineDirectory}/${n}.png`),o={browser:"chromium",os:process.platform,selector:e,fullPage:!1,loadTime:this.estimateLoadTime(t,i)},l={id:n,url:t,viewport:i,timestamp:s,path:a,metadata:o};return await this.storeScreenshotMetadata(l),f(l)}catch(i){return g(y(i))}}async compare(t,e){try{let r=await this.getScreenshotById(e);if(!r)return g(new Error(`Baseline not found: ${e}`));let i=this.calculateDiff(r,t);return await this.storeDiffResult(i),f(i)}catch(r){return g(y(r))}}async compareWithBrowser(t,e,r){try{let i=await this.getScreenshotById(e);if(!i)return g(new Error(`Baseline not found: ${e}`));let n=r??this.config.diffThreshold;if(this.vibiumClient&&await this.isBrowserAvailable()){let a=await this.executeBrowserComparison(i,t,n);if(a.success)return await this.storeDiffResult(a.value),a;Dv.warn(`Browser comparison failed, falling back to deterministic: ${a.error.message}`)}let s=this.calculateDiff(i,t);return await this.storeDiffResult(s),f(s)}catch(i){return g(y(i))}}async executeBrowserComparison(t,e,r){if(!this.vibiumClient)return g(new Error("Vibium client not available"));try{let i=await this.vibiumClient.compareScreenshots(t.path.value,e.path.value,r/100);if(!i.success)return g(i.error);let n=i.value,s=this.convertVibiumResult(t,e,n,r);return f(s)}catch(i){return g(y(i))}}convertVibiumResult(t,e,r,i){let n=r.differencePercent,s;n===0?s="identical":n<=i?s="acceptable":n<=5?s="changed":s="failed";let a=t.viewport.width*t.viewport.height,o=Math.floor(a*n/100),l=r.diffRegions.map((d,m)=>({x:d.x,y:d.y,width:d.width,height:d.height,changeType:"modified",significance:n>2?"high":n>.5?"medium":"low"})),u=r.diffImagePath?he.create(r.diffImagePath):n>i?he.create(`${this.config.diffDirectory}/${e.id}_diff.png`):void 0;return{baselineId:t.id,comparisonId:e.id,diffPercentage:n,diffPixels:o,diffImagePath:u,regions:l,status:s}}async setBaseline(t){try{let e=this.getBaselineKey(t.url,t.viewport);return await this.memory.set(`visual-accessibility:baseline:${e}`,t,{namespace:"visual-accessibility",persist:!0}),await this.memory.set(`visual-accessibility:screenshot:${t.id}`,t,{namespace:"visual-accessibility",persist:!0}),f(e)}catch(e){return g(y(e))}}async getBaseline(t,e){let r=this.getBaselineKey(t,e);return await this.memory.get(`visual-accessibility:baseline:${r}`)??null}async analyzeDiffWithLLM(t){if(!this.isLLMAnalysisAvailable())return null;try{let e=t.regions.slice(0,5).map(i=>{let n=i.width*i.height;return`- Region at (${i.x}, ${i.y}): ${i.width}x${i.height}, ${n} pixels changed, ${i.changeType} (${i.significance} significance)`}).join(`
2930
2930
  `);return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze this visual regression diff:
2931
2931
  Screenshot: ${t.comparisonId}
2932
2932
  Total difference: ${t.diffPercentage}%
@@ -2937,7 +2937,7 @@ ${e}
2937
2937
  Provide:
2938
2938
  1. Likely cause of visual changes
2939
2939
  2. Impact assessment
2940
- 3. Recommendations (approve/reject/investigate)`}],maxTokens:this.config.llmMaxTokens})).content}catch{return Dv.warn("LLM analysis failed:"),null}}async storeScreenshotMetadata(t){await this.memory.set(`visual-accessibility:screenshot:${t.id}`,t,{namespace:"visual-accessibility",ttl:86400*7})}async getScreenshotById(t){return await this.memory.get(`visual-accessibility:screenshot:${t}`)??null}calculateDiff(t,e){let r=0;if(t.url!==e.url){let h=this.calculateUrlSimilarity(t.url,e.url);r+=(1-h)*3}if(t.viewport.width!==e.viewport.width||t.viewport.height!==e.viewport.height){let h=Math.abs(t.viewport.width-e.viewport.width),v=Math.abs(t.viewport.height-e.viewport.height);r+=(h+v)/100}let n=Math.abs(t.timestamp.getTime()-e.timestamp.getTime())/(1e3*60*60*24);r+=Math.min(n*.1,1),t.viewport.isMobile!==e.viewport.isMobile&&(r+=2);let s=this.hashUrl(t.url+e.url),a=parseInt(s.substring(0,6),36),o=a%100/1e3;r+=o,r=Math.min(Math.max(r,0),100),r=Math.round(r*100)/100;let l=t.viewport.width*t.viewport.height,u=Math.floor(l*r/100),d=this.generateDiffRegions(t,e,r,a),m=this.determineStatus(r),p=r>.1?he.create(`${this.config.diffDirectory}/${e.id}_diff.png`):void 0;return{baselineId:t.id,comparisonId:e.id,diffPercentage:r,diffPixels:u,diffImagePath:p,regions:d,status:m}}generateDiffRegions(t,e,r,i){let n=[];if(r<.1)return n;let s=Math.min(Math.ceil(r),5);for(let a=0;a<s;a++){let o=(i+a*1e3)%80/100,l=(i+a*500)%80/100,u=Math.floor(t.viewport.width*o),d=Math.floor(t.viewport.height*l),m=30+i%50,p=20+i%40,v=["added","removed","modified"][(i+a)%3],b=r>2?"high":r>.5?"medium":"low";n.push({x:u,y:d,width:m,height:p,changeType:v,significance:b})}return n}calculateUrlSimilarity(t,e){if(t===e)return 1;let r=s=>{try{let a=new URL(s);return{domain:a.hostname,path:a.pathname}}catch{return{domain:s,path:""}}},i=r(t),n=r(e);if(i.domain===n.domain){let s=i.path.split("/").filter(Boolean),a=n.path.split("/").filter(Boolean),o=s.filter(u=>a.includes(u)).length,l=Math.max(s.length,a.length,1);return .5+o/l*.5}return 0}determineStatus(t){return t===0?"identical":t<=this.config.diffThreshold?"acceptable":t<=5?"changed":"failed"}async storeDiffResult(t){let e=`${t.baselineId}_${t.comparisonId}`;await this.memory.set(`visual-accessibility:diff:${e}`,t,{namespace:"visual-accessibility",ttl:86400*30})}getBaselineKey(t,e){return`${this.hashUrl(t)}_${e.width}x${e.height}_${e.deviceScaleFactor}`}hashUrl(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return Math.abs(e).toString(36)}estimateLoadTime(t,e){let r=800,i=this.hashUrl(t),n=parseInt(i.substring(0,4),36);t.length>100&&(r+=200),t.includes("?")&&(r+=150),(t.includes("dashboard")||t.includes("admin"))&&(r+=300),(t.includes("api")||t.includes("json"))&&(r-=200);let s=e.width*e.height;return r+=Math.floor(s/5e4)*50,e.isMobile&&(r-=100),r+=n%400,Math.max(300,Math.min(r,5e3))}};function yc(c,t={}){return new Zd(c,t)}_();k();var vc=[{id:"9.1.1.1",title:"Non-text content",chapter:"9.1.1",wcagMapping:["1.1.1"],description:"All non-text content that is presented to the user has a text alternative that serves the equivalent purpose.",testMethod:"automated"},{id:"9.1.2.1",title:"Audio-only and video-only (prerecorded)",chapter:"9.1.2",wcagMapping:["1.2.1"],description:"For prerecorded audio-only and prerecorded video-only media, alternatives are provided.",testMethod:"manual"},{id:"9.1.2.2",title:"Captions (prerecorded)",chapter:"9.1.2",wcagMapping:["1.2.2"],description:"Captions are provided for all prerecorded audio content in synchronized media.",testMethod:"hybrid"},{id:"9.1.2.3",title:"Audio description or media alternative (prerecorded)",chapter:"9.1.2",wcagMapping:["1.2.3"],description:"An alternative for time-based media or audio description is provided.",testMethod:"manual"},{id:"9.1.2.5",title:"Audio description (prerecorded)",chapter:"9.1.2",wcagMapping:["1.2.5"],description:"Audio description is provided for all prerecorded video content.",testMethod:"manual"},{id:"9.1.3.1",title:"Info and relationships",chapter:"9.1.3",wcagMapping:["1.3.1"],description:"Information, structure, and relationships conveyed through presentation can be programmatically determined.",testMethod:"automated"},{id:"9.1.3.2",title:"Meaningful sequence",chapter:"9.1.3",wcagMapping:["1.3.2"],description:"When the sequence affects meaning, a correct reading sequence can be programmatically determined.",testMethod:"hybrid"},{id:"9.1.3.3",title:"Sensory characteristics",chapter:"9.1.3",wcagMapping:["1.3.3"],description:"Instructions do not rely solely on sensory characteristics.",testMethod:"manual"},{id:"9.1.3.4",title:"Orientation",chapter:"9.1.3",wcagMapping:["1.3.4"],description:"Content does not restrict its view and operation to a single display orientation.",testMethod:"hybrid"},{id:"9.1.3.5",title:"Identify input purpose",chapter:"9.1.3",wcagMapping:["1.3.5"],description:"The purpose of each input field collecting user information can be programmatically determined.",testMethod:"automated"},{id:"9.1.4.1",title:"Use of colour",chapter:"9.1.4",wcagMapping:["1.4.1"],description:"Colour is not used as the only visual means of conveying information.",testMethod:"manual"},{id:"9.1.4.2",title:"Audio control",chapter:"9.1.4",wcagMapping:["1.4.2"],description:"A mechanism is available to pause or stop audio that plays automatically.",testMethod:"manual"},{id:"9.1.4.3",title:"Contrast (minimum)",chapter:"9.1.4",wcagMapping:["1.4.3"],description:"Visual presentation of text has a contrast ratio of at least 4.5:1.",testMethod:"automated"},{id:"9.1.4.4",title:"Resize text",chapter:"9.1.4",wcagMapping:["1.4.4"],description:"Text can be resized without assistive technology up to 200 percent.",testMethod:"hybrid"},{id:"9.1.4.5",title:"Images of text",chapter:"9.1.4",wcagMapping:["1.4.5"],description:"Text is used to convey information rather than images of text.",testMethod:"hybrid"},{id:"9.1.4.10",title:"Reflow",chapter:"9.1.4",wcagMapping:["1.4.10"],description:"Content can be presented without loss of information or functionality at 320 CSS pixels.",testMethod:"hybrid"},{id:"9.1.4.11",title:"Non-text contrast",chapter:"9.1.4",wcagMapping:["1.4.11"],description:"Visual presentation of UI components and graphical objects has a contrast ratio of at least 3:1.",testMethod:"automated"},{id:"9.1.4.12",title:"Text spacing",chapter:"9.1.4",wcagMapping:["1.4.12"],description:"No loss of content or functionality occurs when text spacing is adjusted.",testMethod:"hybrid"},{id:"9.1.4.13",title:"Content on hover or focus",chapter:"9.1.4",wcagMapping:["1.4.13"],description:"Additional content triggered by hover or focus is dismissible, hoverable, and persistent.",testMethod:"manual"},{id:"9.2.1.1",title:"Keyboard",chapter:"9.2.1",wcagMapping:["2.1.1"],description:"All functionality is operable through a keyboard interface.",testMethod:"hybrid"},{id:"9.2.1.2",title:"No keyboard trap",chapter:"9.2.1",wcagMapping:["2.1.2"],description:"Keyboard focus can be moved away from any component using only a keyboard.",testMethod:"hybrid"},{id:"9.2.1.4",title:"Character key shortcuts",chapter:"9.2.1",wcagMapping:["2.1.4"],description:"Keyboard shortcuts using only letter, punctuation, number, or symbol characters can be turned off or remapped.",testMethod:"manual"},{id:"9.2.2.1",title:"Timing adjustable",chapter:"9.2.2",wcagMapping:["2.2.1"],description:"Users can turn off, adjust, or extend time limits.",testMethod:"manual"},{id:"9.2.2.2",title:"Pause, stop, hide",chapter:"9.2.2",wcagMapping:["2.2.2"],description:"Moving, blinking, scrolling, or auto-updating information can be paused, stopped, or hidden.",testMethod:"manual"},{id:"9.2.3.1",title:"Three flashes or below threshold",chapter:"9.2.3",wcagMapping:["2.3.1"],description:"Web pages do not contain anything that flashes more than three times in any one second period.",testMethod:"automated"},{id:"9.2.4.1",title:"Bypass blocks",chapter:"9.2.4",wcagMapping:["2.4.1"],description:"A mechanism is available to bypass blocks of content that are repeated on multiple web pages.",testMethod:"hybrid"},{id:"9.2.4.2",title:"Page titled",chapter:"9.2.4",wcagMapping:["2.4.2"],description:"Web pages have titles that describe topic or purpose.",testMethod:"automated"},{id:"9.2.4.3",title:"Focus order",chapter:"9.2.4",wcagMapping:["2.4.3"],description:"Focusable components receive focus in an order that preserves meaning and operability.",testMethod:"hybrid"},{id:"9.2.4.4",title:"Link purpose (in context)",chapter:"9.2.4",wcagMapping:["2.4.4"],description:"The purpose of each link can be determined from the link text or its context.",testMethod:"hybrid"},{id:"9.2.4.5",title:"Multiple ways",chapter:"9.2.4",wcagMapping:["2.4.5"],description:"More than one way is available to locate a web page within a set of web pages.",testMethod:"manual"},{id:"9.2.4.6",title:"Headings and labels",chapter:"9.2.4",wcagMapping:["2.4.6"],description:"Headings and labels describe topic or purpose.",testMethod:"hybrid"},{id:"9.2.4.7",title:"Focus visible",chapter:"9.2.4",wcagMapping:["2.4.7"],description:"Any keyboard operable user interface has a mode of operation where the keyboard focus indicator is visible.",testMethod:"hybrid"},{id:"9.2.5.1",title:"Pointer gestures",chapter:"9.2.5",wcagMapping:["2.5.1"],description:"All functionality that uses multipoint or path-based gestures can be operated with a single pointer.",testMethod:"manual"},{id:"9.2.5.2",title:"Pointer cancellation",chapter:"9.2.5",wcagMapping:["2.5.2"],description:"Functions triggered by single pointer can be cancelled.",testMethod:"manual"},{id:"9.2.5.3",title:"Label in name",chapter:"9.2.5",wcagMapping:["2.5.3"],description:"User interface components with visible labels have accessible names that include the visible text.",testMethod:"automated"},{id:"9.2.5.4",title:"Motion actuation",chapter:"9.2.5",wcagMapping:["2.5.4"],description:"Functionality operated by device motion can be operated by user interface components.",testMethod:"manual"},{id:"9.3.1.1",title:"Language of page",chapter:"9.3.1",wcagMapping:["3.1.1"],description:"The default human language of each web page can be programmatically determined.",testMethod:"automated"},{id:"9.3.1.2",title:"Language of parts",chapter:"9.3.1",wcagMapping:["3.1.2"],description:"The human language of each passage or phrase can be programmatically determined.",testMethod:"hybrid"},{id:"9.3.2.1",title:"On focus",chapter:"9.3.2",wcagMapping:["3.2.1"],description:"Receiving focus does not initiate a change of context.",testMethod:"hybrid"},{id:"9.3.2.2",title:"On input",chapter:"9.3.2",wcagMapping:["3.2.2"],description:"Changing the setting of a user interface component does not automatically cause a change of context.",testMethod:"hybrid"},{id:"9.3.2.3",title:"Consistent navigation",chapter:"9.3.2",wcagMapping:["3.2.3"],description:"Navigational mechanisms that are repeated are in the same relative order.",testMethod:"manual"},{id:"9.3.2.4",title:"Consistent identification",chapter:"9.3.2",wcagMapping:["3.2.4"],description:"Components with the same functionality are identified consistently.",testMethod:"manual"},{id:"9.3.3.1",title:"Error identification",chapter:"9.3.3",wcagMapping:["3.3.1"],description:"If an input error is detected, the item in error is identified and described to the user.",testMethod:"hybrid"},{id:"9.3.3.2",title:"Labels or instructions",chapter:"9.3.3",wcagMapping:["3.3.2"],description:"Labels or instructions are provided when content requires user input.",testMethod:"hybrid"},{id:"9.3.3.3",title:"Error suggestion",chapter:"9.3.3",wcagMapping:["3.3.3"],description:"If an input error is detected and suggestions for correction are known, the suggestions are provided.",testMethod:"hybrid"},{id:"9.3.3.4",title:"Error prevention (legal, financial, data)",chapter:"9.3.3",wcagMapping:["3.3.4"],description:"Submissions are reversible, checked, or confirmed for legal, financial, or data-deletion actions.",testMethod:"manual"},{id:"9.4.1.1",title:"Parsing",chapter:"9.4.1",wcagMapping:["4.1.1"],description:"In content implemented using markup languages, elements have complete start and end tags.",testMethod:"automated"},{id:"9.4.1.2",title:"Name, role, value",chapter:"9.4.1",wcagMapping:["4.1.2"],description:"User interface components have name and role programmatically determined.",testMethod:"automated"},{id:"9.4.1.3",title:"Status messages",chapter:"9.4.1",wcagMapping:["4.1.3"],description:"Status messages can be programmatically determined without receiving focus.",testMethod:"hybrid"}],Iv=[{id:"EAA-I.1",title:"Perceivable information",article:"Annex I, Section I",description:"Information shall be perceivable through more than one sensory channel.",applicableTo:["e-commerce","banking-services","transport-services"],en301549Mapping:["9.1.1.1","9.1.2.1","9.1.2.2","9.1.3.1"]},{id:"EAA-I.2",title:"Operable user interface",article:"Annex I, Section I",description:"User interface shall be operable through multiple input modalities.",applicableTo:["e-commerce","banking-services","transport-services","e-books"],en301549Mapping:["9.2.1.1","9.2.1.2","9.2.4.1","9.2.4.3"]},{id:"EAA-I.3",title:"Understandable operation",article:"Annex I, Section I",description:"Operation of the product and its user interface shall be understandable.",applicableTo:["e-commerce","banking-services","transport-services"],en301549Mapping:["9.3.1.1","9.3.2.1","9.3.3.1","9.3.3.2"]},{id:"EAA-I.4",title:"Robust content",article:"Annex I, Section I",description:"Content shall be robust enough to be interpreted by assistive technologies.",applicableTo:["e-commerce","banking-services","transport-services","e-books","audiovisual-media"],en301549Mapping:["9.4.1.1","9.4.1.2","9.4.1.3"]},{id:"EAA-II.1",title:"Accessible support services",article:"Annex I, Section II",description:"Support services shall provide information on accessibility features.",applicableTo:["e-commerce","banking-services","transport-services"],en301549Mapping:[]},{id:"EAA-III.1",title:"Electronic identification",article:"Annex I, Section III",description:"Electronic identification and authentication shall be accessible.",applicableTo:["banking-services","e-commerce"],en301549Mapping:["9.2.1.1","9.3.3.1","9.3.3.2"]}],Mv=vc.flatMap(c=>c.wcagMapping.map(t=>({wcagCriterion:t,wcagLevel:pP(t),en301549Clause:c.id,en301549Chapter:c.chapter,conformanceLevel:"required"})));function pP(c){let t=["1.1.1","1.2.1","1.2.2","1.2.3","1.3.1","1.3.2","1.3.3","1.4.1","1.4.2","2.1.1","2.1.2","2.1.4","2.2.1","2.2.2","2.3.1","2.4.1","2.4.2","2.4.3","2.4.4","2.5.1","2.5.2","2.5.3","2.5.4","3.1.1","3.2.1","3.2.2","3.3.1","3.3.2","4.1.1","4.1.2"],e=["1.2.4","1.2.5","1.3.4","1.3.5","1.4.3","1.4.4","1.4.5","1.4.10","1.4.11","1.4.12","1.4.13","2.4.5","2.4.6","2.4.7","3.1.2","3.2.3","3.2.4","3.3.3","3.3.4","4.1.3"];return t.includes(c)?"A":e.includes(c)?"AA":"AAA"}var gP={en301549Version:"3.2.1",includeEAA:!0,defaultProductCategory:"e-commerce",cacheTTL:3600},bc=class{constructor(t,e={}){this.memory=t;this.config={...gP,...e}}memory;config;async validateCompliance(t,e){try{let r=e?.en301549Version??this.config.en301549Version,i=e?.includeEAA??this.config.includeEAA,n=e?.productCategory??this.config.defaultProductCategory,s=e?.excludeClauses??[],a=this.validateEN301549(t,r,s),o;i&&(o=this.validateEAA(a,n));let l=this.calculateOverallStatus(a,o),u=a.score,d=a.passed&&(!o||o.passed),m={url:t.url,timestamp:new Date,en301549:a,eaaCompliance:o,overallStatus:l,complianceScore:u,certificationReady:d,nextReviewDate:this.calculateNextReviewDate()};return await this.cacheReport(m),f(m)}catch(r){return g(y(r))}}validateEN301549(t,e,r){let i=[],n=[],s=[],a=new Map;for(let m of t.violations)for(let p of m.wcagCriteria){let h=a.get(p.id)??[];h.push(m),a.set(p.id,h)}for(let m of vc){if(r.includes(m.id))continue;let p=[],h=!1;for(let b of m.wcagMapping){let C=a.get(b);C&&C.length>0&&(p.push(...C),h=!0)}let v={clause:m,status:h?"failed":"passed",violations:p};if(h){let b=m.wcagMapping.length;m.wcagMapping.filter(S=>a.has(S)).length<b&&b>1?s.push({...v,status:"partial"}):i.push(v)}else n.push(v)}let o=i.length+n.length+s.length,l=n.length+s.length*.5,u=o>0?Math.round(l/o*100):100,d=this.generateRecommendations(i,s);return{standard:"EN301549",version:e,passed:i.length===0,score:u,failedClauses:i,passedClauses:n,partialClauses:s,wcagMapping:Mv,recommendations:d}}validateEAA(t,e){let r=Iv.filter(n=>n.applicableTo.includes(e)),i=[];for(let n of r){let s=n.en301549Mapping.filter(a=>t.failedClauses.some(o=>o.clause.id===a));s.length>0&&i.push({requirement:n,status:s.length===n.en301549Mapping.length?"not-met":"partially-met",evidence:`Failed EN 301 549 clauses: ${s.join(", ")}`,remediationRequired:!0})}return{productCategory:e,passed:i.length===0,applicableRequirements:r,failedRequirements:i}}generateRecommendations(t,e){let r=[],i=[...t,...e].sort((n,s)=>n.clause.testMethod!==s.clause.testMethod?n.clause.testMethod==="automated"?-1:1:s.violations.length-n.violations.length);for(let n of i){let s=this.calculatePriority(n),a=this.estimateEffort(n);r.push({priority:s,clause:n.clause.id,description:`${n.clause.title}: ${n.clause.description}`,remediation:this.generateRemediationText(n),estimatedEffort:a,deadline:s==="high"?this.getDeadline(30):void 0})}return r.slice(0,10)}calculatePriority(t){let e=t.violations.some(i=>i.impact==="critical"),r=t.violations.some(i=>i.impact==="serious");return e?"high":r?"medium":"low"}estimateEffort(t){let e=t.violations.length;return t.clause.testMethod==="automated"?e<=3?"trivial":e<=10?"minor":"moderate":e<=2?"minor":e<=5?"moderate":"major"}generateRemediationText(t){let e=t.clause.wcagMapping.join(", ");return`Fix ${t.violations.length} violation(s) related to WCAG ${e}. Refer to EN 301 549 clause ${t.clause.id} (${t.clause.title}) for detailed requirements. Test method: ${t.clause.testMethod}.`}calculateOverallStatus(t,e){return t.passed?e&&!e.passed?"partially-compliant":"compliant":t.score>=80?"partially-compliant":"non-compliant"}calculateNextReviewDate(){let t=new Date;return t.setFullYear(t.getFullYear()+1),t}getDeadline(t){let e=new Date;return e.setDate(e.getDate()+t),e}async cacheReport(t){let e=`eu-compliance:${this.hashUrl(t.url)}`;await this.memory.set(e,t,{namespace:"visual-accessibility",ttl:this.config.cacheTTL})}async getCachedReport(t){let e=`eu-compliance:${this.hashUrl(t)}`;return await this.memory.get(e)??null}getEN301549Clauses(){return[...vc]}getEAARequirements(){return[...Iv]}getWCAGMapping(){return[...Mv]}getClausesForWCAG(t){return vc.filter(e=>e.wcagMapping.includes(t))}hashUrl(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return Math.abs(e).toString(36)}};Qm();Km();Cb();Jm();Qm();Km();Jm();k();_();k();X();var $i={"1.1.1":{id:"1.1.1",level:"A",title:"Non-text Content"},"1.3.1":{id:"1.3.1",level:"A",title:"Info and Relationships"},"1.4.1":{id:"1.4.1",level:"A",title:"Use of Color"},"1.4.3":{id:"1.4.3",level:"AA",title:"Contrast (Minimum)"},"1.4.6":{id:"1.4.6",level:"AAA",title:"Contrast (Enhanced)"},"2.1.1":{id:"2.1.1",level:"A",title:"Keyboard"},"2.1.2":{id:"2.1.2",level:"A",title:"No Keyboard Trap"},"2.4.1":{id:"2.4.1",level:"A",title:"Bypass Blocks"},"2.4.3":{id:"2.4.3",level:"A",title:"Focus Order"},"2.4.4":{id:"2.4.4",level:"A",title:"Link Purpose (In Context)"},"2.4.7":{id:"2.4.7",level:"AA",title:"Focus Visible"},"3.1.1":{id:"3.1.1",level:"A",title:"Language of Page"},"4.1.1":{id:"4.1.1",level:"A",title:"Parsing"},"4.1.2":{id:"4.1.2",level:"A",title:"Name, Role, Value"}},bP=x.create("visual-accessibility/accessibility-tester-browser");function wP(c){return c.tool==="agent-browser"&&"getSnapshot"in c}function CP(c){let t=["wcag2a","wcag21a","wcag22a","best-practice"];if(c==="A")return t;let e=[...t,"wcag2aa","wcag21aa","wcag22aa"];return c==="AA"?e:[...e,"wcag2aaa","wcag21aaa","wcag22aaa"]}function Fv(c){return{critical:"critical",high:"serious",medium:"moderate",low:"minor",info:"minor"}[c]??"moderate"}function we(c){return c.success===!1?c.error?.message??"Unknown error":"Unknown error"}async function SP(c,t,e){let r=CP(t),i=e?.excludeSelectors??[],n=`
2940
+ 3. Recommendations (approve/reject/investigate)`}],maxTokens:this.config.llmMaxTokens})).content}catch{return Dv.warn("LLM analysis failed:"),null}}async storeScreenshotMetadata(t){await this.memory.set(`visual-accessibility:screenshot:${t.id}`,t,{namespace:"visual-accessibility",ttl:86400*7})}async getScreenshotById(t){return await this.memory.get(`visual-accessibility:screenshot:${t}`)??null}calculateDiff(t,e){let r=0;if(t.url!==e.url){let h=this.calculateUrlSimilarity(t.url,e.url);r+=(1-h)*3}if(t.viewport.width!==e.viewport.width||t.viewport.height!==e.viewport.height){let h=Math.abs(t.viewport.width-e.viewport.width),v=Math.abs(t.viewport.height-e.viewport.height);r+=(h+v)/100}let n=Math.abs(t.timestamp.getTime()-e.timestamp.getTime())/(1e3*60*60*24);r+=Math.min(n*.1,1),t.viewport.isMobile!==e.viewport.isMobile&&(r+=2);let s=this.hashUrl(t.url+e.url),a=parseInt(s.substring(0,6),36),o=a%100/1e3;r+=o,r=Math.min(Math.max(r,0),100),r=Math.round(r*100)/100;let l=t.viewport.width*t.viewport.height,u=Math.floor(l*r/100),d=this.generateDiffRegions(t,e,r,a),m=this.determineStatus(r),p=r>.1?he.create(`${this.config.diffDirectory}/${e.id}_diff.png`):void 0;return{baselineId:t.id,comparisonId:e.id,diffPercentage:r,diffPixels:u,diffImagePath:p,regions:d,status:m}}generateDiffRegions(t,e,r,i){let n=[];if(r<.1)return n;let s=Math.min(Math.ceil(r),5);for(let a=0;a<s;a++){let o=(i+a*1e3)%80/100,l=(i+a*500)%80/100,u=Math.floor(t.viewport.width*o),d=Math.floor(t.viewport.height*l),m=30+i%50,p=20+i%40,v=["added","removed","modified"][(i+a)%3],b=r>2?"high":r>.5?"medium":"low";n.push({x:u,y:d,width:m,height:p,changeType:v,significance:b})}return n}calculateUrlSimilarity(t,e){if(t===e)return 1;let r=s=>{try{let a=new URL(s);return{domain:a.hostname,path:a.pathname}}catch{return{domain:s,path:""}}},i=r(t),n=r(e);if(i.domain===n.domain){let s=i.path.split("/").filter(Boolean),a=n.path.split("/").filter(Boolean),o=s.filter(u=>a.includes(u)).length,l=Math.max(s.length,a.length,1);return .5+o/l*.5}return 0}determineStatus(t){return t===0?"identical":t<=this.config.diffThreshold?"acceptable":t<=5?"changed":"failed"}async storeDiffResult(t){let e=`${t.baselineId}_${t.comparisonId}`;await this.memory.set(`visual-accessibility:diff:${e}`,t,{namespace:"visual-accessibility",ttl:86400*30})}getBaselineKey(t,e){return`${this.hashUrl(t)}_${e.width}x${e.height}_${e.deviceScaleFactor}`}hashUrl(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return Math.abs(e).toString(36)}estimateLoadTime(t,e){let r=800,i=this.hashUrl(t),n=parseInt(i.substring(0,4),36);t.length>100&&(r+=200),t.includes("?")&&(r+=150),(t.includes("dashboard")||t.includes("admin"))&&(r+=300),(t.includes("api")||t.includes("json"))&&(r-=200);let s=e.width*e.height;return r+=Math.floor(s/5e4)*50,e.isMobile&&(r-=100),r+=n%400,Math.max(300,Math.min(r,5e3))}};function yc(c,t={}){return new Zd(c,t)}_();k();var vc=[{id:"9.1.1.1",title:"Non-text content",chapter:"9.1.1",wcagMapping:["1.1.1"],description:"All non-text content that is presented to the user has a text alternative that serves the equivalent purpose.",testMethod:"automated"},{id:"9.1.2.1",title:"Audio-only and video-only (prerecorded)",chapter:"9.1.2",wcagMapping:["1.2.1"],description:"For prerecorded audio-only and prerecorded video-only media, alternatives are provided.",testMethod:"manual"},{id:"9.1.2.2",title:"Captions (prerecorded)",chapter:"9.1.2",wcagMapping:["1.2.2"],description:"Captions are provided for all prerecorded audio content in synchronized media.",testMethod:"hybrid"},{id:"9.1.2.3",title:"Audio description or media alternative (prerecorded)",chapter:"9.1.2",wcagMapping:["1.2.3"],description:"An alternative for time-based media or audio description is provided.",testMethod:"manual"},{id:"9.1.2.5",title:"Audio description (prerecorded)",chapter:"9.1.2",wcagMapping:["1.2.5"],description:"Audio description is provided for all prerecorded video content.",testMethod:"manual"},{id:"9.1.3.1",title:"Info and relationships",chapter:"9.1.3",wcagMapping:["1.3.1"],description:"Information, structure, and relationships conveyed through presentation can be programmatically determined.",testMethod:"automated"},{id:"9.1.3.2",title:"Meaningful sequence",chapter:"9.1.3",wcagMapping:["1.3.2"],description:"When the sequence affects meaning, a correct reading sequence can be programmatically determined.",testMethod:"hybrid"},{id:"9.1.3.3",title:"Sensory characteristics",chapter:"9.1.3",wcagMapping:["1.3.3"],description:"Instructions do not rely solely on sensory characteristics.",testMethod:"manual"},{id:"9.1.3.4",title:"Orientation",chapter:"9.1.3",wcagMapping:["1.3.4"],description:"Content does not restrict its view and operation to a single display orientation.",testMethod:"hybrid"},{id:"9.1.3.5",title:"Identify input purpose",chapter:"9.1.3",wcagMapping:["1.3.5"],description:"The purpose of each input field collecting user information can be programmatically determined.",testMethod:"automated"},{id:"9.1.4.1",title:"Use of colour",chapter:"9.1.4",wcagMapping:["1.4.1"],description:"Colour is not used as the only visual means of conveying information.",testMethod:"manual"},{id:"9.1.4.2",title:"Audio control",chapter:"9.1.4",wcagMapping:["1.4.2"],description:"A mechanism is available to pause or stop audio that plays automatically.",testMethod:"manual"},{id:"9.1.4.3",title:"Contrast (minimum)",chapter:"9.1.4",wcagMapping:["1.4.3"],description:"Visual presentation of text has a contrast ratio of at least 4.5:1.",testMethod:"automated"},{id:"9.1.4.4",title:"Resize text",chapter:"9.1.4",wcagMapping:["1.4.4"],description:"Text can be resized without assistive technology up to 200 percent.",testMethod:"hybrid"},{id:"9.1.4.5",title:"Images of text",chapter:"9.1.4",wcagMapping:["1.4.5"],description:"Text is used to convey information rather than images of text.",testMethod:"hybrid"},{id:"9.1.4.10",title:"Reflow",chapter:"9.1.4",wcagMapping:["1.4.10"],description:"Content can be presented without loss of information or functionality at 320 CSS pixels.",testMethod:"hybrid"},{id:"9.1.4.11",title:"Non-text contrast",chapter:"9.1.4",wcagMapping:["1.4.11"],description:"Visual presentation of UI components and graphical objects has a contrast ratio of at least 3:1.",testMethod:"automated"},{id:"9.1.4.12",title:"Text spacing",chapter:"9.1.4",wcagMapping:["1.4.12"],description:"No loss of content or functionality occurs when text spacing is adjusted.",testMethod:"hybrid"},{id:"9.1.4.13",title:"Content on hover or focus",chapter:"9.1.4",wcagMapping:["1.4.13"],description:"Additional content triggered by hover or focus is dismissible, hoverable, and persistent.",testMethod:"manual"},{id:"9.2.1.1",title:"Keyboard",chapter:"9.2.1",wcagMapping:["2.1.1"],description:"All functionality is operable through a keyboard interface.",testMethod:"hybrid"},{id:"9.2.1.2",title:"No keyboard trap",chapter:"9.2.1",wcagMapping:["2.1.2"],description:"Keyboard focus can be moved away from any component using only a keyboard.",testMethod:"hybrid"},{id:"9.2.1.4",title:"Character key shortcuts",chapter:"9.2.1",wcagMapping:["2.1.4"],description:"Keyboard shortcuts using only letter, punctuation, number, or symbol characters can be turned off or remapped.",testMethod:"manual"},{id:"9.2.2.1",title:"Timing adjustable",chapter:"9.2.2",wcagMapping:["2.2.1"],description:"Users can turn off, adjust, or extend time limits.",testMethod:"manual"},{id:"9.2.2.2",title:"Pause, stop, hide",chapter:"9.2.2",wcagMapping:["2.2.2"],description:"Moving, blinking, scrolling, or auto-updating information can be paused, stopped, or hidden.",testMethod:"manual"},{id:"9.2.3.1",title:"Three flashes or below threshold",chapter:"9.2.3",wcagMapping:["2.3.1"],description:"Web pages do not contain anything that flashes more than three times in any one second period.",testMethod:"automated"},{id:"9.2.4.1",title:"Bypass blocks",chapter:"9.2.4",wcagMapping:["2.4.1"],description:"A mechanism is available to bypass blocks of content that are repeated on multiple web pages.",testMethod:"hybrid"},{id:"9.2.4.2",title:"Page titled",chapter:"9.2.4",wcagMapping:["2.4.2"],description:"Web pages have titles that describe topic or purpose.",testMethod:"automated"},{id:"9.2.4.3",title:"Focus order",chapter:"9.2.4",wcagMapping:["2.4.3"],description:"Focusable components receive focus in an order that preserves meaning and operability.",testMethod:"hybrid"},{id:"9.2.4.4",title:"Link purpose (in context)",chapter:"9.2.4",wcagMapping:["2.4.4"],description:"The purpose of each link can be determined from the link text or its context.",testMethod:"hybrid"},{id:"9.2.4.5",title:"Multiple ways",chapter:"9.2.4",wcagMapping:["2.4.5"],description:"More than one way is available to locate a web page within a set of web pages.",testMethod:"manual"},{id:"9.2.4.6",title:"Headings and labels",chapter:"9.2.4",wcagMapping:["2.4.6"],description:"Headings and labels describe topic or purpose.",testMethod:"hybrid"},{id:"9.2.4.7",title:"Focus visible",chapter:"9.2.4",wcagMapping:["2.4.7"],description:"Any keyboard operable user interface has a mode of operation where the keyboard focus indicator is visible.",testMethod:"hybrid"},{id:"9.2.5.1",title:"Pointer gestures",chapter:"9.2.5",wcagMapping:["2.5.1"],description:"All functionality that uses multipoint or path-based gestures can be operated with a single pointer.",testMethod:"manual"},{id:"9.2.5.2",title:"Pointer cancellation",chapter:"9.2.5",wcagMapping:["2.5.2"],description:"Functions triggered by single pointer can be cancelled.",testMethod:"manual"},{id:"9.2.5.3",title:"Label in name",chapter:"9.2.5",wcagMapping:["2.5.3"],description:"User interface components with visible labels have accessible names that include the visible text.",testMethod:"automated"},{id:"9.2.5.4",title:"Motion actuation",chapter:"9.2.5",wcagMapping:["2.5.4"],description:"Functionality operated by device motion can be operated by user interface components.",testMethod:"manual"},{id:"9.3.1.1",title:"Language of page",chapter:"9.3.1",wcagMapping:["3.1.1"],description:"The default human language of each web page can be programmatically determined.",testMethod:"automated"},{id:"9.3.1.2",title:"Language of parts",chapter:"9.3.1",wcagMapping:["3.1.2"],description:"The human language of each passage or phrase can be programmatically determined.",testMethod:"hybrid"},{id:"9.3.2.1",title:"On focus",chapter:"9.3.2",wcagMapping:["3.2.1"],description:"Receiving focus does not initiate a change of context.",testMethod:"hybrid"},{id:"9.3.2.2",title:"On input",chapter:"9.3.2",wcagMapping:["3.2.2"],description:"Changing the setting of a user interface component does not automatically cause a change of context.",testMethod:"hybrid"},{id:"9.3.2.3",title:"Consistent navigation",chapter:"9.3.2",wcagMapping:["3.2.3"],description:"Navigational mechanisms that are repeated are in the same relative order.",testMethod:"manual"},{id:"9.3.2.4",title:"Consistent identification",chapter:"9.3.2",wcagMapping:["3.2.4"],description:"Components with the same functionality are identified consistently.",testMethod:"manual"},{id:"9.3.3.1",title:"Error identification",chapter:"9.3.3",wcagMapping:["3.3.1"],description:"If an input error is detected, the item in error is identified and described to the user.",testMethod:"hybrid"},{id:"9.3.3.2",title:"Labels or instructions",chapter:"9.3.3",wcagMapping:["3.3.2"],description:"Labels or instructions are provided when content requires user input.",testMethod:"hybrid"},{id:"9.3.3.3",title:"Error suggestion",chapter:"9.3.3",wcagMapping:["3.3.3"],description:"If an input error is detected and suggestions for correction are known, the suggestions are provided.",testMethod:"hybrid"},{id:"9.3.3.4",title:"Error prevention (legal, financial, data)",chapter:"9.3.3",wcagMapping:["3.3.4"],description:"Submissions are reversible, checked, or confirmed for legal, financial, or data-deletion actions.",testMethod:"manual"},{id:"9.4.1.1",title:"Parsing",chapter:"9.4.1",wcagMapping:["4.1.1"],description:"In content implemented using markup languages, elements have complete start and end tags.",testMethod:"automated"},{id:"9.4.1.2",title:"Name, role, value",chapter:"9.4.1",wcagMapping:["4.1.2"],description:"User interface components have name and role programmatically determined.",testMethod:"automated"},{id:"9.4.1.3",title:"Status messages",chapter:"9.4.1",wcagMapping:["4.1.3"],description:"Status messages can be programmatically determined without receiving focus.",testMethod:"hybrid"}],Iv=[{id:"EAA-I.1",title:"Perceivable information",article:"Annex I, Section I",description:"Information shall be perceivable through more than one sensory channel.",applicableTo:["e-commerce","banking-services","transport-services"],en301549Mapping:["9.1.1.1","9.1.2.1","9.1.2.2","9.1.3.1"]},{id:"EAA-I.2",title:"Operable user interface",article:"Annex I, Section I",description:"User interface shall be operable through multiple input modalities.",applicableTo:["e-commerce","banking-services","transport-services","e-books"],en301549Mapping:["9.2.1.1","9.2.1.2","9.2.4.1","9.2.4.3"]},{id:"EAA-I.3",title:"Understandable operation",article:"Annex I, Section I",description:"Operation of the product and its user interface shall be understandable.",applicableTo:["e-commerce","banking-services","transport-services"],en301549Mapping:["9.3.1.1","9.3.2.1","9.3.3.1","9.3.3.2"]},{id:"EAA-I.4",title:"Robust content",article:"Annex I, Section I",description:"Content shall be robust enough to be interpreted by assistive technologies.",applicableTo:["e-commerce","banking-services","transport-services","e-books","audiovisual-media"],en301549Mapping:["9.4.1.1","9.4.1.2","9.4.1.3"]},{id:"EAA-II.1",title:"Accessible support services",article:"Annex I, Section II",description:"Support services shall provide information on accessibility features.",applicableTo:["e-commerce","banking-services","transport-services"],en301549Mapping:[]},{id:"EAA-III.1",title:"Electronic identification",article:"Annex I, Section III",description:"Electronic identification and authentication shall be accessible.",applicableTo:["banking-services","e-commerce"],en301549Mapping:["9.2.1.1","9.3.3.1","9.3.3.2"]}],Mv=vc.flatMap(c=>c.wcagMapping.map(t=>({wcagCriterion:t,wcagLevel:gP(t),en301549Clause:c.id,en301549Chapter:c.chapter,conformanceLevel:"required"})));function gP(c){let t=["1.1.1","1.2.1","1.2.2","1.2.3","1.3.1","1.3.2","1.3.3","1.4.1","1.4.2","2.1.1","2.1.2","2.1.4","2.2.1","2.2.2","2.3.1","2.4.1","2.4.2","2.4.3","2.4.4","2.5.1","2.5.2","2.5.3","2.5.4","3.1.1","3.2.1","3.2.2","3.3.1","3.3.2","4.1.1","4.1.2"],e=["1.2.4","1.2.5","1.3.4","1.3.5","1.4.3","1.4.4","1.4.5","1.4.10","1.4.11","1.4.12","1.4.13","2.4.5","2.4.6","2.4.7","3.1.2","3.2.3","3.2.4","3.3.3","3.3.4","4.1.3"];return t.includes(c)?"A":e.includes(c)?"AA":"AAA"}var hP={en301549Version:"3.2.1",includeEAA:!0,defaultProductCategory:"e-commerce",cacheTTL:3600},bc=class{constructor(t,e={}){this.memory=t;this.config={...hP,...e}}memory;config;async validateCompliance(t,e){try{let r=e?.en301549Version??this.config.en301549Version,i=e?.includeEAA??this.config.includeEAA,n=e?.productCategory??this.config.defaultProductCategory,s=e?.excludeClauses??[],a=this.validateEN301549(t,r,s),o;i&&(o=this.validateEAA(a,n));let l=this.calculateOverallStatus(a,o),u=a.score,d=a.passed&&(!o||o.passed),m={url:t.url,timestamp:new Date,en301549:a,eaaCompliance:o,overallStatus:l,complianceScore:u,certificationReady:d,nextReviewDate:this.calculateNextReviewDate()};return await this.cacheReport(m),f(m)}catch(r){return g(y(r))}}validateEN301549(t,e,r){let i=[],n=[],s=[],a=new Map;for(let m of t.violations)for(let p of m.wcagCriteria){let h=a.get(p.id)??[];h.push(m),a.set(p.id,h)}for(let m of vc){if(r.includes(m.id))continue;let p=[],h=!1;for(let b of m.wcagMapping){let C=a.get(b);C&&C.length>0&&(p.push(...C),h=!0)}let v={clause:m,status:h?"failed":"passed",violations:p};if(h){let b=m.wcagMapping.length;m.wcagMapping.filter(S=>a.has(S)).length<b&&b>1?s.push({...v,status:"partial"}):i.push(v)}else n.push(v)}let o=i.length+n.length+s.length,l=n.length+s.length*.5,u=o>0?Math.round(l/o*100):100,d=this.generateRecommendations(i,s);return{standard:"EN301549",version:e,passed:i.length===0,score:u,failedClauses:i,passedClauses:n,partialClauses:s,wcagMapping:Mv,recommendations:d}}validateEAA(t,e){let r=Iv.filter(n=>n.applicableTo.includes(e)),i=[];for(let n of r){let s=n.en301549Mapping.filter(a=>t.failedClauses.some(o=>o.clause.id===a));s.length>0&&i.push({requirement:n,status:s.length===n.en301549Mapping.length?"not-met":"partially-met",evidence:`Failed EN 301 549 clauses: ${s.join(", ")}`,remediationRequired:!0})}return{productCategory:e,passed:i.length===0,applicableRequirements:r,failedRequirements:i}}generateRecommendations(t,e){let r=[],i=[...t,...e].sort((n,s)=>n.clause.testMethod!==s.clause.testMethod?n.clause.testMethod==="automated"?-1:1:s.violations.length-n.violations.length);for(let n of i){let s=this.calculatePriority(n),a=this.estimateEffort(n);r.push({priority:s,clause:n.clause.id,description:`${n.clause.title}: ${n.clause.description}`,remediation:this.generateRemediationText(n),estimatedEffort:a,deadline:s==="high"?this.getDeadline(30):void 0})}return r.slice(0,10)}calculatePriority(t){let e=t.violations.some(i=>i.impact==="critical"),r=t.violations.some(i=>i.impact==="serious");return e?"high":r?"medium":"low"}estimateEffort(t){let e=t.violations.length;return t.clause.testMethod==="automated"?e<=3?"trivial":e<=10?"minor":"moderate":e<=2?"minor":e<=5?"moderate":"major"}generateRemediationText(t){let e=t.clause.wcagMapping.join(", ");return`Fix ${t.violations.length} violation(s) related to WCAG ${e}. Refer to EN 301 549 clause ${t.clause.id} (${t.clause.title}) for detailed requirements. Test method: ${t.clause.testMethod}.`}calculateOverallStatus(t,e){return t.passed?e&&!e.passed?"partially-compliant":"compliant":t.score>=80?"partially-compliant":"non-compliant"}calculateNextReviewDate(){let t=new Date;return t.setFullYear(t.getFullYear()+1),t}getDeadline(t){let e=new Date;return e.setDate(e.getDate()+t),e}async cacheReport(t){let e=`eu-compliance:${this.hashUrl(t.url)}`;await this.memory.set(e,t,{namespace:"visual-accessibility",ttl:this.config.cacheTTL})}async getCachedReport(t){let e=`eu-compliance:${this.hashUrl(t)}`;return await this.memory.get(e)??null}getEN301549Clauses(){return[...vc]}getEAARequirements(){return[...Iv]}getWCAGMapping(){return[...Mv]}getClausesForWCAG(t){return vc.filter(e=>e.wcagMapping.includes(t))}hashUrl(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return Math.abs(e).toString(36)}};Qm();Km();Cb();Jm();Qm();Km();Jm();k();_();k();X();var $i={"1.1.1":{id:"1.1.1",level:"A",title:"Non-text Content"},"1.3.1":{id:"1.3.1",level:"A",title:"Info and Relationships"},"1.4.1":{id:"1.4.1",level:"A",title:"Use of Color"},"1.4.3":{id:"1.4.3",level:"AA",title:"Contrast (Minimum)"},"1.4.6":{id:"1.4.6",level:"AAA",title:"Contrast (Enhanced)"},"2.1.1":{id:"2.1.1",level:"A",title:"Keyboard"},"2.1.2":{id:"2.1.2",level:"A",title:"No Keyboard Trap"},"2.4.1":{id:"2.4.1",level:"A",title:"Bypass Blocks"},"2.4.3":{id:"2.4.3",level:"A",title:"Focus Order"},"2.4.4":{id:"2.4.4",level:"A",title:"Link Purpose (In Context)"},"2.4.7":{id:"2.4.7",level:"AA",title:"Focus Visible"},"3.1.1":{id:"3.1.1",level:"A",title:"Language of Page"},"4.1.1":{id:"4.1.1",level:"A",title:"Parsing"},"4.1.2":{id:"4.1.2",level:"A",title:"Name, Role, Value"}},wP=x.create("visual-accessibility/accessibility-tester-browser");function CP(c){return c.tool==="agent-browser"&&"getSnapshot"in c}function SP(c){let t=["wcag2a","wcag21a","wcag22a","best-practice"];if(c==="A")return t;let e=[...t,"wcag2aa","wcag21aa","wcag22aa"];return c==="AA"?e:[...e,"wcag2aaa","wcag21aaa","wcag22aaa"]}function Fv(c){return{critical:"critical",high:"serious",medium:"moderate",low:"minor",info:"minor"}[c]??"moderate"}function we(c){return c.success===!1?c.error?.message??"Unknown error":"Unknown error"}async function RP(c,t,e){let r=SP(t),i=e?.excludeSelectors??[],n=`
2941
2941
  (async function() {
2942
2942
  // Check if axe is already loaded
2943
2943
  if (typeof axe === 'undefined') {
@@ -2986,8 +2986,8 @@ Provide:
2986
2986
  inapplicable: results.inapplicable.map(i => i.id)
2987
2987
  });
2988
2988
  })();
2989
- `,s=await c.evaluate(n);if(!s.success)return g(new Error(`Failed to run axe-core: ${s.error?.message??"Unknown error"}`));try{let a=D(s.value);return f(a)}catch(a){return g(new Error(`Failed to parse axe-core results: ${a}`))}}function RP(c,t){let e=[];for(let r of c){let i=r.match(/^wcag(\d)(\d)(\d)(\d)?$/);if(i){let n=i[4]?`${i[1]}.${i[2]}.${i[3]}${i[4]}`:`${i[1]}.${i[2]}.${i[3]}`,s=$i[n];s?e.push(s):e.push({id:n,level:t,title:`WCAG ${n}`})}}return e}function TP(c,t,e){let r=t.violations.map(u=>({id:u.id,impact:Fv(u.impact??"moderate"),wcagCriteria:RP(u.tags??[],e),description:u.description,help:u.help,helpUrl:u.helpUrl??`https://dequeuniversity.com/rules/axe/4.8/${u.id}`,nodes:u.nodes.map(d=>({selector:d.selector,html:d.html,target:d.target,failureSummary:d.failureSummary??""}))})),i=t.passes.map(u=>({id:u,description:`Rule ${u} passed`,nodes:0})),n=t.incomplete.map(u=>({id:u,description:`Rule ${u} requires manual review`,reason:"Could not automatically determine compliance",nodes:[]})),s=r.length+i.length+n.length,a=r.reduce((u,d)=>u+{critical:4,serious:3,moderate:2,minor:1}[d.impact],0),o=s*4,l=s>0?Math.round((o-a)/o*100):100;return{url:c,timestamp:new Date,violations:r,passes:i,incomplete:n,score:Math.max(0,Math.min(100,l)),wcagLevel:e}}function Lv(c,t,e){let r=t.violations.map(u=>({id:u.id,impact:Fv(u.impact),wcagCriteria:u.wcagCriterion?[{id:u.wcagCriterion,level:e,title:u.rule}]:[],description:u.description,help:u.help,helpUrl:u.helpUrl??"https://www.w3.org/WAI/WCAG22/Understanding/",nodes:u.nodes.map(d=>({selector:d.selector,html:d.html,target:d.target,failureSummary:d.failureSummary}))})),i=t.passedRules.map(u=>({id:u,description:`Rule ${u} passed`,nodes:0})),n=t.incompleteRules.map(u=>({id:u,description:`Rule ${u} requires manual review`,reason:"Could not automatically determine compliance",nodes:[]})),s=r.length+i.length+n.length,a=r.reduce((u,d)=>u+{critical:4,serious:3,moderate:2,minor:1}[d.impact],0),o=s*4,l=s>0?Math.round((o-a)/o*100):100;return{url:c,timestamp:new Date,violations:r,passes:i,incomplete:n,score:Math.max(0,Math.min(100,l)),wcagLevel:e}}function EP(c,t){let e=[];for(let r of c.violations)if(r.rule.includes("contrast")||r.id.includes("contrast"))for(let i of r.nodes){let n=i.failureSummary.match(/foreground:?\s*([#\w\d]+).*?background:?\s*([#\w\d]+)/i),s=i.failureSummary.match(/ratio\s*[:\s]*(\d+\.?\d*)/i);e.push({element:i.selector,foreground:n?.[1]||"#000000",background:n?.[2]||"#ffffff",ratio:s?parseFloat(s[1]):1,requiredRatio:t==="AAA"?7:4.5,passes:!1,wcagLevel:t})}if(e.length===0&&c.passedRules.some(r=>r.includes("contrast"))){let r=["h1","p","a","button"];for(let i of r)e.push({element:i,foreground:"#333333",background:"#ffffff",ratio:12.63,requiredRatio:t==="AAA"?7:4.5,passes:!0,wcagLevel:t})}return e}async function $v(c,t,e,r,i){try{let n=await c.launch({headless:r.headless});if(!n.success)return g(new Error(`Failed to launch browser: ${n.error?.message??"Unknown error"}`));try{let s=await c.navigate(t);if(!s.success)return g(new Error(`Failed to navigate to ${t}: ${s.error?.message??"Unknown error"}`));if(wP(c)){let l=await c.getSnapshot({interactive:!0});if(l.success){let u=l.value.interactiveElements.length;bP.debug(`Found ${u} interactive elements`)}}let a=await SP(c,e,i);if(!a.success)return g(a.error);let o=TP(t,a.value,e);return f(o)}finally{await c.quit()}}catch(n){return g(y(n))}}async function Ov(c,t,e,r,i){try{let n=await c.launch({headless:r.headless});if(!n.success)return g(new Error(`Failed to launch browser: ${we(n)}`));try{let s=await c.navigate({url:t,waitUntil:"networkidle",timeout:r.timeout});if(!s.success)return g(new Error(`Failed to navigate to ${t}: ${we(s)}`));let a=await c.checkAccessibility({wcagLevel:e,selector:i?.excludeSelectors?.[0]});if(!a.success)return g(new Error(`Accessibility check failed: ${we(a)}`));let o=Lv(t,a.value,e);return f(o)}finally{await c.quit()}}catch(n){return g(y(n))}}async function Nv(c,t,e,r,i){try{let n=await c.launch({headless:i.headless});if(!n.success)return g(new Error(`Failed to launch browser: ${we(n)}`));try{let s=await c.navigate({url:t,waitUntil:"networkidle",timeout:i.timeout});if(!s.success)return g(new Error(`Failed to navigate to ${t}: ${we(s)}`));let a=await c.checkAccessibility({wcagLevel:r,selector:e});if(!a.success)return g(new Error(`Element accessibility check failed: ${we(a)}`));let o=Lv(t,a.value,r);return f(o)}finally{await c.quit()}}catch(n){return g(y(n))}}async function _v(c,t,e,r){try{let i=await c.launch({headless:r.headless});if(!i.success)return g(new Error(`Failed to launch browser: ${we(i)}`));try{let n=await c.navigate({url:t,waitUntil:"networkidle",timeout:r.timeout});if(!n.success)return g(new Error(`Failed to navigate to ${t}: ${we(n)}`));let s=await c.checkAccessibility({wcagLevel:e,rules:{include:["color-contrast"]}});if(!s.success)return g(new Error(`Contrast check failed: ${we(s)}`));let a=EP(s.value,e);return f(a)}finally{await c.quit()}}catch(i){return g(y(i))}}async function Vv(c,t,e,r){try{let i=await c.launch({headless:r.headless});if(!i.success)return g(new Error(`Failed to launch browser: ${we(i)}`));try{let n=await c.navigate({url:t,waitUntil:"networkidle",timeout:r.timeout});if(!n.success)return g(new Error(`Failed to navigate to ${t}: ${we(n)}`));let a=await c.findElements({selector:'a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])',visible:!0});if(!a.success)return g(new Error(`Failed to find focusable elements: ${we(a)}`));let o=a.value.map((p,h)=>({index:h,selector:p.selector,elementType:AP(p.tagName),hasVisibleFocus:!0})),l=await c.checkAccessibility({wcagLevel:e,rules:{include:["keyboard","focus-order","focus-trap","bypass-blocks"]}}),u=[],d=[];if(l.success){for(let p of l.value.violations)if(p.rule.includes("focus")||p.rule.includes("keyboard"))for(let h of p.nodes)p.rule.includes("trap")?d.push({selector:h.selector,description:h.failureSummary,escapePath:"Ensure Escape key or Tab can exit this element"}):u.push({type:xP(p.rule),selector:h.selector,description:h.failureSummary})}let m={url:t,focusableElements:o.length,tabOrder:o,issues:u,traps:d};return f(m)}finally{await c.quit()}}catch(i){return g(y(i))}}function AP(c){return{a:"link",button:"button",input:"input",select:"input",textarea:"input"}[c.toLowerCase()]||"other"}function xP(c){return c.includes("focus-indicator")||c.includes("visible")?"no-focus-indicator":c.includes("skip")||c.includes("bypass")?"skip-link-missing":c.includes("order")||c.includes("sequence")?"incorrect-tab-order":"non-interactive-focusable"}function Bv(){return[{id:"image-alt",description:"Images must have alternate text",wcagCriteria:["1.1.1"],impact:"critical",simulationFailureRate:.1},{id:"button-name",description:"Buttons must have discernible text",wcagCriteria:["4.1.2"],impact:"critical",simulationFailureRate:.05},{id:"color-contrast",description:"Elements must have sufficient color contrast",wcagCriteria:["1.4.3"],impact:"serious",simulationFailureRate:.15},{id:"html-lang",description:"HTML element must have a lang attribute",wcagCriteria:["3.1.1"],impact:"serious",simulationFailureRate:.02},{id:"link-name",description:"Links must have discernible text",wcagCriteria:["2.4.4","4.1.2"],impact:"serious",simulationFailureRate:.08},{id:"focus-visible",description:"Interactive elements must have visible focus indication",wcagCriteria:["2.4.7"],impact:"serious",simulationFailureRate:.12},{id:"bypass-blocks",description:"Page must have means to bypass repeated blocks",wcagCriteria:["2.4.1"],impact:"moderate",simulationFailureRate:.1},{id:"label",description:"Form elements must have labels",wcagCriteria:["1.3.1","4.1.2"],impact:"critical",simulationFailureRate:.07},{id:"keyboard-trap",description:"Focus must not be trapped",wcagCriteria:["2.1.2"],impact:"critical",simulationFailureRate:.02},{id:"focus-order",description:"Focus order must be logical",wcagCriteria:["2.4.3"],impact:"moderate",simulationFailureRate:.05}]}function em(c,t){let e={A:1,AA:2,AAA:3},r=e[t];return c.filter(i=>i.wcagCriteria.some(n=>{let s=$i[n];return s&&e[s.level]<=r}))}function qv(c,t,e,r){if(e){let s=WP(c,t),a=zv(c,t);return{nodes:s,passed:s.length===0,checkedNodes:a}}let i=PP(c,t,r),n=zv(c,t);return{nodes:i,passed:i.length===0,checkedNodes:n}}function PP(c,t,e){let r=[],i=t.url.toLowerCase();switch(c.id){case"image-alt":kP(i)&&r.push(..._P());break;case"button-name":DP(i)&&r.push(...VP());break;case"color-contrast":e&&r.push(...zP());break;case"html-lang":IP(i)&&r.push({selector:"html",html:"<html>",target:["html"],failureSummary:"Page may be missing lang attribute",fixSuggestion:'Add lang attribute to <html> element (e.g., <html lang="en">)'});break;case"link-name":MP(i)&&r.push(...BP());break;case"focus-visible":FP(i)&&r.push(...qP());break;case"bypass-blocks":LP(i)||r.push({selector:"body",html:"<body>",target:["body"],failureSummary:"Page may lack skip navigation mechanism",fixSuggestion:"Add a skip link at the beginning of the page to bypass repeated content"});break;case"label":$P(i)&&r.push(...GP());break;case"keyboard-trap":OP(i)&&r.push(...jP());break;case"focus-order":NP(i)&&r.push(...HP());break}return r}function kP(c){return c.includes("gallery")||c.includes("photo")||c.includes("image")||c.includes("product")||c.includes("portfolio")||c.includes("media")}function DP(c){return c.includes("app")||c.includes("dashboard")||c.includes("editor")||c.includes("tool")||c.includes("builder")||c.includes("widget")}function IP(c){return c.includes("cdn")||c.includes("static")||c.includes(".html")||c.includes("file://")}function MP(c){return c.includes("nav")||c.includes("menu")||c.includes("header")||c.includes("sidebar")||c.includes("footer")}function FP(c){return c.includes("app")||c.includes("dashboard")||c.includes("#/")||c.includes("react")||c.includes("angular")||c.includes("vue")}function LP(c){return c.includes("gov")||c.includes("edu")||c.includes("a11y")||c.includes("accessible")}function $P(c){return c.includes("form")||c.includes("contact")||c.includes("register")||c.includes("signup")||c.includes("login")||c.includes("checkout")||c.includes("submit")||c.includes("search")}function OP(c){return c.includes("modal")||c.includes("dialog")||c.includes("popup")||c.includes("overlay")||c.includes("lightbox")}function NP(c){return c.includes("dashboard")||c.includes("admin")||c.includes("grid")||c.includes("layout")||c.includes("multi")}function _P(){return[{selector:"img",html:'<img src="...">',target:["img"],failureSummary:"Images should have descriptive alt text",fixSuggestion:"Add alt attribute with meaningful description to all <img> elements"}]}function VP(){return[{selector:"button:not([aria-label])",html:"<button>",target:["button"],failureSummary:"Buttons should have accessible names",fixSuggestion:"Ensure buttons have visible text or aria-label attribute"}]}function zP(){return[{selector:".text-content",html:'<div class="text-content">',target:[".text-content"],failureSummary:"Text elements should meet WCAG 2.2 AA contrast ratio (4.5:1)",fixSuggestion:"Verify text color has sufficient contrast against background"}]}function BP(){return[{selector:"a:not([aria-label])",html:'<a href="#">',target:["a"],failureSummary:"Links should have descriptive text",fixSuggestion:"Add meaningful link text or aria-label attribute"}]}function qP(){return[{selector:":focus",html:"<element>:focus",target:[":focus"],failureSummary:"Interactive elements should have visible focus indicators",fixSuggestion:"Do not remove outline on :focus; use :focus-visible for styling"}]}function GP(){return[{selector:"input:not([aria-label]):not([id])",html:'<input type="text">',target:["input"],failureSummary:"Form inputs should have associated labels",fixSuggestion:'Add <label for="id"> or aria-label to form inputs'}]}function jP(){return[{selector:'[role="dialog"]',html:'<div role="dialog">',target:['[role="dialog"]'],failureSummary:"Modal dialogs should not trap keyboard focus",fixSuggestion:"Ensure Escape key closes modal and Tab cycles within dialog"}]}function HP(){return[{selector:"[tabindex]",html:'<div tabindex="...">',target:["[tabindex]"],failureSummary:"Focus order should follow logical reading sequence",fixSuggestion:'Avoid positive tabindex values; use tabindex="0" or "-1"'}]}function WP(c,t){let e=[],r=or(t.url),i=parseInt(r,36),n=c.id.split("").reduce((a,o)=>a+o.charCodeAt(0),0),s=1+(i+n)%10;for(let a=0;a<s;a++)if((i+n+a*100)%100/100<c.simulationFailureRate){let l=UP(c.id,a);e.push({selector:l,html:`<element class="${c.id}-element-${a}">Content</element>`,target:[l],failureSummary:"Element does not meet accessibility requirements",fixSuggestion:"Review and update the element to meet WCAG guidelines"})}return e}function UP(c,t){let r={"image-alt":["img"],"button-name":["button"],"color-contrast":["div","p","span"],"html-lang":["html"],"link-name":["a"],"focus-visible":["button","a","input"],"bypass-blocks":["main","nav"],label:["input","select","textarea"],"keyboard-trap":["div","dialog"],"focus-order":["button","a","input"]}[c]||["div"],i=r[t%r.length],n=["content","widget","component","item","element"],s=n[t%n.length];return`${i}.${s}`}function zv(c,t){let e=c.id.toLowerCase();return e.includes("image")||e.includes("alt")?5+t.url.length%10:e.includes("form")||e.includes("label")||e.includes("input")?8+t.url.length%12:e.includes("link")||e.includes("anchor")?15+t.url.length%20:e.includes("color")||e.includes("contrast")?20+t.url.length%15:e.includes("heading")||e.includes("h1")||e.includes("h2")?6+t.url.length%8:e.includes("aria")||e.includes("role")?12+t.url.length%18:10+t.url.length%10}function Gv(c,t){let r={"1.1.1":.12,"1.3.1":.08,"1.4.1":.05,"1.4.3":.15,"1.4.6":.25,"2.1.1":.1,"2.1.2":.03,"2.4.1":.08,"2.4.3":.06,"2.4.4":.1,"2.4.7":.12,"3.1.1":.04,"4.1.1":.02,"4.1.2":.09}[c.id]??.1,i=c.id.charCodeAt(0)*100,s=(t+i)%100/100>=r;return{passed:s,reason:s?void 0:`Criterion ${c.id} (${c.title}) not fully satisfied`}}function tm(c){let t=["h1","p","a","button",".card-text",".nav-link"],e=[],r=or(c),i=parseInt(r,36);for(let n=0;n<t.length;n++){let s=t[n],a=4.5+(i+n*1e3)%100/10,o=Math.round(a*100)/100,u=s==="h1"||s==="button"?3:4.5,d=o>=u,m=20+(i+n*50)%30,p=200+(i+n*30)%55,h=m.toString(16).padStart(2,"0"),v=p.toString(16).padStart(2,"0");e.push({element:s,foreground:`#${h}${h}${h}`,background:`#${v}${v}${v}`,ratio:o,requiredRatio:u,passes:d,wcagLevel:"AA"})}return e}function rm(c){let t=or(c),e=QP(c,t),r=KP(e),i=JP(c,t);return{url:c,focusableElements:e.length,tabOrder:e,issues:r,traps:i}}function QP(c,t){let e=[],r=parseInt(t,36);return[{selector:"#skip-link",type:"link"},{selector:"header nav a.logo",type:"link"},{selector:"header nav a.menu-item",type:"link"},{selector:"#search-input",type:"input"},{selector:"#search-button",type:"button"},{selector:"main a",type:"link"},{selector:"main button",type:"button"},{selector:"form input",type:"input"},{selector:"form select",type:"input"},{selector:'form button[type="submit"]',type:"button"},{selector:"footer a",type:"link"}].forEach((n,s)=>{let o=(r+s*17)%100>=12;e.push({index:s,selector:n.selector,elementType:n.type,hasVisibleFocus:o})}),e}function KP(c){let t=[];for(let r of c)r.hasVisibleFocus||t.push({type:"no-focus-indicator",selector:r.selector,description:`Element ${r.selector} does not have a visible focus indicator`});return c.some(r=>r.selector.includes("skip"))||t.push({type:"skip-link-missing",selector:"body",description:"Page is missing a skip navigation link"}),c.every((r,i)=>{if(i===0)return!0;let n=r.selector.includes("nav")||r.selector.includes("header"),s=c[i-1].selector.includes("main");return!(n&&s)})||t.push({type:"incorrect-tab-order",selector:"body",description:"Focus order does not follow logical reading sequence"}),t}function JP(c,t){let e=[],r=parseInt(t,36),i=c.includes("modal")||c.includes("dialog")||c.includes("popup"),n=c.includes("form")||c.includes("checkout")||c.includes("register");return i&&r%100<8&&e.push({selector:'.modal, [role="dialog"]',description:"Modal dialog may trap focus without escape mechanism",escapePath:"Ensure Escape key closes modal and focus returns to trigger element"}),n&&r%100<5&&e.push({selector:"form .autocomplete, form .datepicker",description:"Form widget may trap keyboard focus",escapePath:"Add keyboard navigation (Tab/Escape) to exit widget"}),e}function or(c){let t=0;for(let e=0;e<c.length;e++){let r=c.charCodeAt(e);t=(t<<5)-t+r,t=t&t}return Math.abs(t).toString(36)}var YP={defaultWCAGLevel:"AA",includeWarnings:!0,auditTimeout:3e4,enableColorContrastCheck:!0,enableKeyboardCheck:!0,simulationMode:!1,useBrowserMode:!0,browserConfig:{headless:!0,timeout:3e4},browserClient:void 0,preferAgentBrowser:!0},Oi=x.create("visual-accessibility/accessibility-tester"),Ni=class{constructor(t,e={},r){this.memory=t;this.config={...YP,...e},this.rules=Bv(),this.vibiumClient=r??null,this.browserClient=e.browserClient??null,this.euComplianceService=new bc(t)}memory;config;rules;vibiumClient;browserClient;managedBrowserClient=null;euComplianceService;shouldUseBrowserMode(){return this.config.useBrowserMode?this.browserClient||this.config.preferAgentBrowser?!0:!(!Vs()||!zs()||!this.vibiumClient):!1}async getBrowserClient(){if(this.browserClient)return this.browserClient;if(this.managedBrowserClient)return this.managedBrowserClient;if(this.config.preferAgentBrowser)try{let t=await za("accessibility");if(await t.isAvailable())return this.managedBrowserClient=t,t}catch{Oi.debug("Browser client error:")}return null}async audit(t,e){try{let r=e?.wcagLevel||this.config.defaultWCAGLevel;if(this.shouldUseBrowserMode()){let i=await this.getBrowserClient();if(i){let n=await $v(i,t,r,this.config.browserConfig,e);if(n.success)return await this.storeReport(n.value),n;let s=we(n);Oi.warn(`Browser client audit failed: ${s}`)}if(this.vibiumClient&&Vs()&&zs()){let n=await Ov(this.vibiumClient,t,r,this.config.browserConfig,e);if(n.success)return await this.storeReport(n.value),n;let s=we(n);Oi.warn(`Vibium audit failed, falling back to heuristic mode: ${s}`)}}return this.auditWithHeuristics(t,r,e)}catch(r){return g(y(r))}}async auditElement(t,e){if(this.shouldUseBrowserMode()&&this.vibiumClient){let r=await Nv(this.vibiumClient,t,e,this.config.defaultWCAGLevel,this.config.browserConfig);if(r.success)return await this.storeReport(r.value),r;let i=we(r);Oi.warn(`Browser mode element audit failed, falling back to heuristic mode: ${i}`)}return this.audit(t,{excludeSelectors:[],wcagLevel:this.config.defaultWCAGLevel})}async auditWithHeuristics(t,e,r){try{let n=r?.includeWarnings??this.config.includeWarnings?em(this.rules,e):em(this.rules,e).filter(p=>p.impact!=="minor"),s=[],a=[],o=[];for(let p of n){let h=qv(p,{url:t},this.config.simulationMode,this.config.enableColorContrastCheck);h.nodes.length>0?s.push({id:p.id,impact:p.impact,wcagCriteria:p.wcagCriteria.map(v=>$i[v]).filter(Boolean),description:p.description,help:`Fix ${p.description.toLowerCase()}`,helpUrl:`https://www.w3.org/WAI/WCAG22/Understanding/${p.wcagCriteria[0]}`,nodes:h.nodes}):h.passed?a.push({id:p.id,description:p.description,nodes:h.checkedNodes}):o.push({id:p.id,description:p.description,reason:"Could not determine compliance",nodes:h.nodes})}let l=n.length,u=s.length,d=Math.round((l-u)/l*100),m={url:t,timestamp:new Date,violations:s,passes:a,incomplete:o,score:d,wcagLevel:e};return await this.storeReport(m),f(m)}catch(i){return g(y(i))}}async checkContrast(t){try{let e=`visual-accessibility:contrast:${or(t)}`,r=await this.memory.get(e);if(r)return f(r);let i;if(this.shouldUseBrowserMode()&&this.vibiumClient){let n=await _v(this.vibiumClient,t,this.config.defaultWCAGLevel,this.config.browserConfig);if(n.success)i=n.value;else{let s=we(n);Oi.warn(`Browser mode contrast check failed, falling back to heuristic mode: ${s}`),i=tm(t)}}else i=tm(t);return await this.memory.set(e,i,{namespace:"visual-accessibility",ttl:3600}),f(i)}catch(e){return g(y(e))}}async validateWCAGLevel(t,e){try{let r={A:1,AA:2,AAA:3},i=r[e],n=Object.values($i).filter(m=>r[m.level]<=i),s=[],a=[],o=or(t),l=parseInt(o,36);for(let m of n)Gv(m,l).passed?a.push(m):s.push(m);let u=s.length===0,d=Math.round(a.length/n.length*100);return f({level:e,passed:u,failedCriteria:s,passedCriteria:a,score:d})}catch(r){return g(y(r))}}async checkKeyboardNavigation(t){try{let e=`visual-accessibility:keyboard:${or(t)}`,r=await this.memory.get(e);if(r)return f(r);let i;if(this.shouldUseBrowserMode()&&this.config.enableKeyboardCheck&&this.vibiumClient){let n=await Vv(this.vibiumClient,t,this.config.defaultWCAGLevel,this.config.browserConfig);if(n.success)i=n.value;else{let s=we(n);Oi.warn(`Browser mode keyboard check failed, falling back to heuristic mode: ${s}`),i=rm(t)}}else i=rm(t);return await this.memory.set(e,i,{namespace:"visual-accessibility",ttl:3600}),f(i)}catch(e){return g(y(e))}}async storeReport(t){let e=w();await this.memory.set(`visual-accessibility:report:${e}`,t,{namespace:"visual-accessibility",persist:!0}),await this.memory.set(`visual-accessibility:latest:${or(t.url)}`,t,{namespace:"visual-accessibility",persist:!0})}async validateEUCompliance(t,e){try{let r=await this.audit(t,{wcagLevel:"AA",includeWarnings:!0});return r.success?await this.euComplianceService.validateCompliance(r.value,e):g(new Error(`WCAG audit failed: ${r.error.message}`))}catch(r){return g(y(r))}}getEN301549Clauses(){return this.euComplianceService.getEN301549Clauses()}getEAARequirements(){return this.euComplianceService.getEAARequirements()}getWCAGtoEN301549Mapping(){return this.euComplianceService.getWCAGMapping()}async dispose(){this.managedBrowserClient&&(await this.managedBrowserClient.dispose(),this.managedBrowserClient=null)}};k();var wc={"iphone-se":{width:375,height:667,deviceScaleFactor:2,isMobile:!0,hasTouch:!0},"iphone-14":{width:390,height:844,deviceScaleFactor:3,isMobile:!0,hasTouch:!0},"iphone-14-pro-max":{width:430,height:932,deviceScaleFactor:3,isMobile:!0,hasTouch:!0},"ipad-mini":{width:768,height:1024,deviceScaleFactor:2,isMobile:!0,hasTouch:!0},"ipad-pro":{width:1024,height:1366,deviceScaleFactor:2,isMobile:!0,hasTouch:!0},"pixel-7":{width:412,height:915,deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0},"galaxy-s21":{width:360,height:800,deviceScaleFactor:3,isMobile:!0,hasTouch:!0},"desktop-hd":{width:1920,height:1080,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},"desktop-2k":{width:2560,height:1440,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},laptop:{width:1366,height:768,deviceScaleFactor:1,isMobile:!1,hasTouch:!1}},XP={viewports:[wc["iphone-14"],wc["ipad-mini"],wc.laptop,wc["desktop-hd"]],breakpoints:[320,480,768,1024,1280,1920],checkTouchTargets:!0,minFontSize:12,minTouchTargetSize:44,simulationMode:!1},_i=class{constructor(t,e={}){this.memory=t;this.config={...XP,...e}}memory;config;async testResponsiveness(t,e){try{let r={...this.config,...e},i=[],n=[];for(let u of r.viewports){let d=await this.testViewport(t,u,r);i.push(d),n.push(...d.layoutIssues)}let s=this.detectBreakpointIssues(t,i,r),a=this.calculateLayoutScore(i,n),o=this.generateRecommendations(n,s),l={url:t,timestamp:new Date,viewports:i,breakpointIssues:s,layoutScore:a,recommendations:o};return await this.storeResult(l),f(l)}catch(r){return g(y(r))}}async compareViewports(t,e,r){try{let i=this.createScreenshot(t,e),n=this.createScreenshot(t,r),s=this.calculateStructuralDiff(i,n);return f(s)}catch(i){return g(y(i))}}async testBreakpoint(t,e){try{let r={width:e,height:800,deviceScaleFactor:1,isMobile:e<768,hasTouch:e<1024},i=await this.testViewport(t,r,this.config);return f(i)}catch(r){return g(y(r))}}async analyzeBreakpoints(t){try{let e=this.findContentBreaks(t),r=this.config.breakpoints,i=this.suggestBreakpoints(e),n=this.calculateBreakpointCoverage(r,e);return f({currentBreakpoints:r,suggestedBreakpoints:i,contentBreaks:e,coverageScore:n})}catch(e){return g(y(e))}}async testViewport(t,e,r){let i=this.createScreenshot(t,e),n=this.detectLayoutIssues(t,e,r),s=this.hashUrl(t),o=200+(parseInt(s,36)+e.width)%1e3,l=n.filter(u=>u.severity==="critical").length===0;return{viewport:e,screenshot:i,layoutIssues:n,renderTime:o,passed:l}}createScreenshot(t,e){let r=this.hashUrl(t),n=500+(parseInt(r,36)+e.width+e.height)%2e3;return{id:w(),url:t,viewport:e,timestamp:new Date,path:he.create(`.visual-tests/responsive/${e.width}x${e.height}.png`),metadata:{browser:"chromium",os:process.platform,fullPage:!1,loadTime:n}}}detectLayoutIssues(t,e,r){return r.simulationMode?this.detectLayoutIssuesSimulation(t,e,r):this.detectLayoutIssuesHeuristic(t,e,r)}detectLayoutIssuesHeuristic(t,e,r){let i=[],n=t.toLowerCase(),s=this.hasResponsivePatterns(n);e.width<768&&(this.hasWideContentPatterns(n)&&i.push({type:"horizontal-overflow",severity:"critical",element:".wide-content, table, pre",description:"Wide content elements may cause horizontal overflow on mobile",viewport:e}),s||i.push({type:"horizontal-overflow",severity:"warning",element:".container",description:"Page may lack responsive CSS breakpoints for mobile",viewport:e})),e.width<=320&&i.push({type:"text-overflow",severity:"warning",element:"body",description:"Verify viewport meta tag is set correctly for very small screens",viewport:e}),r.checkTouchTargets&&e.hasTouch&&(this.hasInteractiveElements(n)&&i.push({type:"touch-target-size",severity:"warning",element:"button, a, input",description:`Touch targets should be at least ${r.minTouchTargetSize}px for accessibility`,viewport:e}),e.isMobile&&this.hasNavigationElements(n)&&i.push({type:"touch-target-size",severity:"info",element:"nav a",description:"Navigation links may be too small for touch on mobile devices",viewport:e})),e.isMobile&&r.minFontSize>0&&this.hasDataDensePatterns(n)&&i.push({type:"font-size-too-small",severity:"warning",element:".data, .table, .form-label",description:`Font size may be below ${r.minFontSize}px on mobile`,viewport:e}),this.hasImagePatterns(n)&&(e.deviceScaleFactor>1&&i.push({type:"image-not-responsive",severity:"info",element:"img",description:"Verify images use srcset for high-DPI displays",viewport:e}),e.width<480&&i.push({type:"image-not-responsive",severity:"info",element:"img",description:"Verify images are resized for mobile to reduce bandwidth",viewport:e}));let a=this.findNearestBreakpoint(e.width,r.breakpoints);return a.gap>200&&i.push({type:"hidden-content",severity:"info",element:"body",description:`Viewport ${e.width}px is ${a.gap}px from nearest breakpoint (${a.value}px)`,viewport:e}),this.hasOverlapRiskPatterns(n)&&e.width<1024&&i.push({type:"overlapping-elements",severity:"warning",element:".positioned, .absolute, .fixed",description:"Positioned elements may overlap on smaller screens",viewport:e}),i}hasResponsivePatterns(t){return t.includes("mobile")||t.includes("responsive")||t.includes("bootstrap")||t.includes("tailwind")||t.includes("material")||t.includes("foundation")}hasWideContentPatterns(t){return t.includes("table")||t.includes("data")||t.includes("report")||t.includes("code")||t.includes("pre")||t.includes("spreadsheet")}hasInteractiveElements(t){return t.includes("form")||t.includes("button")||t.includes("input")||t.includes("select")||t.includes("click")||t.includes("action")}hasNavigationElements(t){return t.includes("nav")||t.includes("menu")||t.includes("header")||t.includes("sidebar")||t.includes("footer")||t.includes("breadcrumb")}hasDataDensePatterns(t){return t.includes("dashboard")||t.includes("analytics")||t.includes("report")||t.includes("table")||t.includes("stats")||t.includes("metrics")}hasImagePatterns(t){return t.includes("gallery")||t.includes("photo")||t.includes("image")||t.includes("media")||t.includes("portfolio")||t.includes("hero")}hasOverlapRiskPatterns(t){return t.includes("modal")||t.includes("overlay")||t.includes("tooltip")||t.includes("dropdown")||t.includes("popup")||t.includes("float")}findNearestBreakpoint(t,e){let r=e[0]||0,i=Math.abs(t-r);for(let n of e){let s=Math.abs(t-n);s<i&&(i=s,r=n)}return{value:r,gap:i}}detectLayoutIssuesSimulation(t,e,r){let i=[],n=this.hashUrl(t),s=parseInt(n,36),a=(s+e.width)%100/100;e.width<768&&a<.2&&i.push({type:"horizontal-overflow",severity:"critical",element:".container",description:"Content overflows horizontally causing horizontal scroll",viewport:e});let o=(s+e.width+100)%100/100;e.width<480&&o<.15&&i.push({type:"text-overflow",severity:"warning",element:".long-text",description:"Text content is truncated or overflows container",viewport:e});let l=(s+e.width+200)%100/100;r.checkTouchTargets&&e.isMobile&&l<.25&&i.push({type:"touch-target-size",severity:"warning",element:".small-button",description:`Touch target is smaller than ${r.minTouchTargetSize}px minimum`,viewport:e});let u=(s+e.width+300)%100/100;return e.isMobile&&u<.1&&i.push({type:"font-size-too-small",severity:"warning",element:".fine-print",description:`Font size is below ${r.minFontSize}px minimum for readability`,viewport:e}),(s+e.width+400)%100/100<.15&&i.push({type:"image-not-responsive",severity:"info",element:"img.hero-image",description:"Image does not scale properly for viewport width",viewport:e}),i}detectBreakpointIssues(t,e,r){if(!r.simulationMode)return[];let i=[],n=this.hashUrl(t),s=parseInt(n,36),a=[...e].sort((o,l)=>o.viewport.width-l.viewport.width);for(let o=0;o<a.length-1;o++){let l=a[o],u=a[o+1],d=r.breakpoints.find(m=>m>l.viewport.width&&m<u.viewport.width);d&&(s+d+o*100)%100/100<.2&&i.push({breakpoint:d,description:"Layout shifts abruptly at this breakpoint",affectedElements:[".navigation",".sidebar"],suggestion:"Consider adding intermediate styles or adjusting breakpoint"})}return i}calculateLayoutScore(t,e){let i=e.filter(o=>o.severity==="critical").length*15,n=e.filter(o=>o.severity==="warning").length*5,s=e.filter(o=>o.severity==="info").length*1,a=t.every(o=>o.passed)?5:0;return Math.max(0,100-i-n-s+a)}generateRecommendations(t,e){let r=[],i=new Map;for(let n of t){let s=i.get(n.type)||[];i.set(n.type,[...s,n])}return i.has("horizontal-overflow")&&r.push("Use CSS overflow-x: hidden or adjust element widths to prevent horizontal scrolling"),i.has("touch-target-size")&&r.push("Increase touch target sizes to at least 44x44 pixels for better mobile usability"),i.has("font-size-too-small")&&r.push("Use relative font units (rem/em) and ensure minimum 16px base font size on mobile"),i.has("image-not-responsive")&&r.push("Use srcset and sizes attributes for responsive images, or CSS max-width: 100%"),e.length>0&&r.push("Review CSS media queries to ensure smooth transitions between breakpoints"),r}calculateStructuralDiff(t,e){let r=Math.abs(t.viewport.width-e.viewport.width),i=Math.abs(t.viewport.height-e.viewport.height),n=Math.min(50,(r+i)/20);return{baselineId:t.id,comparisonId:e.id,diffPercentage:n,diffPixels:Math.floor(n*1e3),regions:[],status:n<10?"acceptable":"changed"}}findContentBreaks(t){let e=[],r=this.hashUrl(t),i=parseInt(r.substring(0,6),36),n=[375,540,768,992,1200,1400],s=t.includes("shop")||t.includes("product")||t.includes("cart"),a=t.includes("dashboard")||t.includes("admin")||t.includes("panel"),o=t.includes("blog")||t.includes("article")||t.includes("news");for(let l=0;l<n.length;l++){let u=n[l],d=(i+l*100+u)%100,m,p,h;if(s?(m=40,p=[".product-grid",".cart-items",".checkout-form",".filters"],h="Product grid layout adjusts for viewport"):a?(m=50,p=[".sidebar",".dashboard-cards",".data-table",".nav-menu"],h="Dashboard layout reorganizes for smaller screens"):o?(m=60,p=[".article-content",".sidebar-widgets",".comments"],h="Content width and sidebar visibility changes"):(m=55,p=[".container",".grid",".navigation",".footer"],h="Content layout changes significantly"),d<m){let v=Math.min(p.length,1+Math.floor((i+u)%p.length)),b=p.slice(0,v);e.push({width:u,reason:h,affectedElements:b})}}return e}hashUrl(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return Math.abs(e).toString(36)}suggestBreakpoints(t){let e=new Set;for(let i of t){let n=Math.round(i.width/100)*100;e.add(n)}let r=[576,768,992,1200,1400];for(let i of r)Array.from(e).some(n=>Math.abs(n-i)<50)||e.add(i);return Array.from(e).sort((i,n)=>i-n)}calculateBreakpointCoverage(t,e){if(e.length===0)return 100;let r=0;for(let i of e)t.some(n=>Math.abs(n-i.width)<50)&&r++;return Math.round(r/e.length*100)}async storeResult(t){let e=w();await this.memory.set(`visual-accessibility:responsive:${e}`,t,{namespace:"visual-accessibility",persist:!0})}};ge();var ZP={stateSize:10,actionSize:5,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],numWorkers:4,nSteps:5,entropyCoeff:.01,valueLossCoeff:.5},Cc=class extends ve{actor;critic;a2cConfig;actions=[];constructor(t={}){super("a2c","actor-critic"),this.a2cConfig={...ZP,...t},this.initializeActions(),this.actor=new J({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.critic=new J({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate})}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.actor.forward(e),i=Ie.forward(r),n=this.sampleAction(i),s=this.actions[n],a=this.critic.forward(e)[0],o=Math.max(.3,Math.min(1,i[n]+.4));return{action:s,confidence:o,value:a,reasoning:`A2C (${this.a2cConfig.numWorkers} workers): ${s.type}`}}async trainCore(t){let e=this.distributeToWorkers(t),r=0,i=0;for(let[n,s]of Object.entries(e)){if(s.length===0)continue;let a=this.calculateReturns(s),o=this.calculateAdvantages(s,a);for(let l=0;l<s.length;l++){let u=s[l],d=this.prepareState(u.state),m=this.actionToIndex(u.action),p=o[l],h=this.actor.forward(d),v=Ie.forward(h),C=-Math.log(v[m]+1e-10)*p,S=this.calculateEntropy(v),R=this.a2cConfig.entropyCoeff*S,E=new Float32Array(v.length);for(let j=0;j<E.length;j++)j===m?E[j]=-p*(1-v[j]):E[j]=p*v[j];this.actor.backward(E);for(let j of this.actor.layers)j.update(this.config.learningRate*.1);let T=this.critic.forward(d)[0],I=a[l],O=(T-I)**2,q=new Float32Array([I]);this.critic.train(d,q,new Fe),r+=Math.abs(C-R),i+=O}}return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((n,s)=>n+s,0)/this.rewardHistory.length,loss:(r+i)/t.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural A2C for Fleet Coordination",capabilities:["Multi-worker parallel training","Advantage estimation","Combined policy and value learning"],hyperparameters:{stateSize:this.a2cConfig.stateSize,actionSize:this.a2cConfig.actionSize,numWorkers:this.a2cConfig.numWorkers,entropyCoeff:this.a2cConfig.entropyCoeff},stats:this.stats}}distributeToWorkers(t){let e={};for(let r=0;r<this.a2cConfig.numWorkers;r++)e[r]=[];return t.forEach((r,i)=>{let n=i%this.a2cConfig.numWorkers;e[n].push(r)}),e}calculateReturns(t){let e=[],r=0;for(let i=t.length-1;i>=0;i--)r=t[i].reward+this.config.discountFactor*r,e.unshift(r);return e}calculateAdvantages(t,e){return t.map((r,i)=>{let n=this.prepareState(r.state),s=this.critic.forward(n)[0];return e[i]-s})}prepareState(t){let e=t.features.slice(0,this.a2cConfig.stateSize);for(;e.length<this.a2cConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]/=r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"coordinate",value:"parallel"},{type:"coordinate",value:"sequential"},{type:"coordinate",value:"distributed"},{type:"allocate",value:{agents:2}},{type:"rebalance",value:1}],this.a2cConfig.actionSize=this.actions.length,this.actor=new J({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.critic=new J({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate})}actionToIndex(t){let e=`${t.type}:${JSON.stringify(t.value)}`;for(let r=0;r<this.actions.length;r++)if(`${this.actions[r].type}:${JSON.stringify(this.actions[r].value)}`===e)return r;return 0}sampleAction(t){if(z()<this.config.explorationRate)return Se(0,this.actions.length);let e=z(),r=0;for(let i=0;i<t.length;i++)if(r+=t[i],e<=r)return i;return this.argmax(t)}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}calculateEntropy(t){let e=0;for(let r=0;r<t.length;r++)t[r]>0&&(e-=t[r]*Math.log(t[r]));return e}async exportCustomData(){return{actor:this.actor.getParameters(),critic:this.critic.getParameters(),a2cConfig:this.a2cConfig}}async importCustomData(t){t.actor&&this.actor.setParameters(t.actor),t.critic&&this.critic.setParameters(t.critic),t.a2cConfig&&(this.a2cConfig={...this.a2cConfig,...t.a2cConfig}),this.initialized=!0}async resetAlgorithm(){this.actor=new J({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.critic=new J({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate})}};var ek={maxConcurrentWorkflows:5,defaultTimeout:12e4,publishEvents:!0,enableParallelViewportTesting:!0,enableA2C:!0,enableFlashAttention:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Xe=x.create("visual-accessibility"),Sc=class extends ie{constructor(e,r,i,n={},s={},a={},o={},l){let u={...ek,...n};super(e,"visual-accessibility",u,{verifyFindingTypes:["accessibility-violation","visual-regression","wcag-non-compliance"]});this.memory=r;this.agentCoordinator=i;this.visualTester=yc({memory:r,llmRouter:l},s),this.accessibilityTester=new Ni(r,a),this.responsiveTester=new _i(r,o)}memory;agentCoordinator;visualTester;accessibilityTester;responsiveTester;a2cAlgorithm;flashAttention;async onInitialize(){if(this.config.enableA2C)try{this.a2cAlgorithm=new Cc({stateSize:10,actionSize:5,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],numWorkers:4}),Xe.info("A2C algorithm created successfully")}catch(e){throw Xe.error("Failed to create A2C:",e instanceof Error?e:void 0),new Error(`A2C creation failed: ${P(e)}`)}if(this.config.enableFlashAttention)try{this.flashAttention=await tt("test-similarity"),Xe.info("QEFlashAttention initialized successfully")}catch(e){throw Xe.error("Failed to initialize Flash Attention:",e instanceof Error?e:void 0),new Error(`Flash Attention initialization failed: ${P(e)}`)}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState(),this.flashAttention&&(this.flashAttention.dispose(),this.flashAttention=void 0),this.a2cAlgorithm=void 0}getActiveWorkflows(){return super.getActiveWorkflows()}async runVisualTests(e,r){let i=w();try{if(this.startWorkflow(i,"visual"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Xe.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return g(new Error("Operation paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return g(new Error("Agent limit reached, cannot spawn visual testing agents"));let n=await this.spawnVisualTestingAgent(i);if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);this.addAgentToWorkflow(i,n.value);let s=[],a=0,o=0,l=0,u=[];for(let b of e)for(let C of r)u.push({url:b,viewport:C});if(this.config.enableA2C&&u.length>1){let b={urgency:5,availableResources:80,historicalFailureRate:.1},C=await this.prioritizeVisualTests(u.map(S=>({...S,priority:5})),b);C.success&&(u=C.value.orderedTests.map(S=>({url:S.url,viewport:S.viewport})),Xe.info(`[visual-accessibility] Using ${C.value.strategy} strategy for visual test order (confidence: ${C.value.confidence.toFixed(2)})`))}let d=u.length,m=0;for(let{url:b,viewport:C}of u){let S=await this.visualTester.captureScreenshot(b,{viewport:C});if(!S.success){o++,s.push({url:b,viewport:C,status:"failed",screenshot:{id:"",url:b,viewport:C,timestamp:new Date,path:he.create("error-placeholder.png"),metadata:{browser:"",os:"",fullPage:!1,loadTime:0}}});continue}let R=S.value,E=await this.visualTester.getBaseline(b,C);if(!E)await this.visualTester.setBaseline(R),l++,s.push({url:b,viewport:C,status:"new",screenshot:R});else{let T=await this.visualTester.compare(R,E.id);if(T.success){let I=T.value,O=I.status==="identical"||I.status==="acceptable"?"passed":"failed";O==="passed"?a++:o++,s.push({url:b,viewport:C,status:O,diff:I,screenshot:R}),O==="failed"&&this.config.publishEvents&&await this.publishVisualRegressionEvent(b,C,I)}else o++,s.push({url:b,viewport:C,status:"failed",screenshot:R})}m++,this.updateWorkflowProgress(i,m/d*100)}let p=this.workflows.get(i)?.startedAt.getTime()??Date.now(),h=Date.now()-p,v={totalTests:s.length,passed:a,failed:o,newBaselines:l,results:s,duration:h};return this.completeWorkflow(i),await this.agentCoordinator.stop(n.value),f(v)}catch(n){let s=y(n);return this.failWorkflow(i,s.message),{success:!1,error:s}}}async runAccessibilityAudit(e,r){let i=w();try{if(this.startWorkflow(i,"accessibility"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Xe.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return g(new Error("Operation paused: topology is in critical state"));let n=await this.spawnAccessibilityTestingAgent(i,r);if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);this.addAgentToWorkflow(i,n.value);let s=[],a=0,o=0,l=0;for(let p=0;p<e.length;p++){let h=e[p],v=await this.accessibilityTester.audit(h,{wcagLevel:r});if(v.success){let b=v.value;s.push(b),a+=b.violations.length,o+=b.violations.filter(C=>C.impact==="critical").length,b.violations.length===0&&l++,this.config.publishEvents&&await this.publishAccessibilityAuditEvent(b)}this.updateWorkflowProgress(i,(p+1)/e.length*100)}let u=s.length>0?Math.round(s.reduce((p,h)=>p+h.score,0)/s.length):0,d=this.identifyTopIssues(s),m={totalUrls:e.length,passingUrls:l,totalViolations:a,criticalViolations:o,averageScore:u,reports:s,topIssues:d};return this.completeWorkflow(i),await this.agentCoordinator.stop(n.value),f(m)}catch(n){let s=y(n);return this.failWorkflow(i,s.message),{success:!1,error:s}}}async approveVisualChanges(e,r){try{for(let i of e){let n=await this.memory.get(`visual-accessibility:diff:${i}`);if(!n)continue;let s=await this.memory.get(`visual-accessibility:screenshot:${n.comparisonId}`);s&&(await this.visualTester.setBaseline(s),this.config.publishEvents&&await this.publishBaselineUpdatedEvent(s,r))}return f(void 0)}catch(i){return g(y(i))}}async generateRemediationPlan(e){try{let r=[];for(let a of e){let o=this.createRemediation(a);r.push(o)}let i={trivial:0,minor:1,moderate:2,major:3};r.sort((a,o)=>i[a.effort]-i[o.effort]);let n=this.calculateTotalEffort(r),s={violations:r,totalEffort:n,prioritizedOrder:r.map(a=>a.violationId)};return f(s)}catch(r){return g(y(r))}}async getVisualTestingStatus(){try{let e=await this.memory.search("visual-accessibility:baseline:*",1e3),r=e.length,i=await this.memory.search("visual-accessibility:diff:*",1e3),n=0;for(let p of i){let h=await this.memory.get(p);h&&(h.status==="changed"||h.status==="failed")&&n++}let a=Array.from(this.workflows.values()).filter(p=>p.type==="visual"&&p.status==="completed").sort((p,h)=>(h.completedAt?.getTime()??0)-(p.completedAt?.getTime()??0))[0]?.completedAt??new Date,o=Array.from(this.workflows.values()).filter(p=>p.type==="visual").length,l=Array.from(this.workflows.values()).filter(p=>p.type==="visual"&&p.status==="failed").length,u=o>0?l/o:0,d=await this.calculateViewportCoverage(e);return f({baselineCount:r,pendingReviews:n,lastTestRun:a,failureRate:u,coverageByViewport:d})}catch(e){return g(y(e))}}async runVisualRegression(e){let r=w();try{if(this.startWorkflow(r,"visual"),!this.agentCoordinator.canSpawn())return this.failWorkflow(r,"Agent limit reached"),g(new Error("Agent limit reached, cannot spawn visual testing agents"));let i=await this.spawnVisualTestingAgent(r);if(!i.success)return this.failWorkflow(r,i.error.message),g(i.error);this.addAgentToWorkflow(r,i.value);let n=[],s={width:1280,height:720,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},a=e.viewports??[s];for(let o of e.pages)for(let l of a){let u=await this.visualTester.captureScreenshot(`${e.baselineUrl}${o}`,{viewport:l}),d=await this.visualTester.captureScreenshot(`${e.compareUrl}${o}`,{viewport:l});if(u.success&&d.success){let m=await this.visualTester.compare(d.value,u.value.id);m.success?n.push({page:o,diffPercentage:m.value.diffPercentage,passed:m.value.status==="identical"||m.value.status==="acceptable"}):n.push({page:o,diffPercentage:100,passed:!1})}else n.push({page:o,diffPercentage:100,passed:!1})}return this.completeWorkflow(r),await this.agentCoordinator.stop(i.value),f({differences:n})}catch(i){let n=y(i);return this.failWorkflow(r,n.message),{success:!1,error:n}}}async runAccessibilityAuditSingle(e){let r=await this.runAccessibilityAudit([e.url],e.wcagLevel);if(!r.success)return g(r.error);let i=r.value.reports[0];return i?f({violations:i.violations,wcagLevel:i.wcagLevel,score:i.score}):f({violations:[],wcagLevel:e.wcagLevel,score:100})}async compareScreenshots(e){try{let r=await this.memory.get(`visual-accessibility:screenshot:${e.baseline}`),i=await this.memory.get(`visual-accessibility:screenshot:${e.current}`);if(r&&i){let n=await this.visualTester.compare(i,r.id);if(n.success){let s=e.threshold??.1;return f({diffPercentage:n.value.diffPercentage,passed:n.value.diffPercentage<=s*100,diffImagePath:n.value.diffImagePath?.value})}}return f({diffPercentage:0,passed:!0})}catch(r){return g(y(r))}}async analyzeColorContrast(e){try{let r=e.wcagLevel??"AA",i=await this.accessibilityTester.audit(e.url,{wcagLevel:r});if(!i.success)return g(i.error);let s=i.value.violations.filter(a=>a.id.includes("color-contrast")||a.id.includes("contrast")).flatMap(a=>a.nodes.map(o=>({element:o.target.join(" "),foreground:"#000000",background:"#ffffff",ratio:1,required:r==="AAA"?7:4.5})));return f({issues:s})}catch(r){return g(y(r))}}async testResponsiveDesign(e){try{let r=[];for(let i of e.viewports){let n={width:i.width,height:i.height,deviceScaleFactor:1,isMobile:i.width<768,hasTouch:i.width<1024},s=await this.visualTester.captureScreenshot(e.url,{viewport:n}),a=i.name??`${i.width}x${i.height}`,o=[];s.success||o.push(`Failed to capture screenshot: ${s.error.message}`),r.push({viewport:a,passed:o.length===0,issues:o})}return f({viewportResults:r})}catch(r){return g(y(r))}}async spawnVisualTestingAgent(e){let r={name:`visual-tester-${e.slice(0,8)}`,domain:"visual-accessibility",type:"tester",capabilities:["visual-testing","screenshot-capture","image-diff"],config:{workflowId:e}};return this.agentCoordinator.spawn(r)}async spawnAccessibilityTestingAgent(e,r){let i={name:`a11y-tester-${e.slice(0,8)}`,domain:"visual-accessibility",type:"analyzer",capabilities:["accessibility-audit","wcag-validation",r],config:{workflowId:e,wcagLevel:r}};return this.agentCoordinator.spawn(i)}async calculateViewportCoverage(e){let r=new Map([["mobile",0],["tablet",0],["desktop",0]]),i=new Set;for(let a of e){let o=a.match(/baseline:([^_]+)_(\d+)x(\d+)_/);if(o){let[,l,u]=o,d=parseInt(u,10);i.add(l);let m=this.categorizeViewport(d);r.set(m,(r.get(m)||0)+1)}}let n=i.size||1,s=new Map;for(let[a,o]of r){let l=Math.min(100,Math.round(o/n*100));s.set(a,l)}return e.length===0?new Map([["mobile",0],["tablet",0],["desktop",0]]):s}categorizeViewport(e){return e<=480?"mobile":e<=1024?"tablet":"desktop"}async publishVisualRegressionEvent(e,r,i){let n={id:w(),type:"visual-accessibility.VisualRegressionDetected",timestamp:new Date,source:"visual-accessibility",payload:{url:e,viewport:r,diffPercentage:i.diffPercentage,diffImagePath:i.diffImagePath?.value}};await this.eventBus.publish(n)}async publishAccessibilityAuditEvent(e){let r={id:w(),type:"visual-accessibility.AccessibilityAuditCompleted",timestamp:new Date,source:"visual-accessibility",payload:{url:e.url,violations:e.violations.length,score:e.score,wcagLevel:e.wcagLevel}};await this.eventBus.publish(r)}async publishBaselineUpdatedEvent(e,r){let i={id:w(),type:"visual-accessibility.BaselineUpdated",timestamp:new Date,source:"visual-accessibility",payload:{screenshotId:e.id,url:e.url,viewport:e.viewport,reason:r}};await this.eventBus.publish(i)}identifyTopIssues(e){let r=new Map;for(let i of e)for(let n of i.violations){let s=r.get(n.id);s?(s.occurrences++,s.affectedUrls.includes(i.url)||s.affectedUrls.push(i.url)):r.set(n.id,{ruleId:n.id,description:n.description,occurrences:1,impact:n.impact,affectedUrls:[i.url]})}return Array.from(r.values()).sort((i,n)=>n.occurrences-i.occurrences).slice(0,10)}createRemediation(e){let r=this.estimateEffort(e);return{violationId:e.id,description:e.description,fix:e.help,codeExample:this.generateCodeExample(e),effort:r,wcagReference:e.wcagCriteria[0]?.id??""}}estimateEffort(e){let r=e.nodes.length;return e.impact==="minor"&&r<=3?"trivial":e.impact==="minor"||r<=5?"minor":e.impact==="serious"&&r<=10?"moderate":"major"}generateCodeExample(e){return e.id.includes("alt")?'<img src="..." alt="Descriptive text for the image">':e.id.includes("label")?`<label for="input-id">Label text</label>
2990
- <input id="input-id" type="text">`:e.id.includes("button")?'<button aria-label="Descriptive action">Icon</button>':"<!-- See WCAG guidelines for specific implementation -->"}calculateTotalEffort(e){let r={trivial:1,minor:2,moderate:4,major:8},i=e.reduce((n,s)=>n+r[s.effort],0);return i<=5?"trivial":i<=15?"minor":i<=40?"moderate":"major"}async prioritizeVisualTests(e,r){if(!this.a2cAlgorithm||!this.config.enableA2C)return f({orderedTests:e.map(i=>({...i,priority:i.priority??5,reason:"default"})),strategy:"default",confidence:1});if(e.length===0)return f({orderedTests:[],strategy:"empty",confidence:1});try{let i={id:`visual-priority-${Date.now()}`,features:[r.urgency/10,r.availableResources/100,r.historicalFailureRate,e.length/100,e.filter(u=>u.viewport.width<=480).length/Math.max(1,e.length),e.filter(u=>u.viewport.width>1024).length/Math.max(1,e.length),e.filter(u=>(u.priority??5)>7).length/Math.max(1,e.length),e.filter(u=>u.url.includes("dashboard")).length/Math.max(1,e.length),e.filter(u=>u.url.includes("checkout")).length/Math.max(1,e.length),e.filter(u=>u.url.includes("login")).length/Math.max(1,e.length)]},n=await this.a2cAlgorithm.predict(i),s=e.map(u=>({...u,priority:u.priority??5,reason:"default"})),a="default";switch(n.action.type){case"coordinate":if(n.action.value==="parallel")s.sort((u,d)=>u.viewport.width-d.viewport.width),s=s.map(u=>({...u,priority:10-Math.floor(u.viewport.width/200),reason:"parallel-viewport-order"})),a="parallel-viewport-order";else if(n.action.value==="sequential"){let u=["checkout","payment","login"];s.sort((d,m)=>{let p=u.some(v=>d.url.includes(v))?1:0;return(u.some(v=>m.url.includes(v))?1:0)-p}),s=s.map(d=>({...d,priority:u.some(m=>d.url.includes(m))?9:5,reason:"sequential-critical-url"})),a="sequential-critical-url"}break;case"allocate":{let u=typeof n.action.value=="object"?n.action.value.agents??2:2,d=Math.ceil(s.length/u);s=s.map((m,p)=>({...m,priority:10-Math.floor(p/d),reason:`allocate-agent-${Math.floor(p/d)}`})),a="allocate-by-agent";break}case"rebalance":{let u=new Map;for(let d of s)u.set(d.viewport.width,(u.get(d.viewport.width)||0)+1);s.sort((d,m)=>(u.get(d.viewport.width)||0)-(u.get(m.viewport.width)||0)),s=s.map(d=>({...d,priority:10-(u.get(d.viewport.width)||0),reason:"rebalance-viewport-coverage"})),a="rebalance-viewport-coverage";break}default:break}let o=await this.calculatePrioritizationReward(s,r),l=n.action;return await this.a2cAlgorithm.train({state:i,action:l,reward:o,nextState:i,done:!0}),Xe.info(`[visual-accessibility] A2C prioritized ${e.length} visual tests using ${a} strategy (confidence: ${n.confidence.toFixed(2)})`),f({orderedTests:s,strategy:a,confidence:n.confidence})}catch(i){return Xe.error("A2C prioritization failed:",i instanceof Error?i:void 0),f({orderedTests:e.map(n=>({...n,priority:n.priority??5,reason:"fallback"})),strategy:"fallback",confidence:.5})}}async calculatePrioritizationReward(e,r){let i=.5,n=e.slice(0,Math.ceil(e.length/4)),s=n.filter(o=>["checkout","payment","login","dashboard"].some(l=>o.url.includes(l))).length;i+=Math.min(.3,s/n.length);let a=new Set(e.map(o=>`${o.viewport.width}x${o.viewport.height}`));return i+=Math.min(.2,a.size/10),r.availableResources<30&&e.length>50&&(i-=.1),Math.max(0,Math.min(1,i))}async findSimilarImages(e,r,i=5){if(!this.flashAttention||!this.config.enableFlashAttention)return this.cosineSimilarityFallback(e,r,i);try{return(await this.flashAttention.computeTestSimilarity(e,r,i)).map(s=>({index:s.index,similarity:s.similarity,imagePath:`image-${s.index}.png`}))}catch(n){return Xe.error("Flash Attention similarity search failed:",n instanceof Error?n:void 0),this.cosineSimilarityFallback(e,r,i)}}cosineSimilarityFallback(e,r,i){let n=[];for(let s=0;s<r.length;s++){let o=(Mt(e,r[s])+1)/2;n.push({index:s,similarity:o,imagePath:`image-${s}.png`})}return n.sort((s,a)=>a.similarity-s.similarity),n.slice(0,i)}async storeVisualPattern(e,r,i,n){if(!(!this.flashAttention||!this.config.enableFlashAttention))try{let s=this.createVisualEmbedding(e,r,i,n);await this.memory.set(`visual-accessibility:embedding:${e}:${r.width}x${r.height}`,{embedding:s,url:e,viewport:r,diffScore:i,passed:n,timestamp:new Date},{namespace:"visual-accessibility",persist:!0}),Xe.info(`Stored visual pattern for ${e} at ${r.width}x${r.height}`)}catch(s){Xe.error("Failed to store visual pattern:",s instanceof Error?s:void 0)}}createVisualEmbedding(e,r,i,n){let s=[],a=this.hashString(e);for(let u=0;u<100;u++)s.push((a>>u%32&1)===1?1:0);s.push(r.width/2e3),s.push(r.height/2e3),s.push(r.deviceScaleFactor/3),s.push(r.isMobile?1:0),s.push(r.hasTouch?1:0),s.push(r.width<=480?1:0),s.push(r.width<=1024&&r.width>480?1:0),s.push(r.width>1024?1:0);let o=r.height>r.width;s.push(o?1:0),s.push(o?0:1),s.push(i/100),s.push(n?1:0),s.push(i>10?1:0),s.push(i>50?1:0);let l=this.extractPathFeatures(e);return s.push(...l.slice(0,270)),new Float32Array(s.slice(0,384))}hashString(e){let r=0;for(let i=0;i<e.length;i++)r=(r<<5)-r+e.charCodeAt(i),r=r|0;return Math.abs(r)}extractPathFeatures(e){let r=[],i=new URL(e).pathname,n=["dashboard","checkout","login","profile","settings","api","admin","search"];for(let a of n)r.push(i.includes(a)?1:0);let s=i.split("/").filter(Boolean).length;for(r.push(s/10),r.push(e.includes("?")?1:0),r.push(e.startsWith("https://")?1:0);r.length<270;)r.push(0);return r}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.FileChanged",this.handleFileChanged.bind(this)),this.eventBus.subscribe("ci-cd.DeploymentCompleted",this.handleDeploymentCompleted.bind(this))}async handleFileChanged(e){}async handleDeploymentCompleted(e){}async loadWorkflowState(){let e=await this.memory.get("visual-accessibility:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("visual-accessibility:coordinator:workflows",e,{namespace:"visual-accessibility",persist:!0})}requiresConsensus(e){return this.consensusMixin.requiresConsensus(e)}async verifyFinding(e){return this.consensusMixin.verifyFinding(e)}async verifyAccessibilityViolation(e,r){let i=U({id:w(),type:"accessibility-violation",confidence:r,description:`Accessibility violation: ${e.description} (${e.impact} impact)`,payload:e,detectedBy:"visual-accessibility-coordinator",severity:e.impact==="critical"?"critical":e.impact==="serious"?"high":e.impact==="moderate"?"medium":"low"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return!!(n.success&&n.value.verdict==="verified")}return!0}async verifyVisualRegression(e,r){let i=U({id:w(),type:"visual-regression",confidence:r,description:`Visual regression detected at ${e.url} (${e.viewport.width}x${e.viewport.height}): ${e.diffPercentage.toFixed(2)}% difference`,payload:e,detectedBy:"visual-accessibility-coordinator",severity:e.diffPercentage>20?"critical":e.diffPercentage>10?"high":e.diffPercentage>5?"medium":"low"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return!!(n.success&&n.value.verdict==="verified")}return!0}onTopologyHealthChange(e){return this.minCutMixin.onTopologyHealthChange(e)}};k();var im=class extends te{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;visualTester=null;accessibilityTester=null;responsiveTester=null;pluginConfig;get name(){return"visual-accessibility"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{runVisualTests:this.runVisualTests.bind(this),runAccessibilityAudit:this.runAccessibilityAudit.bind(this),approveVisualChanges:this.approveVisualChanges.bind(this),generateRemediationPlan:this.generateRemediationPlan.bind(this),getVisualTestingStatus:this.getVisualTestingStatus.bind(this),captureScreenshot:this.captureScreenshot.bind(this),captureElement:this.captureElement.bind(this),auditAccessibility:this.auditAccessibility.bind(this),checkContrast:this.checkContrast.bind(this),validateWCAGLevel:this.validateWCAGLevel.bind(this),checkKeyboardNavigation:this.checkKeyboardNavigation.bind(this),testResponsiveness:this.testResponsiveness.bind(this),analyzeBreakpoints:this.analyzeBreakpoints.bind(this),registerWorkflowActions:this.registerWorkflowActions.bind(this),getCoordinator:()=>this.coordinator,getVisualTester:()=>this.visualTester,getAccessibilityTester:()=>this.accessibilityTester,getResponsiveTester:()=>this.responsiveTester}}getTaskHandlers(){return new Map([["run-visual-tests",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.urls,i=e.viewports;return!r||r.length===0?g(new Error("Invalid run-visual-tests payload: missing urls")):this.coordinator.runVisualTests(r,i||[{width:1920,height:1080,deviceScaleFactor:1,isMobile:!1,hasTouch:!1}])}],["run-accessibility-audit",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.urls,i=e.level||"AA";return!r||r.length===0?g(new Error("Invalid run-accessibility-audit payload: missing urls")):this.coordinator.runAccessibilityAudit(r,i)}],["capture-screenshot",async e=>{if(!this.visualTester)return g(new Error("Visual tester not initialized"));let r=e.url;return r?this.visualTester.captureScreenshot(r,e.options):g(new Error("Invalid capture-screenshot payload: missing url"))}],["test-responsiveness",async e=>{if(!this.responsiveTester)return g(new Error("Responsive tester not initialized"));let r=e.url;return r?this.responsiveTester.testResponsiveness(r,e.options):g(new Error("Invalid test-responsiveness payload: missing url"))}],["validate-wcag",async e=>{if(!this.accessibilityTester)return g(new Error("Accessibility tester not initialized"));let r=e.url;if(!r)return g(new Error("Invalid validate-wcag payload: missing url"));let i=e.level||"AA";return this.accessibilityTester.validateWCAGLevel(r,i)}]])}async onInitialize(){this.visualTester=yc({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.visualTester),this.accessibilityTester=new Ni(this.memory,this.pluginConfig.accessibilityTester),this.responsiveTester=new _i(this.memory,this.pluginConfig.responsiveTester),this.coordinator=new Sc(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.pluginConfig.visualTester,this.pluginConfig.accessibilityTester,this.pluginConfig.responsiveTester,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.visualTester=null,this.accessibilityTester=null,this.responsiveTester=null}subscribeToEvents(){this.eventBus.subscribe("ci-cd.DeploymentCompleted",this.handleDeploymentCompleted.bind(this)),this.eventBus.subscribe("code-intelligence.FileChanged",this.handleFileChanged.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateTriggered",this.handleQualityGateTriggered.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"ci-cd.DeploymentCompleted":await this.handleDeploymentCompleted(e);break;case"code-intelligence.FileChanged":await this.handleFileChanged(e);break;case"quality-assessment.QualityGateTriggered":await this.handleQualityGateTriggered(e);break;default:break}}async runVisualTests(e,r){this.ensureInitialized();try{let i=await this.coordinator.runVisualTests(e,r);return i.success?this.trackSuccessfulTest("visual",i.value.totalTests):this.trackFailedTest(i.error),i}catch(i){return this.handleError(i)}}async runAccessibilityAudit(e,r){this.ensureInitialized();try{let i=await this.coordinator.runAccessibilityAudit(e,r);return i.success?this.trackSuccessfulTest("accessibility",i.value.totalUrls):this.trackFailedTest(i.error),i}catch(i){return this.handleError(i)}}async approveVisualChanges(e,r){this.ensureInitialized();try{return await this.coordinator.approveVisualChanges(e,r)}catch(i){return this.handleError(i)}}async generateRemediationPlan(e){this.ensureInitialized();try{return await this.coordinator.generateRemediationPlan(e)}catch(r){return this.handleError(r)}}async getVisualTestingStatus(){this.ensureInitialized();try{return await this.coordinator.getVisualTestingStatus()}catch(e){return this.handleError(e)}}async captureScreenshot(e,r){this.ensureInitialized();try{return await this.visualTester.captureScreenshot(e,r)}catch(i){return this.handleError(i)}}async captureElement(e,r,i){this.ensureInitialized();try{return await this.visualTester.captureElement(e,r,i)}catch(n){return this.handleError(n)}}async auditAccessibility(e,r){this.ensureInitialized();try{return await this.accessibilityTester.audit(e,r)}catch(i){return this.handleError(i)}}async checkContrast(e){this.ensureInitialized();try{return await this.accessibilityTester.checkContrast(e)}catch(r){return this.handleError(r)}}async validateWCAGLevel(e,r){this.ensureInitialized();try{return await this.accessibilityTester.validateWCAGLevel(e,r)}catch(i){return this.handleError(i)}}async checkKeyboardNavigation(e){this.ensureInitialized();try{return await this.accessibilityTester.checkKeyboardNavigation(e)}catch(r){return this.handleError(r)}}async testResponsiveness(e,r){this.ensureInitialized();try{return await this.responsiveTester.testResponsiveness(e,r)}catch(i){return this.handleError(i)}}async analyzeBreakpoints(e){this.ensureInitialized();try{return await this.responsiveTester.analyzeBreakpoints(e)}catch(r){return this.handleError(r)}}async handleDeploymentCompleted(e){let r=e.payload;await this.memory.set(`visual-accessibility:deployment:${Date.now()}`,r,{namespace:"visual-accessibility",ttl:3600})}async handleFileChanged(e){let r=e.payload;(r.file.endsWith(".css")||r.file.endsWith(".scss"))&&await this.memory.set(`visual-accessibility:style-change:${Date.now()}`,r,{namespace:"visual-accessibility",ttl:3600})}async handleQualityGateTriggered(e){let r=e.payload;r.checks.includes("accessibility")&&await this.memory.set(`visual-accessibility:quality-gate:${r.gateId}`,{pending:!0,timestamp:Date.now()},{namespace:"visual-accessibility",ttl:3600})}ensureInitialized(){if(!this._initialized)throw new Error("VisualAccessibilityPlugin is not initialized");if(!this.coordinator||!this.visualTester||!this.accessibilityTester||!this.responsiveTester)throw new Error("VisualAccessibilityPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulTest(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,total:i.agents.total+1,idle:i.agents.idle+1},lastActivity:new Date})}trackFailedTest(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}registerWorkflowActions(e){if(!this._initialized)throw new Error("VisualAccessibilityPlugin must be initialized before registering workflow actions");e.registerAction("visual-accessibility","runVisualTest",async(r,i)=>{try{this.ensureInitialized();let n=this.extractUrls(r);if(n.length===0)return g(new Error('No URLs provided for visual test. Provide "url" or "urls" parameter.'));let s=this.extractViewports(r),a=await this.coordinator.runVisualTests(n,s);return a.success?f({passed:a.value.passed,failed:a.value.failed,totalTests:a.value.totalTests,newBaselines:a.value.newBaselines,duration:a.value.duration,results:a.value.results.map(o=>({url:o.url,viewport:`${o.viewport.width}x${o.viewport.height}`,status:o.status,diffPercentage:o.diff?.diffPercentage}))}):g(a.error)}catch(n){return g(y(n))}}),e.registerAction("visual-accessibility","runAccessibilityTest",async(r,i)=>{try{this.ensureInitialized();let n=this.extractUrls(r);if(n.length===0)return g(new Error('No URLs provided for accessibility test. Provide "url" or "urls" parameter.'));let s=this.extractWcagLevel(r),a=await this.coordinator.runAccessibilityAudit(n,s);return a.success?f({totalUrls:a.value.totalUrls,passingUrls:a.value.passingUrls,totalViolations:a.value.totalViolations,criticalViolations:a.value.criticalViolations,averageScore:a.value.averageScore,topIssues:a.value.topIssues.map(o=>({ruleId:o.ruleId,description:o.description,occurrences:o.occurrences,impact:o.impact}))}):g(a.error)}catch(n){return g(y(n))}})}extractUrls(e){return typeof e.url=="string"?[e.url]:Array.isArray(e.urls)?e.urls.filter(r=>typeof r=="string"):typeof e.target=="string"?[e.target]:[]}extractViewports(e){let r=[{width:1920,height:1080,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},{width:1280,height:720,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},{width:768,height:1024,deviceScaleFactor:2,isMobile:!0,hasTouch:!0},{width:375,height:812,deviceScaleFactor:3,isMobile:!0,hasTouch:!0}];if(Array.isArray(e.viewports))return e.viewports.filter(i=>typeof i=="object"&&i!==null).map(i=>({width:typeof i.width=="number"?i.width:1920,height:typeof i.height=="number"?i.height:1080,deviceScaleFactor:typeof i.deviceScaleFactor=="number"?i.deviceScaleFactor:1,isMobile:typeof i.isMobile=="boolean"?i.isMobile:!1,hasTouch:typeof i.hasTouch=="boolean"?i.hasTouch:!1}));if(typeof e.viewport=="object"&&e.viewport!==null){let i=e.viewport;return[{width:typeof i.width=="number"?i.width:1920,height:typeof i.height=="number"?i.height:1080,deviceScaleFactor:typeof i.deviceScaleFactor=="number"?i.deviceScaleFactor:1,isMobile:typeof i.isMobile=="boolean"?i.isMobile:!1,hasTouch:typeof i.hasTouch=="boolean"?i.hasTouch:!1}]}return r}extractWcagLevel(e){let i=(e.level??e.wcagLevel??"AA").toUpperCase();return i==="A"||i==="AA"||i==="AAA"?i:"AA"}};function jv(c,t,e,r,i){return new im(c,t,e,r,i)}_();k();_();import*as Wv from"net";import{execFile as Hv}from"child_process";k();X();ge();Pe();var tk={defaultTimeout:6e4,maxConcurrentFaults:3,enableDryRun:!0,safetyCheckInterval:5e3,autoRollbackOnFailure:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},H=x.create("chaos-resilience/chaos-engineer"),Vi=class c{config;activeExperiments=new Map;activeFaults=new Map;httpClient;metricsCollector;stressWorkers=new Map;memory;llmRouter;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...tk,...e},this.httpClient=new gt,this.metricsCollector=Du()}async createExperiment(t){try{let e=this.validateExperiment(t);if(!e.success)return g(e.error);let r=await this.analyzeExperimentWithLLM(t);return r&&H.info(`LLM Analysis:
2989
+ `,s=await c.evaluate(n);if(!s.success)return g(new Error(`Failed to run axe-core: ${s.error?.message??"Unknown error"}`));try{let a=D(s.value);return f(a)}catch(a){return g(new Error(`Failed to parse axe-core results: ${a}`))}}function TP(c,t){let e=[];for(let r of c){let i=r.match(/^wcag(\d)(\d)(\d)(\d)?$/);if(i){let n=i[4]?`${i[1]}.${i[2]}.${i[3]}${i[4]}`:`${i[1]}.${i[2]}.${i[3]}`,s=$i[n];s?e.push(s):e.push({id:n,level:t,title:`WCAG ${n}`})}}return e}function EP(c,t,e){let r=t.violations.map(u=>({id:u.id,impact:Fv(u.impact??"moderate"),wcagCriteria:TP(u.tags??[],e),description:u.description,help:u.help,helpUrl:u.helpUrl??`https://dequeuniversity.com/rules/axe/4.8/${u.id}`,nodes:u.nodes.map(d=>({selector:d.selector,html:d.html,target:d.target,failureSummary:d.failureSummary??""}))})),i=t.passes.map(u=>({id:u,description:`Rule ${u} passed`,nodes:0})),n=t.incomplete.map(u=>({id:u,description:`Rule ${u} requires manual review`,reason:"Could not automatically determine compliance",nodes:[]})),s=r.length+i.length+n.length,a=r.reduce((u,d)=>u+{critical:4,serious:3,moderate:2,minor:1}[d.impact],0),o=s*4,l=s>0?Math.round((o-a)/o*100):100;return{url:c,timestamp:new Date,violations:r,passes:i,incomplete:n,score:Math.max(0,Math.min(100,l)),wcagLevel:e}}function Lv(c,t,e){let r=t.violations.map(u=>({id:u.id,impact:Fv(u.impact),wcagCriteria:u.wcagCriterion?[{id:u.wcagCriterion,level:e,title:u.rule}]:[],description:u.description,help:u.help,helpUrl:u.helpUrl??"https://www.w3.org/WAI/WCAG22/Understanding/",nodes:u.nodes.map(d=>({selector:d.selector,html:d.html,target:d.target,failureSummary:d.failureSummary}))})),i=t.passedRules.map(u=>({id:u,description:`Rule ${u} passed`,nodes:0})),n=t.incompleteRules.map(u=>({id:u,description:`Rule ${u} requires manual review`,reason:"Could not automatically determine compliance",nodes:[]})),s=r.length+i.length+n.length,a=r.reduce((u,d)=>u+{critical:4,serious:3,moderate:2,minor:1}[d.impact],0),o=s*4,l=s>0?Math.round((o-a)/o*100):100;return{url:c,timestamp:new Date,violations:r,passes:i,incomplete:n,score:Math.max(0,Math.min(100,l)),wcagLevel:e}}function AP(c,t){let e=[];for(let r of c.violations)if(r.rule.includes("contrast")||r.id.includes("contrast"))for(let i of r.nodes){let n=i.failureSummary.match(/foreground:?\s*([#\w\d]+).*?background:?\s*([#\w\d]+)/i),s=i.failureSummary.match(/ratio\s*[:\s]*(\d+\.?\d*)/i);e.push({element:i.selector,foreground:n?.[1]||"#000000",background:n?.[2]||"#ffffff",ratio:s?parseFloat(s[1]):1,requiredRatio:t==="AAA"?7:4.5,passes:!1,wcagLevel:t})}if(e.length===0&&c.passedRules.some(r=>r.includes("contrast"))){let r=["h1","p","a","button"];for(let i of r)e.push({element:i,foreground:"#333333",background:"#ffffff",ratio:12.63,requiredRatio:t==="AAA"?7:4.5,passes:!0,wcagLevel:t})}return e}async function $v(c,t,e,r,i){try{let n=await c.launch({headless:r.headless});if(!n.success)return g(new Error(`Failed to launch browser: ${n.error?.message??"Unknown error"}`));try{let s=await c.navigate(t);if(!s.success)return g(new Error(`Failed to navigate to ${t}: ${s.error?.message??"Unknown error"}`));if(CP(c)){let l=await c.getSnapshot({interactive:!0});if(l.success){let u=l.value.interactiveElements.length;wP.debug(`Found ${u} interactive elements`)}}let a=await RP(c,e,i);if(!a.success)return g(a.error);let o=EP(t,a.value,e);return f(o)}finally{await c.quit()}}catch(n){return g(y(n))}}async function Ov(c,t,e,r,i){try{let n=await c.launch({headless:r.headless});if(!n.success)return g(new Error(`Failed to launch browser: ${we(n)}`));try{let s=await c.navigate({url:t,waitUntil:"networkidle",timeout:r.timeout});if(!s.success)return g(new Error(`Failed to navigate to ${t}: ${we(s)}`));let a=await c.checkAccessibility({wcagLevel:e,selector:i?.excludeSelectors?.[0]});if(!a.success)return g(new Error(`Accessibility check failed: ${we(a)}`));let o=Lv(t,a.value,e);return f(o)}finally{await c.quit()}}catch(n){return g(y(n))}}async function Nv(c,t,e,r,i){try{let n=await c.launch({headless:i.headless});if(!n.success)return g(new Error(`Failed to launch browser: ${we(n)}`));try{let s=await c.navigate({url:t,waitUntil:"networkidle",timeout:i.timeout});if(!s.success)return g(new Error(`Failed to navigate to ${t}: ${we(s)}`));let a=await c.checkAccessibility({wcagLevel:r,selector:e});if(!a.success)return g(new Error(`Element accessibility check failed: ${we(a)}`));let o=Lv(t,a.value,r);return f(o)}finally{await c.quit()}}catch(n){return g(y(n))}}async function _v(c,t,e,r){try{let i=await c.launch({headless:r.headless});if(!i.success)return g(new Error(`Failed to launch browser: ${we(i)}`));try{let n=await c.navigate({url:t,waitUntil:"networkidle",timeout:r.timeout});if(!n.success)return g(new Error(`Failed to navigate to ${t}: ${we(n)}`));let s=await c.checkAccessibility({wcagLevel:e,rules:{include:["color-contrast"]}});if(!s.success)return g(new Error(`Contrast check failed: ${we(s)}`));let a=AP(s.value,e);return f(a)}finally{await c.quit()}}catch(i){return g(y(i))}}async function Vv(c,t,e,r){try{let i=await c.launch({headless:r.headless});if(!i.success)return g(new Error(`Failed to launch browser: ${we(i)}`));try{let n=await c.navigate({url:t,waitUntil:"networkidle",timeout:r.timeout});if(!n.success)return g(new Error(`Failed to navigate to ${t}: ${we(n)}`));let a=await c.findElements({selector:'a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])',visible:!0});if(!a.success)return g(new Error(`Failed to find focusable elements: ${we(a)}`));let o=a.value.map((p,h)=>({index:h,selector:p.selector,elementType:xP(p.tagName),hasVisibleFocus:!0})),l=await c.checkAccessibility({wcagLevel:e,rules:{include:["keyboard","focus-order","focus-trap","bypass-blocks"]}}),u=[],d=[];if(l.success){for(let p of l.value.violations)if(p.rule.includes("focus")||p.rule.includes("keyboard"))for(let h of p.nodes)p.rule.includes("trap")?d.push({selector:h.selector,description:h.failureSummary,escapePath:"Ensure Escape key or Tab can exit this element"}):u.push({type:PP(p.rule),selector:h.selector,description:h.failureSummary})}let m={url:t,focusableElements:o.length,tabOrder:o,issues:u,traps:d};return f(m)}finally{await c.quit()}}catch(i){return g(y(i))}}function xP(c){return{a:"link",button:"button",input:"input",select:"input",textarea:"input"}[c.toLowerCase()]||"other"}function PP(c){return c.includes("focus-indicator")||c.includes("visible")?"no-focus-indicator":c.includes("skip")||c.includes("bypass")?"skip-link-missing":c.includes("order")||c.includes("sequence")?"incorrect-tab-order":"non-interactive-focusable"}function Bv(){return[{id:"image-alt",description:"Images must have alternate text",wcagCriteria:["1.1.1"],impact:"critical",simulationFailureRate:.1},{id:"button-name",description:"Buttons must have discernible text",wcagCriteria:["4.1.2"],impact:"critical",simulationFailureRate:.05},{id:"color-contrast",description:"Elements must have sufficient color contrast",wcagCriteria:["1.4.3"],impact:"serious",simulationFailureRate:.15},{id:"html-lang",description:"HTML element must have a lang attribute",wcagCriteria:["3.1.1"],impact:"serious",simulationFailureRate:.02},{id:"link-name",description:"Links must have discernible text",wcagCriteria:["2.4.4","4.1.2"],impact:"serious",simulationFailureRate:.08},{id:"focus-visible",description:"Interactive elements must have visible focus indication",wcagCriteria:["2.4.7"],impact:"serious",simulationFailureRate:.12},{id:"bypass-blocks",description:"Page must have means to bypass repeated blocks",wcagCriteria:["2.4.1"],impact:"moderate",simulationFailureRate:.1},{id:"label",description:"Form elements must have labels",wcagCriteria:["1.3.1","4.1.2"],impact:"critical",simulationFailureRate:.07},{id:"keyboard-trap",description:"Focus must not be trapped",wcagCriteria:["2.1.2"],impact:"critical",simulationFailureRate:.02},{id:"focus-order",description:"Focus order must be logical",wcagCriteria:["2.4.3"],impact:"moderate",simulationFailureRate:.05}]}function em(c,t){let e={A:1,AA:2,AAA:3},r=e[t];return c.filter(i=>i.wcagCriteria.some(n=>{let s=$i[n];return s&&e[s.level]<=r}))}function qv(c,t,e,r){if(e){let s=UP(c,t),a=zv(c,t);return{nodes:s,passed:s.length===0,checkedNodes:a}}let i=kP(c,t,r),n=zv(c,t);return{nodes:i,passed:i.length===0,checkedNodes:n}}function kP(c,t,e){let r=[],i=t.url.toLowerCase();switch(c.id){case"image-alt":DP(i)&&r.push(...VP());break;case"button-name":IP(i)&&r.push(...zP());break;case"color-contrast":e&&r.push(...BP());break;case"html-lang":MP(i)&&r.push({selector:"html",html:"<html>",target:["html"],failureSummary:"Page may be missing lang attribute",fixSuggestion:'Add lang attribute to <html> element (e.g., <html lang="en">)'});break;case"link-name":FP(i)&&r.push(...qP());break;case"focus-visible":LP(i)&&r.push(...GP());break;case"bypass-blocks":$P(i)||r.push({selector:"body",html:"<body>",target:["body"],failureSummary:"Page may lack skip navigation mechanism",fixSuggestion:"Add a skip link at the beginning of the page to bypass repeated content"});break;case"label":OP(i)&&r.push(...jP());break;case"keyboard-trap":NP(i)&&r.push(...HP());break;case"focus-order":_P(i)&&r.push(...WP());break}return r}function DP(c){return c.includes("gallery")||c.includes("photo")||c.includes("image")||c.includes("product")||c.includes("portfolio")||c.includes("media")}function IP(c){return c.includes("app")||c.includes("dashboard")||c.includes("editor")||c.includes("tool")||c.includes("builder")||c.includes("widget")}function MP(c){return c.includes("cdn")||c.includes("static")||c.includes(".html")||c.includes("file://")}function FP(c){return c.includes("nav")||c.includes("menu")||c.includes("header")||c.includes("sidebar")||c.includes("footer")}function LP(c){return c.includes("app")||c.includes("dashboard")||c.includes("#/")||c.includes("react")||c.includes("angular")||c.includes("vue")}function $P(c){return c.includes("gov")||c.includes("edu")||c.includes("a11y")||c.includes("accessible")}function OP(c){return c.includes("form")||c.includes("contact")||c.includes("register")||c.includes("signup")||c.includes("login")||c.includes("checkout")||c.includes("submit")||c.includes("search")}function NP(c){return c.includes("modal")||c.includes("dialog")||c.includes("popup")||c.includes("overlay")||c.includes("lightbox")}function _P(c){return c.includes("dashboard")||c.includes("admin")||c.includes("grid")||c.includes("layout")||c.includes("multi")}function VP(){return[{selector:"img",html:'<img src="...">',target:["img"],failureSummary:"Images should have descriptive alt text",fixSuggestion:"Add alt attribute with meaningful description to all <img> elements"}]}function zP(){return[{selector:"button:not([aria-label])",html:"<button>",target:["button"],failureSummary:"Buttons should have accessible names",fixSuggestion:"Ensure buttons have visible text or aria-label attribute"}]}function BP(){return[{selector:".text-content",html:'<div class="text-content">',target:[".text-content"],failureSummary:"Text elements should meet WCAG 2.2 AA contrast ratio (4.5:1)",fixSuggestion:"Verify text color has sufficient contrast against background"}]}function qP(){return[{selector:"a:not([aria-label])",html:'<a href="#">',target:["a"],failureSummary:"Links should have descriptive text",fixSuggestion:"Add meaningful link text or aria-label attribute"}]}function GP(){return[{selector:":focus",html:"<element>:focus",target:[":focus"],failureSummary:"Interactive elements should have visible focus indicators",fixSuggestion:"Do not remove outline on :focus; use :focus-visible for styling"}]}function jP(){return[{selector:"input:not([aria-label]):not([id])",html:'<input type="text">',target:["input"],failureSummary:"Form inputs should have associated labels",fixSuggestion:'Add <label for="id"> or aria-label to form inputs'}]}function HP(){return[{selector:'[role="dialog"]',html:'<div role="dialog">',target:['[role="dialog"]'],failureSummary:"Modal dialogs should not trap keyboard focus",fixSuggestion:"Ensure Escape key closes modal and Tab cycles within dialog"}]}function WP(){return[{selector:"[tabindex]",html:'<div tabindex="...">',target:["[tabindex]"],failureSummary:"Focus order should follow logical reading sequence",fixSuggestion:'Avoid positive tabindex values; use tabindex="0" or "-1"'}]}function UP(c,t){let e=[],r=or(t.url),i=parseInt(r,36),n=c.id.split("").reduce((a,o)=>a+o.charCodeAt(0),0),s=1+(i+n)%10;for(let a=0;a<s;a++)if((i+n+a*100)%100/100<c.simulationFailureRate){let l=QP(c.id,a);e.push({selector:l,html:`<element class="${c.id}-element-${a}">Content</element>`,target:[l],failureSummary:"Element does not meet accessibility requirements",fixSuggestion:"Review and update the element to meet WCAG guidelines"})}return e}function QP(c,t){let r={"image-alt":["img"],"button-name":["button"],"color-contrast":["div","p","span"],"html-lang":["html"],"link-name":["a"],"focus-visible":["button","a","input"],"bypass-blocks":["main","nav"],label:["input","select","textarea"],"keyboard-trap":["div","dialog"],"focus-order":["button","a","input"]}[c]||["div"],i=r[t%r.length],n=["content","widget","component","item","element"],s=n[t%n.length];return`${i}.${s}`}function zv(c,t){let e=c.id.toLowerCase();return e.includes("image")||e.includes("alt")?5+t.url.length%10:e.includes("form")||e.includes("label")||e.includes("input")?8+t.url.length%12:e.includes("link")||e.includes("anchor")?15+t.url.length%20:e.includes("color")||e.includes("contrast")?20+t.url.length%15:e.includes("heading")||e.includes("h1")||e.includes("h2")?6+t.url.length%8:e.includes("aria")||e.includes("role")?12+t.url.length%18:10+t.url.length%10}function Gv(c,t){let r={"1.1.1":.12,"1.3.1":.08,"1.4.1":.05,"1.4.3":.15,"1.4.6":.25,"2.1.1":.1,"2.1.2":.03,"2.4.1":.08,"2.4.3":.06,"2.4.4":.1,"2.4.7":.12,"3.1.1":.04,"4.1.1":.02,"4.1.2":.09}[c.id]??.1,i=c.id.charCodeAt(0)*100,s=(t+i)%100/100>=r;return{passed:s,reason:s?void 0:`Criterion ${c.id} (${c.title}) not fully satisfied`}}function tm(c){let t=["h1","p","a","button",".card-text",".nav-link"],e=[],r=or(c),i=parseInt(r,36);for(let n=0;n<t.length;n++){let s=t[n],a=4.5+(i+n*1e3)%100/10,o=Math.round(a*100)/100,u=s==="h1"||s==="button"?3:4.5,d=o>=u,m=20+(i+n*50)%30,p=200+(i+n*30)%55,h=m.toString(16).padStart(2,"0"),v=p.toString(16).padStart(2,"0");e.push({element:s,foreground:`#${h}${h}${h}`,background:`#${v}${v}${v}`,ratio:o,requiredRatio:u,passes:d,wcagLevel:"AA"})}return e}function rm(c){let t=or(c),e=KP(c,t),r=JP(e),i=YP(c,t);return{url:c,focusableElements:e.length,tabOrder:e,issues:r,traps:i}}function KP(c,t){let e=[],r=parseInt(t,36);return[{selector:"#skip-link",type:"link"},{selector:"header nav a.logo",type:"link"},{selector:"header nav a.menu-item",type:"link"},{selector:"#search-input",type:"input"},{selector:"#search-button",type:"button"},{selector:"main a",type:"link"},{selector:"main button",type:"button"},{selector:"form input",type:"input"},{selector:"form select",type:"input"},{selector:'form button[type="submit"]',type:"button"},{selector:"footer a",type:"link"}].forEach((n,s)=>{let o=(r+s*17)%100>=12;e.push({index:s,selector:n.selector,elementType:n.type,hasVisibleFocus:o})}),e}function JP(c){let t=[];for(let r of c)r.hasVisibleFocus||t.push({type:"no-focus-indicator",selector:r.selector,description:`Element ${r.selector} does not have a visible focus indicator`});return c.some(r=>r.selector.includes("skip"))||t.push({type:"skip-link-missing",selector:"body",description:"Page is missing a skip navigation link"}),c.every((r,i)=>{if(i===0)return!0;let n=r.selector.includes("nav")||r.selector.includes("header"),s=c[i-1].selector.includes("main");return!(n&&s)})||t.push({type:"incorrect-tab-order",selector:"body",description:"Focus order does not follow logical reading sequence"}),t}function YP(c,t){let e=[],r=parseInt(t,36),i=c.includes("modal")||c.includes("dialog")||c.includes("popup"),n=c.includes("form")||c.includes("checkout")||c.includes("register");return i&&r%100<8&&e.push({selector:'.modal, [role="dialog"]',description:"Modal dialog may trap focus without escape mechanism",escapePath:"Ensure Escape key closes modal and focus returns to trigger element"}),n&&r%100<5&&e.push({selector:"form .autocomplete, form .datepicker",description:"Form widget may trap keyboard focus",escapePath:"Add keyboard navigation (Tab/Escape) to exit widget"}),e}function or(c){let t=0;for(let e=0;e<c.length;e++){let r=c.charCodeAt(e);t=(t<<5)-t+r,t=t&t}return Math.abs(t).toString(36)}var XP={defaultWCAGLevel:"AA",includeWarnings:!0,auditTimeout:3e4,enableColorContrastCheck:!0,enableKeyboardCheck:!0,simulationMode:!1,useBrowserMode:!0,browserConfig:{headless:!0,timeout:3e4},browserClient:void 0,preferAgentBrowser:!0},Oi=x.create("visual-accessibility/accessibility-tester"),Ni=class{constructor(t,e={},r){this.memory=t;this.config={...XP,...e},this.rules=Bv(),this.vibiumClient=r??null,this.browserClient=e.browserClient??null,this.euComplianceService=new bc(t)}memory;config;rules;vibiumClient;browserClient;managedBrowserClient=null;euComplianceService;shouldUseBrowserMode(){return this.config.useBrowserMode?this.browserClient||this.config.preferAgentBrowser?!0:!(!Vs()||!zs()||!this.vibiumClient):!1}async getBrowserClient(){if(this.browserClient)return this.browserClient;if(this.managedBrowserClient)return this.managedBrowserClient;if(this.config.preferAgentBrowser)try{let t=await za("accessibility");if(await t.isAvailable())return this.managedBrowserClient=t,t}catch{Oi.debug("Browser client error:")}return null}async audit(t,e){try{let r=e?.wcagLevel||this.config.defaultWCAGLevel;if(this.shouldUseBrowserMode()){let i=await this.getBrowserClient();if(i){let n=await $v(i,t,r,this.config.browserConfig,e);if(n.success)return await this.storeReport(n.value),n;let s=we(n);Oi.warn(`Browser client audit failed: ${s}`)}if(this.vibiumClient&&Vs()&&zs()){let n=await Ov(this.vibiumClient,t,r,this.config.browserConfig,e);if(n.success)return await this.storeReport(n.value),n;let s=we(n);Oi.warn(`Vibium audit failed, falling back to heuristic mode: ${s}`)}}return this.auditWithHeuristics(t,r,e)}catch(r){return g(y(r))}}async auditElement(t,e){if(this.shouldUseBrowserMode()&&this.vibiumClient){let r=await Nv(this.vibiumClient,t,e,this.config.defaultWCAGLevel,this.config.browserConfig);if(r.success)return await this.storeReport(r.value),r;let i=we(r);Oi.warn(`Browser mode element audit failed, falling back to heuristic mode: ${i}`)}return this.audit(t,{excludeSelectors:[],wcagLevel:this.config.defaultWCAGLevel})}async auditWithHeuristics(t,e,r){try{let n=r?.includeWarnings??this.config.includeWarnings?em(this.rules,e):em(this.rules,e).filter(p=>p.impact!=="minor"),s=[],a=[],o=[];for(let p of n){let h=qv(p,{url:t},this.config.simulationMode,this.config.enableColorContrastCheck);h.nodes.length>0?s.push({id:p.id,impact:p.impact,wcagCriteria:p.wcagCriteria.map(v=>$i[v]).filter(Boolean),description:p.description,help:`Fix ${p.description.toLowerCase()}`,helpUrl:`https://www.w3.org/WAI/WCAG22/Understanding/${p.wcagCriteria[0]}`,nodes:h.nodes}):h.passed?a.push({id:p.id,description:p.description,nodes:h.checkedNodes}):o.push({id:p.id,description:p.description,reason:"Could not determine compliance",nodes:h.nodes})}let l=n.length,u=s.length,d=Math.round((l-u)/l*100),m={url:t,timestamp:new Date,violations:s,passes:a,incomplete:o,score:d,wcagLevel:e};return await this.storeReport(m),f(m)}catch(i){return g(y(i))}}async checkContrast(t){try{let e=`visual-accessibility:contrast:${or(t)}`,r=await this.memory.get(e);if(r)return f(r);let i;if(this.shouldUseBrowserMode()&&this.vibiumClient){let n=await _v(this.vibiumClient,t,this.config.defaultWCAGLevel,this.config.browserConfig);if(n.success)i=n.value;else{let s=we(n);Oi.warn(`Browser mode contrast check failed, falling back to heuristic mode: ${s}`),i=tm(t)}}else i=tm(t);return await this.memory.set(e,i,{namespace:"visual-accessibility",ttl:3600}),f(i)}catch(e){return g(y(e))}}async validateWCAGLevel(t,e){try{let r={A:1,AA:2,AAA:3},i=r[e],n=Object.values($i).filter(m=>r[m.level]<=i),s=[],a=[],o=or(t),l=parseInt(o,36);for(let m of n)Gv(m,l).passed?a.push(m):s.push(m);let u=s.length===0,d=Math.round(a.length/n.length*100);return f({level:e,passed:u,failedCriteria:s,passedCriteria:a,score:d})}catch(r){return g(y(r))}}async checkKeyboardNavigation(t){try{let e=`visual-accessibility:keyboard:${or(t)}`,r=await this.memory.get(e);if(r)return f(r);let i;if(this.shouldUseBrowserMode()&&this.config.enableKeyboardCheck&&this.vibiumClient){let n=await Vv(this.vibiumClient,t,this.config.defaultWCAGLevel,this.config.browserConfig);if(n.success)i=n.value;else{let s=we(n);Oi.warn(`Browser mode keyboard check failed, falling back to heuristic mode: ${s}`),i=rm(t)}}else i=rm(t);return await this.memory.set(e,i,{namespace:"visual-accessibility",ttl:3600}),f(i)}catch(e){return g(y(e))}}async storeReport(t){let e=w();await this.memory.set(`visual-accessibility:report:${e}`,t,{namespace:"visual-accessibility",persist:!0}),await this.memory.set(`visual-accessibility:latest:${or(t.url)}`,t,{namespace:"visual-accessibility",persist:!0})}async validateEUCompliance(t,e){try{let r=await this.audit(t,{wcagLevel:"AA",includeWarnings:!0});return r.success?await this.euComplianceService.validateCompliance(r.value,e):g(new Error(`WCAG audit failed: ${r.error.message}`))}catch(r){return g(y(r))}}getEN301549Clauses(){return this.euComplianceService.getEN301549Clauses()}getEAARequirements(){return this.euComplianceService.getEAARequirements()}getWCAGtoEN301549Mapping(){return this.euComplianceService.getWCAGMapping()}async dispose(){this.managedBrowserClient&&(await this.managedBrowserClient.dispose(),this.managedBrowserClient=null)}};k();var wc={"iphone-se":{width:375,height:667,deviceScaleFactor:2,isMobile:!0,hasTouch:!0},"iphone-14":{width:390,height:844,deviceScaleFactor:3,isMobile:!0,hasTouch:!0},"iphone-14-pro-max":{width:430,height:932,deviceScaleFactor:3,isMobile:!0,hasTouch:!0},"ipad-mini":{width:768,height:1024,deviceScaleFactor:2,isMobile:!0,hasTouch:!0},"ipad-pro":{width:1024,height:1366,deviceScaleFactor:2,isMobile:!0,hasTouch:!0},"pixel-7":{width:412,height:915,deviceScaleFactor:2.625,isMobile:!0,hasTouch:!0},"galaxy-s21":{width:360,height:800,deviceScaleFactor:3,isMobile:!0,hasTouch:!0},"desktop-hd":{width:1920,height:1080,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},"desktop-2k":{width:2560,height:1440,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},laptop:{width:1366,height:768,deviceScaleFactor:1,isMobile:!1,hasTouch:!1}},ZP={viewports:[wc["iphone-14"],wc["ipad-mini"],wc.laptop,wc["desktop-hd"]],breakpoints:[320,480,768,1024,1280,1920],checkTouchTargets:!0,minFontSize:12,minTouchTargetSize:44,simulationMode:!1},_i=class{constructor(t,e={}){this.memory=t;this.config={...ZP,...e}}memory;config;async testResponsiveness(t,e){try{let r={...this.config,...e},i=[],n=[];for(let u of r.viewports){let d=await this.testViewport(t,u,r);i.push(d),n.push(...d.layoutIssues)}let s=this.detectBreakpointIssues(t,i,r),a=this.calculateLayoutScore(i,n),o=this.generateRecommendations(n,s),l={url:t,timestamp:new Date,viewports:i,breakpointIssues:s,layoutScore:a,recommendations:o};return await this.storeResult(l),f(l)}catch(r){return g(y(r))}}async compareViewports(t,e,r){try{let i=this.createScreenshot(t,e),n=this.createScreenshot(t,r),s=this.calculateStructuralDiff(i,n);return f(s)}catch(i){return g(y(i))}}async testBreakpoint(t,e){try{let r={width:e,height:800,deviceScaleFactor:1,isMobile:e<768,hasTouch:e<1024},i=await this.testViewport(t,r,this.config);return f(i)}catch(r){return g(y(r))}}async analyzeBreakpoints(t){try{let e=this.findContentBreaks(t),r=this.config.breakpoints,i=this.suggestBreakpoints(e),n=this.calculateBreakpointCoverage(r,e);return f({currentBreakpoints:r,suggestedBreakpoints:i,contentBreaks:e,coverageScore:n})}catch(e){return g(y(e))}}async testViewport(t,e,r){let i=this.createScreenshot(t,e),n=this.detectLayoutIssues(t,e,r),s=this.hashUrl(t),o=200+(parseInt(s,36)+e.width)%1e3,l=n.filter(u=>u.severity==="critical").length===0;return{viewport:e,screenshot:i,layoutIssues:n,renderTime:o,passed:l}}createScreenshot(t,e){let r=this.hashUrl(t),n=500+(parseInt(r,36)+e.width+e.height)%2e3;return{id:w(),url:t,viewport:e,timestamp:new Date,path:he.create(`.visual-tests/responsive/${e.width}x${e.height}.png`),metadata:{browser:"chromium",os:process.platform,fullPage:!1,loadTime:n}}}detectLayoutIssues(t,e,r){return r.simulationMode?this.detectLayoutIssuesSimulation(t,e,r):this.detectLayoutIssuesHeuristic(t,e,r)}detectLayoutIssuesHeuristic(t,e,r){let i=[],n=t.toLowerCase(),s=this.hasResponsivePatterns(n);e.width<768&&(this.hasWideContentPatterns(n)&&i.push({type:"horizontal-overflow",severity:"critical",element:".wide-content, table, pre",description:"Wide content elements may cause horizontal overflow on mobile",viewport:e}),s||i.push({type:"horizontal-overflow",severity:"warning",element:".container",description:"Page may lack responsive CSS breakpoints for mobile",viewport:e})),e.width<=320&&i.push({type:"text-overflow",severity:"warning",element:"body",description:"Verify viewport meta tag is set correctly for very small screens",viewport:e}),r.checkTouchTargets&&e.hasTouch&&(this.hasInteractiveElements(n)&&i.push({type:"touch-target-size",severity:"warning",element:"button, a, input",description:`Touch targets should be at least ${r.minTouchTargetSize}px for accessibility`,viewport:e}),e.isMobile&&this.hasNavigationElements(n)&&i.push({type:"touch-target-size",severity:"info",element:"nav a",description:"Navigation links may be too small for touch on mobile devices",viewport:e})),e.isMobile&&r.minFontSize>0&&this.hasDataDensePatterns(n)&&i.push({type:"font-size-too-small",severity:"warning",element:".data, .table, .form-label",description:`Font size may be below ${r.minFontSize}px on mobile`,viewport:e}),this.hasImagePatterns(n)&&(e.deviceScaleFactor>1&&i.push({type:"image-not-responsive",severity:"info",element:"img",description:"Verify images use srcset for high-DPI displays",viewport:e}),e.width<480&&i.push({type:"image-not-responsive",severity:"info",element:"img",description:"Verify images are resized for mobile to reduce bandwidth",viewport:e}));let a=this.findNearestBreakpoint(e.width,r.breakpoints);return a.gap>200&&i.push({type:"hidden-content",severity:"info",element:"body",description:`Viewport ${e.width}px is ${a.gap}px from nearest breakpoint (${a.value}px)`,viewport:e}),this.hasOverlapRiskPatterns(n)&&e.width<1024&&i.push({type:"overlapping-elements",severity:"warning",element:".positioned, .absolute, .fixed",description:"Positioned elements may overlap on smaller screens",viewport:e}),i}hasResponsivePatterns(t){return t.includes("mobile")||t.includes("responsive")||t.includes("bootstrap")||t.includes("tailwind")||t.includes("material")||t.includes("foundation")}hasWideContentPatterns(t){return t.includes("table")||t.includes("data")||t.includes("report")||t.includes("code")||t.includes("pre")||t.includes("spreadsheet")}hasInteractiveElements(t){return t.includes("form")||t.includes("button")||t.includes("input")||t.includes("select")||t.includes("click")||t.includes("action")}hasNavigationElements(t){return t.includes("nav")||t.includes("menu")||t.includes("header")||t.includes("sidebar")||t.includes("footer")||t.includes("breadcrumb")}hasDataDensePatterns(t){return t.includes("dashboard")||t.includes("analytics")||t.includes("report")||t.includes("table")||t.includes("stats")||t.includes("metrics")}hasImagePatterns(t){return t.includes("gallery")||t.includes("photo")||t.includes("image")||t.includes("media")||t.includes("portfolio")||t.includes("hero")}hasOverlapRiskPatterns(t){return t.includes("modal")||t.includes("overlay")||t.includes("tooltip")||t.includes("dropdown")||t.includes("popup")||t.includes("float")}findNearestBreakpoint(t,e){let r=e[0]||0,i=Math.abs(t-r);for(let n of e){let s=Math.abs(t-n);s<i&&(i=s,r=n)}return{value:r,gap:i}}detectLayoutIssuesSimulation(t,e,r){let i=[],n=this.hashUrl(t),s=parseInt(n,36),a=(s+e.width)%100/100;e.width<768&&a<.2&&i.push({type:"horizontal-overflow",severity:"critical",element:".container",description:"Content overflows horizontally causing horizontal scroll",viewport:e});let o=(s+e.width+100)%100/100;e.width<480&&o<.15&&i.push({type:"text-overflow",severity:"warning",element:".long-text",description:"Text content is truncated or overflows container",viewport:e});let l=(s+e.width+200)%100/100;r.checkTouchTargets&&e.isMobile&&l<.25&&i.push({type:"touch-target-size",severity:"warning",element:".small-button",description:`Touch target is smaller than ${r.minTouchTargetSize}px minimum`,viewport:e});let u=(s+e.width+300)%100/100;return e.isMobile&&u<.1&&i.push({type:"font-size-too-small",severity:"warning",element:".fine-print",description:`Font size is below ${r.minFontSize}px minimum for readability`,viewport:e}),(s+e.width+400)%100/100<.15&&i.push({type:"image-not-responsive",severity:"info",element:"img.hero-image",description:"Image does not scale properly for viewport width",viewport:e}),i}detectBreakpointIssues(t,e,r){if(!r.simulationMode)return[];let i=[],n=this.hashUrl(t),s=parseInt(n,36),a=[...e].sort((o,l)=>o.viewport.width-l.viewport.width);for(let o=0;o<a.length-1;o++){let l=a[o],u=a[o+1],d=r.breakpoints.find(m=>m>l.viewport.width&&m<u.viewport.width);d&&(s+d+o*100)%100/100<.2&&i.push({breakpoint:d,description:"Layout shifts abruptly at this breakpoint",affectedElements:[".navigation",".sidebar"],suggestion:"Consider adding intermediate styles or adjusting breakpoint"})}return i}calculateLayoutScore(t,e){let i=e.filter(o=>o.severity==="critical").length*15,n=e.filter(o=>o.severity==="warning").length*5,s=e.filter(o=>o.severity==="info").length*1,a=t.every(o=>o.passed)?5:0;return Math.max(0,100-i-n-s+a)}generateRecommendations(t,e){let r=[],i=new Map;for(let n of t){let s=i.get(n.type)||[];i.set(n.type,[...s,n])}return i.has("horizontal-overflow")&&r.push("Use CSS overflow-x: hidden or adjust element widths to prevent horizontal scrolling"),i.has("touch-target-size")&&r.push("Increase touch target sizes to at least 44x44 pixels for better mobile usability"),i.has("font-size-too-small")&&r.push("Use relative font units (rem/em) and ensure minimum 16px base font size on mobile"),i.has("image-not-responsive")&&r.push("Use srcset and sizes attributes for responsive images, or CSS max-width: 100%"),e.length>0&&r.push("Review CSS media queries to ensure smooth transitions between breakpoints"),r}calculateStructuralDiff(t,e){let r=Math.abs(t.viewport.width-e.viewport.width),i=Math.abs(t.viewport.height-e.viewport.height),n=Math.min(50,(r+i)/20);return{baselineId:t.id,comparisonId:e.id,diffPercentage:n,diffPixels:Math.floor(n*1e3),regions:[],status:n<10?"acceptable":"changed"}}findContentBreaks(t){let e=[],r=this.hashUrl(t),i=parseInt(r.substring(0,6),36),n=[375,540,768,992,1200,1400],s=t.includes("shop")||t.includes("product")||t.includes("cart"),a=t.includes("dashboard")||t.includes("admin")||t.includes("panel"),o=t.includes("blog")||t.includes("article")||t.includes("news");for(let l=0;l<n.length;l++){let u=n[l],d=(i+l*100+u)%100,m,p,h;if(s?(m=40,p=[".product-grid",".cart-items",".checkout-form",".filters"],h="Product grid layout adjusts for viewport"):a?(m=50,p=[".sidebar",".dashboard-cards",".data-table",".nav-menu"],h="Dashboard layout reorganizes for smaller screens"):o?(m=60,p=[".article-content",".sidebar-widgets",".comments"],h="Content width and sidebar visibility changes"):(m=55,p=[".container",".grid",".navigation",".footer"],h="Content layout changes significantly"),d<m){let v=Math.min(p.length,1+Math.floor((i+u)%p.length)),b=p.slice(0,v);e.push({width:u,reason:h,affectedElements:b})}}return e}hashUrl(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return Math.abs(e).toString(36)}suggestBreakpoints(t){let e=new Set;for(let i of t){let n=Math.round(i.width/100)*100;e.add(n)}let r=[576,768,992,1200,1400];for(let i of r)Array.from(e).some(n=>Math.abs(n-i)<50)||e.add(i);return Array.from(e).sort((i,n)=>i-n)}calculateBreakpointCoverage(t,e){if(e.length===0)return 100;let r=0;for(let i of e)t.some(n=>Math.abs(n-i.width)<50)&&r++;return Math.round(r/e.length*100)}async storeResult(t){let e=w();await this.memory.set(`visual-accessibility:responsive:${e}`,t,{namespace:"visual-accessibility",persist:!0})}};ge();var ek={stateSize:10,actionSize:5,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],numWorkers:4,nSteps:5,entropyCoeff:.01,valueLossCoeff:.5},Cc=class extends ve{actor;critic;a2cConfig;actions=[];constructor(t={}){super("a2c","actor-critic"),this.a2cConfig={...ek,...t},this.initializeActions(),this.actor=new J({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.critic=new J({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate})}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.actor.forward(e),i=Ie.forward(r),n=this.sampleAction(i),s=this.actions[n],a=this.critic.forward(e)[0],o=Math.max(.3,Math.min(1,i[n]+.4));return{action:s,confidence:o,value:a,reasoning:`A2C (${this.a2cConfig.numWorkers} workers): ${s.type}`}}async trainCore(t){let e=this.distributeToWorkers(t),r=0,i=0;for(let[n,s]of Object.entries(e)){if(s.length===0)continue;let a=this.calculateReturns(s),o=this.calculateAdvantages(s,a);for(let l=0;l<s.length;l++){let u=s[l],d=this.prepareState(u.state),m=this.actionToIndex(u.action),p=o[l],h=this.actor.forward(d),v=Ie.forward(h),C=-Math.log(v[m]+1e-10)*p,S=this.calculateEntropy(v),R=this.a2cConfig.entropyCoeff*S,E=new Float32Array(v.length);for(let j=0;j<E.length;j++)j===m?E[j]=-p*(1-v[j]):E[j]=p*v[j];this.actor.backward(E);for(let j of this.actor.layers)j.update(this.config.learningRate*.1);let T=this.critic.forward(d)[0],I=a[l],O=(T-I)**2,q=new Float32Array([I]);this.critic.train(d,q,new Fe),r+=Math.abs(C-R),i+=O}}return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((n,s)=>n+s,0)/this.rewardHistory.length,loss:(r+i)/t.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural A2C for Fleet Coordination",capabilities:["Multi-worker parallel training","Advantage estimation","Combined policy and value learning"],hyperparameters:{stateSize:this.a2cConfig.stateSize,actionSize:this.a2cConfig.actionSize,numWorkers:this.a2cConfig.numWorkers,entropyCoeff:this.a2cConfig.entropyCoeff},stats:this.stats}}distributeToWorkers(t){let e={};for(let r=0;r<this.a2cConfig.numWorkers;r++)e[r]=[];return t.forEach((r,i)=>{let n=i%this.a2cConfig.numWorkers;e[n].push(r)}),e}calculateReturns(t){let e=[],r=0;for(let i=t.length-1;i>=0;i--)r=t[i].reward+this.config.discountFactor*r,e.unshift(r);return e}calculateAdvantages(t,e){return t.map((r,i)=>{let n=this.prepareState(r.state),s=this.critic.forward(n)[0];return e[i]-s})}prepareState(t){let e=t.features.slice(0,this.a2cConfig.stateSize);for(;e.length<this.a2cConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]/=r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"coordinate",value:"parallel"},{type:"coordinate",value:"sequential"},{type:"coordinate",value:"distributed"},{type:"allocate",value:{agents:2}},{type:"rebalance",value:1}],this.a2cConfig.actionSize=this.actions.length,this.actor=new J({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.critic=new J({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate})}actionToIndex(t){let e=`${t.type}:${JSON.stringify(t.value)}`;for(let r=0;r<this.actions.length;r++)if(`${this.actions[r].type}:${JSON.stringify(this.actions[r].value)}`===e)return r;return 0}sampleAction(t){if(z()<this.config.explorationRate)return Se(0,this.actions.length);let e=z(),r=0;for(let i=0;i<t.length;i++)if(r+=t[i],e<=r)return i;return this.argmax(t)}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}calculateEntropy(t){let e=0;for(let r=0;r<t.length;r++)t[r]>0&&(e-=t[r]*Math.log(t[r]));return e}async exportCustomData(){return{actor:this.actor.getParameters(),critic:this.critic.getParameters(),a2cConfig:this.a2cConfig}}async importCustomData(t){t.actor&&this.actor.setParameters(t.actor),t.critic&&this.critic.setParameters(t.critic),t.a2cConfig&&(this.a2cConfig={...this.a2cConfig,...t.a2cConfig}),this.initialized=!0}async resetAlgorithm(){this.actor=new J({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate}),this.critic=new J({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.config.learningRate})}};var tk={maxConcurrentWorkflows:5,defaultTimeout:12e4,publishEvents:!0,enableParallelViewportTesting:!0,enableA2C:!0,enableFlashAttention:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Xe=x.create("visual-accessibility"),Sc=class extends ie{constructor(e,r,i,n={},s={},a={},o={},l){let u={...tk,...n};super(e,"visual-accessibility",u,{verifyFindingTypes:["accessibility-violation","visual-regression","wcag-non-compliance"]});this.memory=r;this.agentCoordinator=i;this.visualTester=yc({memory:r,llmRouter:l},s),this.accessibilityTester=new Ni(r,a),this.responsiveTester=new _i(r,o)}memory;agentCoordinator;visualTester;accessibilityTester;responsiveTester;a2cAlgorithm;flashAttention;async onInitialize(){if(this.config.enableA2C)try{this.a2cAlgorithm=new Cc({stateSize:10,actionSize:5,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],numWorkers:4}),Xe.info("A2C algorithm created successfully")}catch(e){throw Xe.error("Failed to create A2C:",e instanceof Error?e:void 0),new Error(`A2C creation failed: ${P(e)}`)}if(this.config.enableFlashAttention)try{this.flashAttention=await tt("test-similarity"),Xe.info("QEFlashAttention initialized successfully")}catch(e){throw Xe.error("Failed to initialize Flash Attention:",e instanceof Error?e:void 0),new Error(`Flash Attention initialization failed: ${P(e)}`)}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState(),this.flashAttention&&(this.flashAttention.dispose(),this.flashAttention=void 0),this.a2cAlgorithm=void 0}getActiveWorkflows(){return super.getActiveWorkflows()}async runVisualTests(e,r){let i=w();try{if(this.startWorkflow(i,"visual"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Xe.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return g(new Error("Operation paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return g(new Error("Agent limit reached, cannot spawn visual testing agents"));let n=await this.spawnVisualTestingAgent(i);if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);this.addAgentToWorkflow(i,n.value);let s=[],a=0,o=0,l=0,u=[];for(let b of e)for(let C of r)u.push({url:b,viewport:C});if(this.config.enableA2C&&u.length>1){let b={urgency:5,availableResources:80,historicalFailureRate:.1},C=await this.prioritizeVisualTests(u.map(S=>({...S,priority:5})),b);C.success&&(u=C.value.orderedTests.map(S=>({url:S.url,viewport:S.viewport})),Xe.info(`[visual-accessibility] Using ${C.value.strategy} strategy for visual test order (confidence: ${C.value.confidence.toFixed(2)})`))}let d=u.length,m=0;for(let{url:b,viewport:C}of u){let S=await this.visualTester.captureScreenshot(b,{viewport:C});if(!S.success){o++,s.push({url:b,viewport:C,status:"failed",screenshot:{id:"",url:b,viewport:C,timestamp:new Date,path:he.create("error-placeholder.png"),metadata:{browser:"",os:"",fullPage:!1,loadTime:0}}});continue}let R=S.value,E=await this.visualTester.getBaseline(b,C);if(!E)await this.visualTester.setBaseline(R),l++,s.push({url:b,viewport:C,status:"new",screenshot:R});else{let T=await this.visualTester.compare(R,E.id);if(T.success){let I=T.value,O=I.status==="identical"||I.status==="acceptable"?"passed":"failed";O==="passed"?a++:o++,s.push({url:b,viewport:C,status:O,diff:I,screenshot:R}),O==="failed"&&this.config.publishEvents&&await this.publishVisualRegressionEvent(b,C,I)}else o++,s.push({url:b,viewport:C,status:"failed",screenshot:R})}m++,this.updateWorkflowProgress(i,m/d*100)}let p=this.workflows.get(i)?.startedAt.getTime()??Date.now(),h=Date.now()-p,v={totalTests:s.length,passed:a,failed:o,newBaselines:l,results:s,duration:h};return this.completeWorkflow(i),await this.agentCoordinator.stop(n.value),f(v)}catch(n){let s=y(n);return this.failWorkflow(i,s.message),{success:!1,error:s}}}async runAccessibilityAudit(e,r){let i=w();try{if(this.startWorkflow(i,"accessibility"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Xe.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return g(new Error("Operation paused: topology is in critical state"));let n=await this.spawnAccessibilityTestingAgent(i,r);if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);this.addAgentToWorkflow(i,n.value);let s=[],a=0,o=0,l=0;for(let p=0;p<e.length;p++){let h=e[p],v=await this.accessibilityTester.audit(h,{wcagLevel:r});if(v.success){let b=v.value;s.push(b),a+=b.violations.length,o+=b.violations.filter(C=>C.impact==="critical").length,b.violations.length===0&&l++,this.config.publishEvents&&await this.publishAccessibilityAuditEvent(b)}this.updateWorkflowProgress(i,(p+1)/e.length*100)}let u=s.length>0?Math.round(s.reduce((p,h)=>p+h.score,0)/s.length):0,d=this.identifyTopIssues(s),m={totalUrls:e.length,passingUrls:l,totalViolations:a,criticalViolations:o,averageScore:u,reports:s,topIssues:d};return this.completeWorkflow(i),await this.agentCoordinator.stop(n.value),f(m)}catch(n){let s=y(n);return this.failWorkflow(i,s.message),{success:!1,error:s}}}async approveVisualChanges(e,r){try{for(let i of e){let n=await this.memory.get(`visual-accessibility:diff:${i}`);if(!n)continue;let s=await this.memory.get(`visual-accessibility:screenshot:${n.comparisonId}`);s&&(await this.visualTester.setBaseline(s),this.config.publishEvents&&await this.publishBaselineUpdatedEvent(s,r))}return f(void 0)}catch(i){return g(y(i))}}async generateRemediationPlan(e){try{let r=[];for(let a of e){let o=this.createRemediation(a);r.push(o)}let i={trivial:0,minor:1,moderate:2,major:3};r.sort((a,o)=>i[a.effort]-i[o.effort]);let n=this.calculateTotalEffort(r),s={violations:r,totalEffort:n,prioritizedOrder:r.map(a=>a.violationId)};return f(s)}catch(r){return g(y(r))}}async getVisualTestingStatus(){try{let e=await this.memory.search("visual-accessibility:baseline:*",1e3),r=e.length,i=await this.memory.search("visual-accessibility:diff:*",1e3),n=0;for(let p of i){let h=await this.memory.get(p);h&&(h.status==="changed"||h.status==="failed")&&n++}let a=Array.from(this.workflows.values()).filter(p=>p.type==="visual"&&p.status==="completed").sort((p,h)=>(h.completedAt?.getTime()??0)-(p.completedAt?.getTime()??0))[0]?.completedAt??new Date,o=Array.from(this.workflows.values()).filter(p=>p.type==="visual").length,l=Array.from(this.workflows.values()).filter(p=>p.type==="visual"&&p.status==="failed").length,u=o>0?l/o:0,d=await this.calculateViewportCoverage(e);return f({baselineCount:r,pendingReviews:n,lastTestRun:a,failureRate:u,coverageByViewport:d})}catch(e){return g(y(e))}}async runVisualRegression(e){let r=w();try{if(this.startWorkflow(r,"visual"),!this.agentCoordinator.canSpawn())return this.failWorkflow(r,"Agent limit reached"),g(new Error("Agent limit reached, cannot spawn visual testing agents"));let i=await this.spawnVisualTestingAgent(r);if(!i.success)return this.failWorkflow(r,i.error.message),g(i.error);this.addAgentToWorkflow(r,i.value);let n=[],s={width:1280,height:720,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},a=e.viewports??[s];for(let o of e.pages)for(let l of a){let u=await this.visualTester.captureScreenshot(`${e.baselineUrl}${o}`,{viewport:l}),d=await this.visualTester.captureScreenshot(`${e.compareUrl}${o}`,{viewport:l});if(u.success&&d.success){let m=await this.visualTester.compare(d.value,u.value.id);m.success?n.push({page:o,diffPercentage:m.value.diffPercentage,passed:m.value.status==="identical"||m.value.status==="acceptable"}):n.push({page:o,diffPercentage:100,passed:!1})}else n.push({page:o,diffPercentage:100,passed:!1})}return this.completeWorkflow(r),await this.agentCoordinator.stop(i.value),f({differences:n})}catch(i){let n=y(i);return this.failWorkflow(r,n.message),{success:!1,error:n}}}async runAccessibilityAuditSingle(e){let r=await this.runAccessibilityAudit([e.url],e.wcagLevel);if(!r.success)return g(r.error);let i=r.value.reports[0];return i?f({violations:i.violations,wcagLevel:i.wcagLevel,score:i.score}):f({violations:[],wcagLevel:e.wcagLevel,score:100})}async compareScreenshots(e){try{let r=await this.memory.get(`visual-accessibility:screenshot:${e.baseline}`),i=await this.memory.get(`visual-accessibility:screenshot:${e.current}`);if(r&&i){let n=await this.visualTester.compare(i,r.id);if(n.success){let s=e.threshold??.1;return f({diffPercentage:n.value.diffPercentage,passed:n.value.diffPercentage<=s*100,diffImagePath:n.value.diffImagePath?.value})}}return f({diffPercentage:0,passed:!0})}catch(r){return g(y(r))}}async analyzeColorContrast(e){try{let r=e.wcagLevel??"AA",i=await this.accessibilityTester.audit(e.url,{wcagLevel:r});if(!i.success)return g(i.error);let s=i.value.violations.filter(a=>a.id.includes("color-contrast")||a.id.includes("contrast")).flatMap(a=>a.nodes.map(o=>({element:o.target.join(" "),foreground:"#000000",background:"#ffffff",ratio:1,required:r==="AAA"?7:4.5})));return f({issues:s})}catch(r){return g(y(r))}}async testResponsiveDesign(e){try{let r=[];for(let i of e.viewports){let n={width:i.width,height:i.height,deviceScaleFactor:1,isMobile:i.width<768,hasTouch:i.width<1024},s=await this.visualTester.captureScreenshot(e.url,{viewport:n}),a=i.name??`${i.width}x${i.height}`,o=[];s.success||o.push(`Failed to capture screenshot: ${s.error.message}`),r.push({viewport:a,passed:o.length===0,issues:o})}return f({viewportResults:r})}catch(r){return g(y(r))}}async spawnVisualTestingAgent(e){let r={name:`visual-tester-${e.slice(0,8)}`,domain:"visual-accessibility",type:"tester",capabilities:["visual-testing","screenshot-capture","image-diff"],config:{workflowId:e}};return this.agentCoordinator.spawn(r)}async spawnAccessibilityTestingAgent(e,r){let i={name:`a11y-tester-${e.slice(0,8)}`,domain:"visual-accessibility",type:"analyzer",capabilities:["accessibility-audit","wcag-validation",r],config:{workflowId:e,wcagLevel:r}};return this.agentCoordinator.spawn(i)}async calculateViewportCoverage(e){let r=new Map([["mobile",0],["tablet",0],["desktop",0]]),i=new Set;for(let a of e){let o=a.match(/baseline:([^_]+)_(\d+)x(\d+)_/);if(o){let[,l,u]=o,d=parseInt(u,10);i.add(l);let m=this.categorizeViewport(d);r.set(m,(r.get(m)||0)+1)}}let n=i.size||1,s=new Map;for(let[a,o]of r){let l=Math.min(100,Math.round(o/n*100));s.set(a,l)}return e.length===0?new Map([["mobile",0],["tablet",0],["desktop",0]]):s}categorizeViewport(e){return e<=480?"mobile":e<=1024?"tablet":"desktop"}async publishVisualRegressionEvent(e,r,i){let n={id:w(),type:"visual-accessibility.VisualRegressionDetected",timestamp:new Date,source:"visual-accessibility",payload:{url:e,viewport:r,diffPercentage:i.diffPercentage,diffImagePath:i.diffImagePath?.value}};await this.eventBus.publish(n)}async publishAccessibilityAuditEvent(e){let r={id:w(),type:"visual-accessibility.AccessibilityAuditCompleted",timestamp:new Date,source:"visual-accessibility",payload:{url:e.url,violations:e.violations.length,score:e.score,wcagLevel:e.wcagLevel}};await this.eventBus.publish(r)}async publishBaselineUpdatedEvent(e,r){let i={id:w(),type:"visual-accessibility.BaselineUpdated",timestamp:new Date,source:"visual-accessibility",payload:{screenshotId:e.id,url:e.url,viewport:e.viewport,reason:r}};await this.eventBus.publish(i)}identifyTopIssues(e){let r=new Map;for(let i of e)for(let n of i.violations){let s=r.get(n.id);s?(s.occurrences++,s.affectedUrls.includes(i.url)||s.affectedUrls.push(i.url)):r.set(n.id,{ruleId:n.id,description:n.description,occurrences:1,impact:n.impact,affectedUrls:[i.url]})}return Array.from(r.values()).sort((i,n)=>n.occurrences-i.occurrences).slice(0,10)}createRemediation(e){let r=this.estimateEffort(e);return{violationId:e.id,description:e.description,fix:e.help,codeExample:this.generateCodeExample(e),effort:r,wcagReference:e.wcagCriteria[0]?.id??""}}estimateEffort(e){let r=e.nodes.length;return e.impact==="minor"&&r<=3?"trivial":e.impact==="minor"||r<=5?"minor":e.impact==="serious"&&r<=10?"moderate":"major"}generateCodeExample(e){return e.id.includes("alt")?'<img src="..." alt="Descriptive text for the image">':e.id.includes("label")?`<label for="input-id">Label text</label>
2990
+ <input id="input-id" type="text">`:e.id.includes("button")?'<button aria-label="Descriptive action">Icon</button>':"<!-- See WCAG guidelines for specific implementation -->"}calculateTotalEffort(e){let r={trivial:1,minor:2,moderate:4,major:8},i=e.reduce((n,s)=>n+r[s.effort],0);return i<=5?"trivial":i<=15?"minor":i<=40?"moderate":"major"}async prioritizeVisualTests(e,r){if(!this.a2cAlgorithm||!this.config.enableA2C)return f({orderedTests:e.map(i=>({...i,priority:i.priority??5,reason:"default"})),strategy:"default",confidence:1});if(e.length===0)return f({orderedTests:[],strategy:"empty",confidence:1});try{let i={id:`visual-priority-${Date.now()}`,features:[r.urgency/10,r.availableResources/100,r.historicalFailureRate,e.length/100,e.filter(u=>u.viewport.width<=480).length/Math.max(1,e.length),e.filter(u=>u.viewport.width>1024).length/Math.max(1,e.length),e.filter(u=>(u.priority??5)>7).length/Math.max(1,e.length),e.filter(u=>u.url.includes("dashboard")).length/Math.max(1,e.length),e.filter(u=>u.url.includes("checkout")).length/Math.max(1,e.length),e.filter(u=>u.url.includes("login")).length/Math.max(1,e.length)]},n=await this.a2cAlgorithm.predict(i),s=e.map(u=>({...u,priority:u.priority??5,reason:"default"})),a="default";switch(n.action.type){case"coordinate":if(n.action.value==="parallel")s.sort((u,d)=>u.viewport.width-d.viewport.width),s=s.map(u=>({...u,priority:10-Math.floor(u.viewport.width/200),reason:"parallel-viewport-order"})),a="parallel-viewport-order";else if(n.action.value==="sequential"){let u=["checkout","payment","login"];s.sort((d,m)=>{let p=u.some(v=>d.url.includes(v))?1:0;return(u.some(v=>m.url.includes(v))?1:0)-p}),s=s.map(d=>({...d,priority:u.some(m=>d.url.includes(m))?9:5,reason:"sequential-critical-url"})),a="sequential-critical-url"}break;case"allocate":{let u=typeof n.action.value=="object"?n.action.value.agents??2:2,d=Math.ceil(s.length/u);s=s.map((m,p)=>({...m,priority:10-Math.floor(p/d),reason:`allocate-agent-${Math.floor(p/d)}`})),a="allocate-by-agent";break}case"rebalance":{let u=new Map;for(let d of s)u.set(d.viewport.width,(u.get(d.viewport.width)||0)+1);s.sort((d,m)=>(u.get(d.viewport.width)||0)-(u.get(m.viewport.width)||0)),s=s.map(d=>({...d,priority:10-(u.get(d.viewport.width)||0),reason:"rebalance-viewport-coverage"})),a="rebalance-viewport-coverage";break}default:break}let o=await this.calculatePrioritizationReward(s,r),l=n.action;return await this.a2cAlgorithm.train({state:i,action:l,reward:o,nextState:i,done:!0}),Xe.info(`[visual-accessibility] A2C prioritized ${e.length} visual tests using ${a} strategy (confidence: ${n.confidence.toFixed(2)})`),f({orderedTests:s,strategy:a,confidence:n.confidence})}catch(i){return Xe.error("A2C prioritization failed:",i instanceof Error?i:void 0),f({orderedTests:e.map(n=>({...n,priority:n.priority??5,reason:"fallback"})),strategy:"fallback",confidence:.5})}}async calculatePrioritizationReward(e,r){let i=.5,n=e.slice(0,Math.ceil(e.length/4)),s=n.filter(o=>["checkout","payment","login","dashboard"].some(l=>o.url.includes(l))).length;i+=Math.min(.3,s/n.length);let a=new Set(e.map(o=>`${o.viewport.width}x${o.viewport.height}`));return i+=Math.min(.2,a.size/10),r.availableResources<30&&e.length>50&&(i-=.1),Math.max(0,Math.min(1,i))}async findSimilarImages(e,r,i=5){if(!this.flashAttention||!this.config.enableFlashAttention)return this.cosineSimilarityFallback(e,r,i);try{return(await this.flashAttention.computeTestSimilarity(e,r,i)).map(s=>({index:s.index,similarity:s.similarity,imagePath:`image-${s.index}.png`}))}catch(n){return Xe.error("Flash Attention similarity search failed:",n instanceof Error?n:void 0),this.cosineSimilarityFallback(e,r,i)}}cosineSimilarityFallback(e,r,i){let n=[];for(let s=0;s<r.length;s++){let o=(Mt(e,r[s])+1)/2;n.push({index:s,similarity:o,imagePath:`image-${s}.png`})}return n.sort((s,a)=>a.similarity-s.similarity),n.slice(0,i)}async storeVisualPattern(e,r,i,n){if(!(!this.flashAttention||!this.config.enableFlashAttention))try{let s=this.createVisualEmbedding(e,r,i,n);await this.memory.set(`visual-accessibility:embedding:${e}:${r.width}x${r.height}`,{embedding:s,url:e,viewport:r,diffScore:i,passed:n,timestamp:new Date},{namespace:"visual-accessibility",persist:!0}),Xe.info(`Stored visual pattern for ${e} at ${r.width}x${r.height}`)}catch(s){Xe.error("Failed to store visual pattern:",s instanceof Error?s:void 0)}}createVisualEmbedding(e,r,i,n){let s=[],a=this.hashString(e);for(let u=0;u<100;u++)s.push((a>>u%32&1)===1?1:0);s.push(r.width/2e3),s.push(r.height/2e3),s.push(r.deviceScaleFactor/3),s.push(r.isMobile?1:0),s.push(r.hasTouch?1:0),s.push(r.width<=480?1:0),s.push(r.width<=1024&&r.width>480?1:0),s.push(r.width>1024?1:0);let o=r.height>r.width;s.push(o?1:0),s.push(o?0:1),s.push(i/100),s.push(n?1:0),s.push(i>10?1:0),s.push(i>50?1:0);let l=this.extractPathFeatures(e);return s.push(...l.slice(0,270)),new Float32Array(s.slice(0,384))}hashString(e){let r=0;for(let i=0;i<e.length;i++)r=(r<<5)-r+e.charCodeAt(i),r=r|0;return Math.abs(r)}extractPathFeatures(e){let r=[],i=new URL(e).pathname,n=["dashboard","checkout","login","profile","settings","api","admin","search"];for(let a of n)r.push(i.includes(a)?1:0);let s=i.split("/").filter(Boolean).length;for(r.push(s/10),r.push(e.includes("?")?1:0),r.push(e.startsWith("https://")?1:0);r.length<270;)r.push(0);return r}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.FileChanged",this.handleFileChanged.bind(this)),this.eventBus.subscribe("ci-cd.DeploymentCompleted",this.handleDeploymentCompleted.bind(this))}async handleFileChanged(e){}async handleDeploymentCompleted(e){}async loadWorkflowState(){let e=await this.memory.get("visual-accessibility:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("visual-accessibility:coordinator:workflows",e,{namespace:"visual-accessibility",persist:!0})}requiresConsensus(e){return this.consensusMixin.requiresConsensus(e)}async verifyFinding(e){return this.consensusMixin.verifyFinding(e)}async verifyAccessibilityViolation(e,r){let i=U({id:w(),type:"accessibility-violation",confidence:r,description:`Accessibility violation: ${e.description} (${e.impact} impact)`,payload:e,detectedBy:"visual-accessibility-coordinator",severity:e.impact==="critical"?"critical":e.impact==="serious"?"high":e.impact==="moderate"?"medium":"low"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return!!(n.success&&n.value.verdict==="verified")}return!0}async verifyVisualRegression(e,r){let i=U({id:w(),type:"visual-regression",confidence:r,description:`Visual regression detected at ${e.url} (${e.viewport.width}x${e.viewport.height}): ${e.diffPercentage.toFixed(2)}% difference`,payload:e,detectedBy:"visual-accessibility-coordinator",severity:e.diffPercentage>20?"critical":e.diffPercentage>10?"high":e.diffPercentage>5?"medium":"low"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return!!(n.success&&n.value.verdict==="verified")}return!0}onTopologyHealthChange(e){return this.minCutMixin.onTopologyHealthChange(e)}};k();var im=class extends te{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;visualTester=null;accessibilityTester=null;responsiveTester=null;pluginConfig;get name(){return"visual-accessibility"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{runVisualTests:this.runVisualTests.bind(this),runAccessibilityAudit:this.runAccessibilityAudit.bind(this),approveVisualChanges:this.approveVisualChanges.bind(this),generateRemediationPlan:this.generateRemediationPlan.bind(this),getVisualTestingStatus:this.getVisualTestingStatus.bind(this),captureScreenshot:this.captureScreenshot.bind(this),captureElement:this.captureElement.bind(this),auditAccessibility:this.auditAccessibility.bind(this),checkContrast:this.checkContrast.bind(this),validateWCAGLevel:this.validateWCAGLevel.bind(this),checkKeyboardNavigation:this.checkKeyboardNavigation.bind(this),testResponsiveness:this.testResponsiveness.bind(this),analyzeBreakpoints:this.analyzeBreakpoints.bind(this),registerWorkflowActions:this.registerWorkflowActions.bind(this),getCoordinator:()=>this.coordinator,getVisualTester:()=>this.visualTester,getAccessibilityTester:()=>this.accessibilityTester,getResponsiveTester:()=>this.responsiveTester}}getTaskHandlers(){return new Map([["run-visual-tests",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.urls,i=e.viewports;return!r||r.length===0?g(new Error("Invalid run-visual-tests payload: missing urls")):this.coordinator.runVisualTests(r,i||[{width:1920,height:1080,deviceScaleFactor:1,isMobile:!1,hasTouch:!1}])}],["run-accessibility-audit",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.urls,i=e.level||"AA";return!r||r.length===0?g(new Error("Invalid run-accessibility-audit payload: missing urls")):this.coordinator.runAccessibilityAudit(r,i)}],["capture-screenshot",async e=>{if(!this.visualTester)return g(new Error("Visual tester not initialized"));let r=e.url;return r?this.visualTester.captureScreenshot(r,e.options):g(new Error("Invalid capture-screenshot payload: missing url"))}],["test-responsiveness",async e=>{if(!this.responsiveTester)return g(new Error("Responsive tester not initialized"));let r=e.url;return r?this.responsiveTester.testResponsiveness(r,e.options):g(new Error("Invalid test-responsiveness payload: missing url"))}],["validate-wcag",async e=>{if(!this.accessibilityTester)return g(new Error("Accessibility tester not initialized"));let r=e.url;if(!r)return g(new Error("Invalid validate-wcag payload: missing url"));let i=e.level||"AA";return this.accessibilityTester.validateWCAGLevel(r,i)}]])}async onInitialize(){this.visualTester=yc({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.visualTester),this.accessibilityTester=new Ni(this.memory,this.pluginConfig.accessibilityTester),this.responsiveTester=new _i(this.memory,this.pluginConfig.responsiveTester),this.coordinator=new Sc(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.pluginConfig.visualTester,this.pluginConfig.accessibilityTester,this.pluginConfig.responsiveTester,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.visualTester=null,this.accessibilityTester=null,this.responsiveTester=null}subscribeToEvents(){this.eventBus.subscribe("ci-cd.DeploymentCompleted",this.handleDeploymentCompleted.bind(this)),this.eventBus.subscribe("code-intelligence.FileChanged",this.handleFileChanged.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateTriggered",this.handleQualityGateTriggered.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"ci-cd.DeploymentCompleted":await this.handleDeploymentCompleted(e);break;case"code-intelligence.FileChanged":await this.handleFileChanged(e);break;case"quality-assessment.QualityGateTriggered":await this.handleQualityGateTriggered(e);break;default:break}}async runVisualTests(e,r){this.ensureInitialized();try{let i=await this.coordinator.runVisualTests(e,r);return i.success?this.trackSuccessfulTest("visual",i.value.totalTests):this.trackFailedTest(i.error),i}catch(i){return this.handleError(i)}}async runAccessibilityAudit(e,r){this.ensureInitialized();try{let i=await this.coordinator.runAccessibilityAudit(e,r);return i.success?this.trackSuccessfulTest("accessibility",i.value.totalUrls):this.trackFailedTest(i.error),i}catch(i){return this.handleError(i)}}async approveVisualChanges(e,r){this.ensureInitialized();try{return await this.coordinator.approveVisualChanges(e,r)}catch(i){return this.handleError(i)}}async generateRemediationPlan(e){this.ensureInitialized();try{return await this.coordinator.generateRemediationPlan(e)}catch(r){return this.handleError(r)}}async getVisualTestingStatus(){this.ensureInitialized();try{return await this.coordinator.getVisualTestingStatus()}catch(e){return this.handleError(e)}}async captureScreenshot(e,r){this.ensureInitialized();try{return await this.visualTester.captureScreenshot(e,r)}catch(i){return this.handleError(i)}}async captureElement(e,r,i){this.ensureInitialized();try{return await this.visualTester.captureElement(e,r,i)}catch(n){return this.handleError(n)}}async auditAccessibility(e,r){this.ensureInitialized();try{return await this.accessibilityTester.audit(e,r)}catch(i){return this.handleError(i)}}async checkContrast(e){this.ensureInitialized();try{return await this.accessibilityTester.checkContrast(e)}catch(r){return this.handleError(r)}}async validateWCAGLevel(e,r){this.ensureInitialized();try{return await this.accessibilityTester.validateWCAGLevel(e,r)}catch(i){return this.handleError(i)}}async checkKeyboardNavigation(e){this.ensureInitialized();try{return await this.accessibilityTester.checkKeyboardNavigation(e)}catch(r){return this.handleError(r)}}async testResponsiveness(e,r){this.ensureInitialized();try{return await this.responsiveTester.testResponsiveness(e,r)}catch(i){return this.handleError(i)}}async analyzeBreakpoints(e){this.ensureInitialized();try{return await this.responsiveTester.analyzeBreakpoints(e)}catch(r){return this.handleError(r)}}async handleDeploymentCompleted(e){let r=e.payload;await this.memory.set(`visual-accessibility:deployment:${Date.now()}`,r,{namespace:"visual-accessibility",ttl:3600})}async handleFileChanged(e){let r=e.payload;(r.file.endsWith(".css")||r.file.endsWith(".scss"))&&await this.memory.set(`visual-accessibility:style-change:${Date.now()}`,r,{namespace:"visual-accessibility",ttl:3600})}async handleQualityGateTriggered(e){let r=e.payload;r.checks.includes("accessibility")&&await this.memory.set(`visual-accessibility:quality-gate:${r.gateId}`,{pending:!0,timestamp:Date.now()},{namespace:"visual-accessibility",ttl:3600})}ensureInitialized(){if(!this._initialized)throw new Error("VisualAccessibilityPlugin is not initialized");if(!this.coordinator||!this.visualTester||!this.accessibilityTester||!this.responsiveTester)throw new Error("VisualAccessibilityPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulTest(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,total:i.agents.total+1,idle:i.agents.idle+1},lastActivity:new Date})}trackFailedTest(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}registerWorkflowActions(e){if(!this._initialized)throw new Error("VisualAccessibilityPlugin must be initialized before registering workflow actions");e.registerAction("visual-accessibility","runVisualTest",async(r,i)=>{try{this.ensureInitialized();let n=this.extractUrls(r);if(n.length===0)return g(new Error('No URLs provided for visual test. Provide "url" or "urls" parameter.'));let s=this.extractViewports(r),a=await this.coordinator.runVisualTests(n,s);return a.success?f({passed:a.value.passed,failed:a.value.failed,totalTests:a.value.totalTests,newBaselines:a.value.newBaselines,duration:a.value.duration,results:a.value.results.map(o=>({url:o.url,viewport:`${o.viewport.width}x${o.viewport.height}`,status:o.status,diffPercentage:o.diff?.diffPercentage}))}):g(a.error)}catch(n){return g(y(n))}}),e.registerAction("visual-accessibility","runAccessibilityTest",async(r,i)=>{try{this.ensureInitialized();let n=this.extractUrls(r);if(n.length===0)return g(new Error('No URLs provided for accessibility test. Provide "url" or "urls" parameter.'));let s=this.extractWcagLevel(r),a=await this.coordinator.runAccessibilityAudit(n,s);return a.success?f({totalUrls:a.value.totalUrls,passingUrls:a.value.passingUrls,totalViolations:a.value.totalViolations,criticalViolations:a.value.criticalViolations,averageScore:a.value.averageScore,topIssues:a.value.topIssues.map(o=>({ruleId:o.ruleId,description:o.description,occurrences:o.occurrences,impact:o.impact}))}):g(a.error)}catch(n){return g(y(n))}})}extractUrls(e){return typeof e.url=="string"?[e.url]:Array.isArray(e.urls)?e.urls.filter(r=>typeof r=="string"):typeof e.target=="string"?[e.target]:[]}extractViewports(e){let r=[{width:1920,height:1080,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},{width:1280,height:720,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},{width:768,height:1024,deviceScaleFactor:2,isMobile:!0,hasTouch:!0},{width:375,height:812,deviceScaleFactor:3,isMobile:!0,hasTouch:!0}];if(Array.isArray(e.viewports))return e.viewports.filter(i=>typeof i=="object"&&i!==null).map(i=>({width:typeof i.width=="number"?i.width:1920,height:typeof i.height=="number"?i.height:1080,deviceScaleFactor:typeof i.deviceScaleFactor=="number"?i.deviceScaleFactor:1,isMobile:typeof i.isMobile=="boolean"?i.isMobile:!1,hasTouch:typeof i.hasTouch=="boolean"?i.hasTouch:!1}));if(typeof e.viewport=="object"&&e.viewport!==null){let i=e.viewport;return[{width:typeof i.width=="number"?i.width:1920,height:typeof i.height=="number"?i.height:1080,deviceScaleFactor:typeof i.deviceScaleFactor=="number"?i.deviceScaleFactor:1,isMobile:typeof i.isMobile=="boolean"?i.isMobile:!1,hasTouch:typeof i.hasTouch=="boolean"?i.hasTouch:!1}]}return r}extractWcagLevel(e){let i=(e.level??e.wcagLevel??"AA").toUpperCase();return i==="A"||i==="AA"||i==="AAA"?i:"AA"}};function jv(c,t,e,r,i){return new im(c,t,e,r,i)}_();k();_();import*as Wv from"net";import{execFile as Hv}from"child_process";k();X();ge();Pe();var rk={defaultTimeout:6e4,maxConcurrentFaults:3,enableDryRun:!0,safetyCheckInterval:5e3,autoRollbackOnFailure:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},H=x.create("chaos-resilience/chaos-engineer"),Vi=class c{config;activeExperiments=new Map;activeFaults=new Map;httpClient;metricsCollector;stressWorkers=new Map;memory;llmRouter;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...rk,...e},this.httpClient=new gt,this.metricsCollector=Du()}async createExperiment(t){try{let e=this.validateExperiment(t);if(!e.success)return g(e.error);let r=await this.analyzeExperimentWithLLM(t);return r&&H.info(`LLM Analysis:
2991
2991
  ${r}`),await this.memory.set(`chaos:experiments:${t.id}`,t,{namespace:"chaos-resilience",persist:!0}),f(t.id)}catch(e){return g(y(e))}}async runExperiment(t){try{let e=await this.memory.get(`chaos:experiments:${t}`);if(!e)return g(new Error(`Experiment not found: ${t}`));if(this.activeExperiments.has(t))return g(new Error(`Experiment ${t} is already running`));let r=this.createExecution(e);this.activeExperiments.set(t,r);try{let i=await this.verifySteadyState(e.steadyState);if(!i.success||!i.value)return r.result.steadyStateVerified=!1,r.result.status="failed",r.result.incidents.push({type:"error",severity:"high",message:"Initial steady state verification failed",timestamp:new Date,resolved:!1}),f(this.finalizeExecution(r));r.result.steadyStateVerified=!0;for(let a of e.faults){let o=await this.injectFault(a);o.success?r.result.faultResults.push(o.value):r.result.faultResults.push({faultId:a.id,injected:!1,duration:0,affectedTargets:0,errors:[o.error.message]})}await this.collectMetricsDuringExperiment(r,e);let n=await this.verifySteadyState(e.steadyState),s=n.success?n.value:!1;r.result.hypothesisValidated=this.validateHypothesis(e.hypothesis,r.result.metrics),r.result.status=this.determineExperimentStatus(r,s);for(let a of e.faults)await this.removeFault(a.id);return f(this.finalizeExecution(r))}catch(i){return r.result.status="failed",r.result.incidents.push({type:"error",severity:"critical",message:P(i),timestamp:new Date,resolved:!1}),this.config.autoRollbackOnFailure&&(await this.rollbackExperiment(e),r.result.status="rolled-back"),f(this.finalizeExecution(r))}finally{this.activeExperiments.delete(t)}}catch(e){return g(y(e))}}async abortExperiment(t,e){try{let r=this.activeExperiments.get(t);if(!r)return g(new Error(`No active experiment found: ${t}`));r.result.status="aborted",r.result.incidents.push({type:"alert",severity:"medium",message:`Experiment aborted: ${e}`,timestamp:new Date,resolved:!0});let i=await this.memory.get(`chaos:experiments:${t}`);if(i)for(let n of i.faults)await this.removeFault(n.id);return f(void 0)}catch(r){return g(y(r))}}async verifySteadyState(t){try{let e=[];for(let i of t.probes){let n=await this.executeProbe(i);e.push(n)}let r=e.every(i=>i);return f(r)}catch(e){return g(y(e))}}async injectFault(t){try{if(this.activeFaults.size>=this.config.maxConcurrentFaults)return g(new Error(`Maximum concurrent faults (${this.config.maxConcurrentFaults}) reached`));let e=this.validateFault(t);if(!e.success)return g(e.error);let r=Date.now();if(t.probability!==void 0&&z()>t.probability)return f({faultId:t.id,injected:!1,duration:0,affectedTargets:0,errors:["Skipped due to probability check"]});let i=await this.performFaultInjection(t);return i.success?(this.activeFaults.set(t.id,t),t.duration>0&&setTimeout(()=>{this.removeFault(t.id)},t.duration),f({faultId:t.id,injected:!0,duration:Date.now()-r,affectedTargets:i.value,errors:[]})):f({faultId:t.id,injected:!1,duration:Date.now()-r,affectedTargets:0,errors:[i.error.message]})}catch(e){return g(y(e))}}async removeFault(t){try{let e=this.activeFaults.get(t);return e?(await this.performFaultRemoval(e),this.activeFaults.delete(t),f(void 0)):f(void 0)}catch(e){return g(y(e))}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(t){return ae(t)}async analyzeExperimentWithLLM(t){if(!this.isLLMAnalysisAvailable())return null;try{return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze this chaos experiment hypothesis and provide recommendations:
2992
2992
  Experiment: ${t.name}
2993
2993
  Hypothesis: ${t.hypothesis.statement}
@@ -2997,15 +2997,15 @@ Fault Types: ${t.faults.map(r=>`${r.type} targeting ${r.target.type}:${r.target.
2997
2997
  Provide:
2998
2998
  1. Hypothesis validation likelihood
2999
2999
  2. Potential risks
3000
- 3. Recommended safety measures`}],maxTokens:this.config.llmMaxTokens})).content}catch{return H.warn("LLM analysis failed:"),null}}validateExperiment(t){return t.id?t.name?t.hypothesis?!t.steadyState||t.steadyState.probes.length===0?g(new Error("At least one steady state probe is required")):!t.faults||t.faults.length===0?g(new Error("At least one fault injection is required")):t.rollbackPlan?t.blastRadius.excludeProduction===!1&&!t.rollbackPlan.automatic?g(new Error("Production experiments require automatic rollback")):f(void 0):g(new Error("Rollback plan is required")):g(new Error("Experiment hypothesis is required")):g(new Error("Experiment name is required")):g(new Error("Experiment ID is required"))}validateFault(t){return t.id?t.type?t.target?t.duration<0?g(new Error("Fault duration must be non-negative")):t.probability!==void 0&&(t.probability<0||t.probability>1)?g(new Error("Fault probability must be between 0 and 1")):f(void 0):g(new Error("Fault target is required")):g(new Error("Fault type is required")):g(new Error("Fault ID is required"))}createExecution(t){return{experimentId:t.id,startTime:new Date,result:{experimentId:t.id,status:"running",startTime:new Date,hypothesisValidated:!1,steadyStateVerified:!1,faultResults:[],metrics:[],incidents:[]}}}finalizeExecution(t){t.result.endTime=new Date;let e={experimentId:t.result.experimentId,status:t.result.status,startTime:t.result.startTime,endTime:t.result.endTime,hypothesisValidated:t.result.hypothesisValidated,steadyStateVerified:t.result.steadyStateVerified,faultResults:t.result.faultResults,metrics:t.result.metrics,incidents:t.result.incidents};return this.memory.set(`chaos:results:${t.experimentId}:${Date.now()}`,e,{namespace:"chaos-resilience",persist:!0}),e}async executeProbe(t){try{switch(t.type){case"http":return await this.executeHttpProbe(t);case"tcp":return await this.executeTcpProbe(t);case"command":return await this.executeCommandProbe(t);case"metric":return await this.executeMetricProbe(t);default:return!1}}catch{return!1}}async executeHttpProbe(t){try{let e=await this.httpClient.get(t.target,{timeout:t.timeout??5e3,retries:1,circuitBreaker:!1});if(!e.success)return H.info(`HTTP probe failed: ${t.name} -> ${e.error.message}`),!1;let r=e.value;if(t.expectedStatus!==void 0){let i=r.status===t.expectedStatus;return i||H.info(`HTTP probe ${t.name}: expected status ${t.expectedStatus}, got ${r.status}`),i}return r.ok}catch(e){return H.info(`HTTP probe error: ${t.name} -> ${P(e)}`),!1}}async executeTcpProbe(t){return new Promise(e=>{try{let[r,i]=t.target.split(":"),n=parseInt(i,10);if(!r||isNaN(n)){H.info(`TCP probe invalid target: ${t.target} (expected host:port)`),e(!1);return}let s=t.timeout??5e3,a=new Wv.Socket,o=setTimeout(()=>{a.destroy(),H.info(`TCP probe timeout: ${t.name} -> ${t.target}`),e(!1)},s);a.connect(n,r,()=>{clearTimeout(o),a.destroy(),e(!0)}),a.on("error",l=>{clearTimeout(o),a.destroy(),H.info(`TCP probe error: ${t.name} -> ${l.message}`),e(!1)})}catch(r){H.info(`TCP probe exception: ${t.name} -> ${P(r)}`),e(!1)}})}static ALLOWED_PROBE_COMMANDS=["curl","wget","nc","netcat","ping","nslookup","dig","ps","pgrep","cat","head","tail","ls","stat","echo","test","[","node","npm"];async executeCommandProbe(t){return new Promise(e=>{let r=t.timeout??1e4,i=Qo(t.target,c.ALLOWED_PROBE_COMMANDS);if(!i.valid){H.info(`Command probe ${t.name} blocked: ${i.error}`),H.info(`Blocked patterns: ${i.blockedPatterns?.join(", ")||"none"}`),e(!1);return}let s=(i.sanitizedCommand||t.target).trim().split(/\s+/),a=s[0],o=s.slice(1);Hv(a,o,{timeout:r},(l,u,d)=>{if(l){H.info(`Command probe failed: ${t.name} -> ${l.message}`),e(!1);return}if(t.expectedOutput!==void 0){let m=u.trim().includes(t.expectedOutput);m||H.info(`Command probe ${t.name}: output did not contain expected value`),e(m);return}e(!0)})})}async executeMetricProbe(t){try{let e=await this.httpClient.get(t.target,{timeout:t.timeout??5e3,retries:1,circuitBreaker:!1});if(!e.success)return H.info(`Metric probe failed: ${t.name} -> ${e.error.message}`),!1;let r=e.value;if(!r.ok)return H.info(`Metric probe HTTP error: ${t.name} -> ${r.status}`),!1;let i=await r.text(),n;try{let s=D(i);n=typeof s.value=="number"?s.value:parseFloat(s.value)}catch{n=parseFloat(i)}if(isNaN(n))return H.info(`Metric probe ${t.name}: could not parse metric value from response`),!1;if(t.threshold!==void 0){let{operator:s,value:a}=t.threshold;switch(s){case"lt":return n<a;case"gt":return n>a;case"lte":return n<=a;case"gte":return n>=a;case"eq":return n===a;default:return!0}}return!0}catch(e){return H.info(`Metric probe error: ${t.name} -> ${P(e)}`),!1}}async performFaultInjection(t){let r={latency:async()=>this.injectLatency(t),error:async()=>this.injectError(t),timeout:async()=>this.injectTimeout(t),"packet-loss":async()=>this.injectPacketLoss(t),"cpu-stress":async()=>this.injectCpuStress(t),"memory-stress":async()=>this.injectMemoryStress(t),"disk-stress":async()=>this.injectDiskStress(t),"network-partition":async()=>this.injectNetworkPartition(t),"dns-failure":async()=>this.injectDnsFailure(t),"process-kill":async()=>this.injectProcessKill(t)}[t.type];return r?r():g(new Error(`Unknown fault type: ${t.type}`))}async injectLatency(t){let e=t.parameters.latencyMs??100;return H.info(`Latency injection configured: ${e}ms for ${t.target.selector}`),H.info("Note: Actual latency injection requires network proxy (e.g., Toxiproxy, tc)"),f(1)}async injectError(t){let e=t.parameters.errorCode??500;return H.info(`Error injection configured: ${e} for ${t.target.selector}`),H.info("Note: Actual error injection requires service mesh (e.g., Istio, Linkerd)"),f(1)}async injectTimeout(t){return H.info(`Timeout injection configured for ${t.target.selector}`),H.info("Note: Actual timeout injection requires network proxy configuration"),f(1)}async injectPacketLoss(t){let e=t.parameters.packetLossPercent??10;return H.info(`Packet loss configured: ${e}% for ${t.target.selector}`),H.info("Note: Actual packet loss requires tc/iptables (Linux) or similar"),f(1)}async injectCpuStress(t){let e=t.parameters.cpuPercent??80,r=t.parameters.cores??1,i=t.duration;H.info(`Injecting CPU stress: ${e}% on ${r} core(s) for ${i}ms`);let n=Date.now(),s=setInterval(()=>{if(Date.now()-n>=i){clearInterval(s);return}let a=10*(e/100),o=Date.now();for(;Date.now()-o<a;)z()*z()},10);return this.stressWorkers.set(t.id,s),f(r)}async injectMemoryStress(t){let e=t.parameters.memoryBytes??104857600,r=Math.round(e/(1024*1024));H.info(`Injecting memory stress: ${r}MB allocation`);try{let n=Math.ceil(e/1048576),s=[];for(let a=0;a<n;a++){let o=Math.min(1048576,e-a*1048576),l=new Array(o).fill(z());s.push(l)}return this.stressWorkers.set(t.id,s),H.info(`Memory stress active: ${s.length} chunks allocated`),f(1)}catch(i){return g(new Error(`Failed to allocate memory: ${P(i)}`))}}async injectDiskStress(t){return H.info(`Disk stress configured for ${t.target.selector}`),H.info("Note: Actual disk stress requires file system write permissions"),f(1)}async injectNetworkPartition(t){return H.info(`Network partition configured for ${t.target.selector}`),H.info("Note: Actual network partition requires iptables/firewall rules"),f(1)}async injectDnsFailure(t){return H.info(`DNS failure configured for ${t.target.selector}`),H.info("Note: Actual DNS failure requires DNS server or /etc/hosts modification"),f(1)}async injectProcessKill(t){let e=t.target.selector;return H.info(`Process kill configured for pattern: ${e}`),H.info("Note: Actual process kill requires appropriate permissions"),this.config.enableDryRun?(H.info(`Would kill processes matching: ${e}`),f(0)):f(1)}async performFaultRemoval(t){H.info(`Removing fault: ${t.id} (${t.type})`);let e=this.stressWorkers.get(t.id);e&&(typeof e=="object"&&"unref"in e&&clearInterval(e),this.stressWorkers.delete(t.id))}async collectMetricsDuringExperiment(t,e){let r=e.hypothesis.metrics.map(s=>s.metric),i=Date.now(),n=Math.max(...e.faults.map(s=>s.duration),this.config.defaultTimeout);for(;Date.now()-i<Math.min(n,5e3);){for(let s of r){let a={timestamp:new Date,name:s,value:this.collectRealMetricValue(s),labels:{experiment:e.id}};t.result.metrics.push(a)}await this.sleep(this.config.safetyCheckInterval)}}collectRealMetricValue(t){return this.metricsCollector.getChaosMetricValue(t)}validateHypothesis(t,e){for(let r of t.metrics){let i=e.filter(s=>s.name===r.metric);if(i.length===0)return!1;let n=i.reduce((s,a)=>s+a.value,0)/i.length;if(!this.checkMetricExpectation(n,r))return!1}for(let r of t.tolerances){let i=e.filter(o=>o.name===r.metric);if(i.length===0)continue;let n=i.map(o=>o.value),s=this.calculateDeviation(n);if((r.unit==="percent"?s/n[0]*100:s)>r.maxDeviation)return!1}return!0}checkMetricExpectation(t,e){let{operator:r,value:i}=e;switch(r){case"eq":return t===i;case"lt":return t<i;case"gt":return t>i;case"lte":return t<=i;case"gte":return t>=i;case"between":{let[n,s]=i;return t>=n&&t<=s}default:return!1}}calculateDeviation(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n,0)/t.length,r=t.map(i=>Math.pow(i-e,2));return Math.sqrt(r.reduce((i,n)=>i+n,0)/t.length)}determineExperimentStatus(t,e){return!t.result.steadyStateVerified||!e?"failed":t.result.hypothesisValidated?"completed":t.result.faultResults.filter(i=>!i.injected).length>0?"failed":"completed"}async rollbackExperiment(t){for(let e of t.rollbackPlan.steps.sort((r,i)=>r.order-i.order)){H.info(`Executing rollback step ${e.order}: ${e.action}`);try{await this.executeRollbackAction(e.action,e.target,e.timeout)}catch(r){H.error(`Rollback step ${e.order} failed: ${P(r)}`)}}for(let e of t.faults)await this.removeFault(e.id)}async executeRollbackAction(t,e,r=3e4){t.startsWith("http://")||t.startsWith("https://")?await this.executeHttpRollback(t,r):t.startsWith("cmd:")?await this.executeCommandRollback(t.slice(4),r):e&&(e.startsWith("http://")||e.startsWith("https://"))?await this.executeHttpRollback(`${e}/_chaos/${t}`,r):await this.executeBuiltInRollback(t,e,r)}async executeHttpRollback(t,e){let r=await this.httpClient.post(t,{},{timeout:e,retries:1});if(!r.success)throw new Error(`HTTP rollback failed: ${r.error.message}`)}static ALLOWED_ROLLBACK_COMMANDS=["kill","pkill","rm","rmdir","mv","cp","systemctl","service","docker","kubectl","iptables","tc","echo","true"];executeCommandRollback(t,e){return new Promise((r,i)=>{let n=Qo(t,c.ALLOWED_ROLLBACK_COMMANDS);if(!n.valid){i(new Error(`Rollback command blocked: ${n.error}`));return}let a=(n.sanitizedCommand||t).trim().split(/\s+/),o=a[0],l=a.slice(1);Hv(o,l,{timeout:e},(u,d,m)=>{u?i(new Error(`Command rollback failed: ${u.message}. ${m}`)):r()})})}async executeBuiltInRollback(t,e,r){let i=t.toLowerCase();i.includes("remove")||i.includes("clear")?e&&H.info(`Clearing state for target: ${e}`):i.includes("restart")?H.info(`Restart requested for: ${e||"service"}`):i.includes("restore")?H.info(`Restore requested for: ${e||"system"}`):H.info(`Rollback action logged: ${t}`),await this.sleep(100)}sleep(t){return new Promise(e=>setTimeout(e,t))}};k();ge();var rk={defaultTimeout:3e5,maxVirtualUsers:1e3,reportingInterval:1e3,enableDetailedMetrics:!0,connectionPoolSize:100},zi=class{constructor(t,e={}){this.memory=t;this.config={...rk,...e},this.httpClient=new gt}memory;config;activeTests=new Map;httpClient;async createTest(t){try{let e=this.validateTest(t);return e.success?(await this.memory.set(`loadtest:tests:${t.id}`,t,{namespace:"chaos-resilience",persist:!0}),f(t.id)):g(e.error)}catch(e){return g(y(e))}}async runTest(t){try{let e=await this.memory.get(`loadtest:tests:${t}`);if(!e)return g(new Error(`Load test not found: ${t}`));if(this.activeTests.has(t))return g(new Error(`Load test ${t} is already running`));if(e.profile.virtualUsers.max>this.config.maxVirtualUsers)return g(new Error(`Virtual users (${e.profile.virtualUsers.max}) exceeds maximum (${this.config.maxVirtualUsers})`));let r=this.createExecution(e);this.activeTests.set(t,r);try{return await this.executeLoadTest(r,e),r.result.assertionResults=this.evaluateAssertions(e.assertions,r.result.summary),r.result.status=this.determineTestStatus(r.result),f(this.finalizeExecution(r))}catch(i){return r.result.status="failed",r.result.errors.push({type:"execution_error",message:P(i),count:1,firstOccurrence:new Date,lastOccurrence:new Date}),f(this.finalizeExecution(r))}finally{this.activeTests.delete(t)}}catch(e){return g(y(e))}}async stopTest(t){try{let e=this.activeTests.get(t);return e?(e.aborted=!0,e.result.status="aborted",f(this.finalizeExecution(e))):g(new Error(`No active load test found: ${t}`))}catch(e){return g(y(e))}}async getRealtimeMetrics(t){try{let e=this.activeTests.get(t);if(!e)return g(new Error(`No active load test found: ${t}`));let r=e.result.timeline[e.result.timeline.length-1];return r?f(r):g(new Error("No metrics available yet"))}catch(e){return g(y(e))}}async generateFromTraffic(t,e){try{if(t.requests.length===0)return g(new Error("Traffic sample contains no requests"));if(e<=0)return g(new Error("Multiplier must be positive"));let r=t.requests.reduce((p,h)=>p+h.frequency,0),i=t.requests.reduce((p,h)=>p+h.avgResponseTime*h.frequency,0)/r,n=t.requests.map(p=>({name:`${p.method} ${p.url}`,weight:p.frequency/r,steps:[{type:"request",target:{url:p.url,method:p.method}},{type:"think",duration:Math.max(100,i*.5)}]})),a=r/t.duration*e,o=Math.ceil(a*(i/1e3)),l={virtualUsers:{start:Math.ceil(o*.1),max:Math.min(o,this.config.maxVirtualUsers),pattern:"ramp"},duration:Math.max(6e4,t.duration*e),rampUp:3e4,rampDown:15e3},u=[{metric:"p95",operator:"lt",value:i*2},{metric:"error-rate",operator:"lt",value:5},{metric:"throughput",operator:"gte",value:a*.9}],d=e>5?"stress":"load",m={id:w(),name:`Generated from ${t.source} (${e}x)`,type:d,target:{url:t.requests[0].url,method:t.requests[0].method},profile:l,scenarios:n,assertions:u};return f(m)}catch(r){return g(y(r))}}validateTest(t){return t.id?t.name?!t.target||!t.target.url?g(new Error("Test target URL is required")):t.profile?t.profile.virtualUsers.max<=0?g(new Error("Maximum virtual users must be positive")):t.profile.duration<=0?g(new Error("Test duration must be positive")):f(void 0):g(new Error("Test profile is required")):g(new Error("Test name is required")):g(new Error("Test ID is required"))}createExecution(t){return{testId:t.id,startTime:new Date,aborted:!1,result:{testId:t.id,status:"completed",duration:0,summary:this.createEmptySummary(),timeline:[],errors:[],assertionResults:[]}}}createEmptySummary(){return{totalRequests:0,successfulRequests:0,failedRequests:0,requestsPerSecond:0,avgResponseTime:0,p50ResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,maxResponseTime:0,errorRate:0}}async executeLoadTest(t,e){let r=Date.now(),i=e.profile.duration,n=[],s=new Map,a=this.getExecutionStrategy(e.type);for(;Date.now()-r<i&&!t.aborted;){let o=Date.now()-r,l=this.calculateCurrentVirtualUsers(e.profile,o,i),u=await this.executeBatch(e,l,a);n.push(...u.responseTimes);for(let m of u.errors){let p=s.get(m);p?(p.count++,p.lastOccurrence=new Date):s.set(m,{type:"request_error",message:m,count:1,firstOccurrence:new Date,lastOccurrence:new Date})}t.result.summary.totalRequests+=u.totalRequests,t.result.summary.successfulRequests+=u.successfulRequests,t.result.summary.failedRequests+=u.failedRequests;let d={timestamp:new Date,virtualUsers:l,requestsPerSecond:u.totalRequests,avgResponseTime:u.responseTimes.length>0?u.responseTimes.reduce((m,p)=>m+p,0)/u.responseTimes.length:0,errorRate:u.totalRequests>0?u.failedRequests/u.totalRequests*100:0};t.result.timeline.push(d),await this.sleep(this.config.reportingInterval)}if(t.result.duration=Date.now()-r,t.result.errors=Array.from(s.values()),n.length>0){let o=n.sort((l,u)=>l-u);t.result.summary.avgResponseTime=o.reduce((l,u)=>l+u,0)/o.length,t.result.summary.p50ResponseTime=this.percentile(o,50),t.result.summary.p95ResponseTime=this.percentile(o,95),t.result.summary.p99ResponseTime=this.percentile(o,99),t.result.summary.maxResponseTime=o[o.length-1]}t.result.summary.requestsPerSecond=t.result.summary.totalRequests/(t.result.duration/1e3),t.result.summary.errorRate=t.result.summary.totalRequests>0?t.result.summary.failedRequests/t.result.summary.totalRequests*100:0}getExecutionStrategy(t){switch(t){case"load":return{requestMultiplier:1,errorInjectionRate:0};case"stress":return{requestMultiplier:1.5,errorInjectionRate:.01};case"spike":return{requestMultiplier:3,errorInjectionRate:.02};case"soak":return{requestMultiplier:.8,errorInjectionRate:0};case"breakpoint":return{requestMultiplier:2,errorInjectionRate:.05};default:return{requestMultiplier:1,errorInjectionRate:0}}}calculateCurrentVirtualUsers(t,e,r){let{virtualUsers:i,rampUp:n=0,rampDown:s=0}=t,{start:a,max:o,pattern:l}=i;switch(l){case"constant":return o;case"ramp":if(e<n)return Math.round(a+(o-a)*(e/n));if(e>r-s){let u=(r-e)/s;return Math.round(a+(o-a)*u)}return o;case"step":{let d=r/5,m=Math.floor(e/d),p=(o-a)/5;return Math.round(a+p*m)}case"spike":return e%3e4<5e3?o:a;default:return o}}async executeBatch(t,e,r){let i=Math.round(e*r.requestMultiplier),n=Math.min(i,this.config.connectionPoolSize),s=this.createBatches(i,n),a=[];for(let u of s){let d=Date.now(),m=await Promise.all(u.map(()=>this.executeRequest(t,r)));a.push(...m);let p=Date.now()-d,h=1e3/Math.max(e,1)*u.length;p<h&&await this.sleep(h-p)}let o=a.filter(u=>u.success).map(u=>u.latency),l=a.filter(u=>!u.success).map(u=>u.error||"Unknown error");return{totalRequests:a.length,successfulRequests:a.filter(u=>u.success).length,failedRequests:a.filter(u=>!u.success).length,responseTimes:o,errors:l}}async executeRequest(t,e){let r=Date.now(),i=r;if(e.errorInjectionRate>0&&z()<e.errorInjectionRate)return{status:0,latency:Date.now()-r,success:!1,error:"Simulated error injection",timestamp:i};try{let{url:n,method:s="GET",headers:a,body:o}=t.target,l={headers:a,timeout:this.config.defaultTimeout,retries:0,circuitBreaker:!1},u;switch(s.toUpperCase()){case"POST":u=await this.httpClient.post(n,o,l);break;case"PUT":u=await this.httpClient.put(n,o,l);break;case"DELETE":u=await this.httpClient.delete(n,l);break;default:u=await this.httpClient.get(n,l);break}if(u.success){let d=u.value;return{status:d.status,latency:Date.now()-r,success:d.ok,error:d.ok?void 0:`HTTP ${d.status}: ${d.statusText}`,timestamp:i}}else return{status:u.error.status??0,latency:Date.now()-r,success:!1,error:u.error.message,timestamp:i}}catch(n){return{status:0,latency:Date.now()-r,success:!1,error:P(n),timestamp:i}}}createBatches(t,e){let r=[],i=t;for(;i>0;){let n=Math.min(i,e);r.push(Array.from({length:n},(s,a)=>a)),i-=n}return r}percentile(t,e){if(t.length===0)return 0;let r=Math.ceil(e/100*t.length)-1;return t[Math.max(0,Math.min(r,t.length-1))]}evaluateAssertions(t,e){return t.map(r=>{let i=this.getMetricValue(r.metric,e),n=this.checkAssertion(r,i);return{assertion:r,passed:n,actualValue:i}})}getMetricValue(t,e){switch(t){case"response-time":return e.avgResponseTime;case"throughput":return e.requestsPerSecond;case"error-rate":return e.errorRate;case"p95":return e.p95ResponseTime;case"p99":return e.p99ResponseTime;default:return 0}}checkAssertion(t,e){switch(t.operator){case"lt":return e<t.value;case"gt":return e>t.value;case"lte":return e<=t.value;case"gte":return e>=t.value;default:return!1}}determineTestStatus(t){return t.status==="aborted"?"aborted":t.assertionResults.filter(r=>!r.passed).length>0||t.summary.errorRate>10?"failed":"completed"}finalizeExecution(t){let e={testId:t.result.testId,status:t.result.status,duration:t.result.duration,summary:t.result.summary,timeline:t.result.timeline,errors:t.result.errors,assertionResults:t.result.assertionResults};return this.memory.set(`loadtest:results:${t.testId}:${Date.now()}`,e,{namespace:"chaos-resilience",persist:!0}),e}sleep(t){return new Promise(e=>setTimeout(e,t))}};_();k();ge();X();var ik={defaultTimeout:6e4,healthCheckInterval:1e3,maxRetries:3,recoveryCheckDelay:500,simulateRandomFailures:!1},cr=x.create("chaos-resilience/performance-profiler"),Bi=class{constructor(t,e={}){this.memory=t;this.config={...ik,...e},this.httpClient=is()}memory;config;httpClient;async testRecovery(t,e,r){let i=w();try{let n=[],s=await this.checkServiceHealth(t);if(n.push({timestamp:new Date,event:"Initial health check",status:s?"healthy":"unhealthy"}),!s)return f({service:t,faultType:e,recoveryTime:0,expectedRecoveryTime:r,passed:!1,timeline:n});n.push({timestamp:new Date,event:`Injecting fault: ${e}`,status:"degraded"}),await this.injectFault(t,e);let a=await this.checkServiceHealth(t);n.push({timestamp:new Date,event:"Post-fault health check",status:a?"healthy":"unhealthy"}),n.push({timestamp:new Date,event:"Removing fault",status:"degraded"}),await this.removeFault(t,e);let o=Date.now(),l=0,u=!1,d=r*2;for(;Date.now()-o<d;){if(await this.checkServiceHealth(t)){l=Date.now()-o,u=!0,n.push({timestamp:new Date,event:"Service recovered",status:"healthy"});break}n.push({timestamp:new Date,event:"Recovery check - still degraded",status:"degraded"}),await this.sleep(this.config.recoveryCheckDelay)}u||n.push({timestamp:new Date,event:"Recovery timeout exceeded",status:"unhealthy"});let m={service:t,faultType:e,recoveryTime:l,expectedRecoveryTime:r,passed:u&&l<=r,timeline:n};return await this.storeTestResult("recovery",i,m),f(m)}catch(n){return g(y(n))}}async testFailover(t,e){let r=w();try{let i=[],n=1,[s,a]=await Promise.all([this.checkServiceHealth(t),this.checkServiceHealth(e)]);if(i.push({order:n++,action:"Verify primary service health",duration:0,success:s}),i.push({order:n++,action:"Verify secondary service health",duration:0,success:a}),!s||!a)return f({primaryService:t,secondaryService:e,failoverTime:0,dataLoss:!0,passed:!1,steps:i});let o=await this.captureServiceState(t);i.push({order:n++,action:"Capture primary service state",duration:0,success:!0});let l=Date.now();await this.injectFault(t,"process-kill"),i.push({order:n++,action:"Trigger primary service failure",duration:Date.now()-l,success:!0});let u=Date.now(),d=!1,m=0;for(;Date.now()-u<this.config.defaultTimeout;){if(await this.checkServiceIsActive(e)){m=Date.now()-l,d=!0;break}await this.sleep(this.config.healthCheckInterval)}i.push({order:n++,action:"Detect failover completion",duration:m,success:d});let p=await this.captureServiceState(e),h=!this.compareServiceStates(o,p);i.push({order:n++,action:"Verify data integrity on secondary",duration:0,success:!h}),await this.removeFault(t,"process-kill"),i.push({order:n++,action:"Restore primary service",duration:0,success:!0});let v={primaryService:t,secondaryService:e,failoverTime:m,dataLoss:h,passed:d&&!h,steps:i};return await this.storeTestResult("failover",r,v),f(v)}catch(i){return g(y(i))}}async testCircuitBreaker(t,e){let r=w();try{let i=e?.errorThreshold??5,n=e?.timeout??this.config.defaultTimeout,s=e?.halfOpenRequests??3;await this.getCircuitState(t)!=="closed"&&await this.resetCircuit(t);let o=0,l=!1;for(let b=0;b<i*2;b++)if(await this.generateError(t),o++,await this.getCircuitState(t)==="open"){l=!0;break}let u=!1,d=Date.now();for(;Date.now()-d<n;){if(await this.getCircuitState(t)==="half-open"){u=!0;break}await this.sleep(this.config.healthCheckInterval)}let m="correct";if(u){let b=0;for(let S=0;S<s;S++)await this.sendSuccessfulRequest(t)&&b++;await this.getCircuitState(t)!=="closed"&&b===s&&(m="incorrect")}let p=!1,h=Date.now();for(;Date.now()-h<n;){if(await this.getCircuitState(t)==="closed"){p=!0;break}await this.sendSuccessfulRequest(t),await this.sleep(this.config.healthCheckInterval)}let v={service:t,opened:l,openedAfterErrors:o,closedAfterRecovery:p,halfOpenBehavior:m,passed:l&&p&&m==="correct"};return await this.storeTestResult("circuit-breaker",r,v),f(v)}catch(i){return g(y(i))}}async testRateLimiting(t,e){let r=w();try{let i=0,n={statusCode:429,retryAfter:void 0,body:void 0},s=[1,5,10,25,50,100,200],a=0,o=!1;for(let m of s){if(o)break;let p=await this.sendRequestBatch(t,m);a+=m;for(let h of p)if(h.statusCode===429){o=!0,i=a-(m-p.indexOf(h)),n=h;break}}o||(i=a);let l=e*.2,u=Math.abs(i-e)<=l||!o,d={service:t,expectedLimit:e,actualLimit:i,passed:o&&u,responseWhenLimited:n};return await this.storeTestResult("rate-limit",r,d),f(d)}catch(i){return g(y(i))}}async checkServiceHealth(t){if(!this.isRealServiceUrl(t))return this.simulateHealthCheck();try{return await this.httpClient.healthCheck(t)}catch{return this.simulateHealthCheck()}}isRealServiceUrl(t){return t.startsWith("http://")||t.startsWith("https://")}simulateHealthCheck(){return this.config.simulateRandomFailures?z()>.05:!0}async checkServiceIsActive(t){if(!this.isRealServiceUrl(t))return this.simulateServiceActive();try{let e=await this.httpClient.get(t,{timeout:5e3,retries:1});return e.success&&e.value.ok}catch{return this.simulateServiceActive()}}simulateServiceActive(){return this.config.simulateRandomFailures?z()>.1:!0}async injectFault(t,e){if(this.isRealServiceUrl(t))try{let r=`${t}/_chaos/inject`;await this.httpClient.post(r,{faultType:e},{timeout:5e3,retries:0});return}catch{cr.debug("Fault injection API failed:")}cr.info(`Injecting fault ${e} into service: ${t}`),await this.sleep(100)}async removeFault(t,e){if(this.isRealServiceUrl(t))try{let r=`${t}/_chaos/remove`;await this.httpClient.post(r,{faultType:e},{timeout:5e3,retries:0});return}catch{cr.debug("Fault removal API failed:")}cr.info(`Removing fault ${e} from service: ${t}`),await this.sleep(50)}async captureServiceState(t){if(this.isRealServiceUrl(t))try{let r=`${t}/_state`,i=await this.httpClient.get(r,{timeout:5e3,retries:1});if(i.success&&i.value.ok){let n=await i.value.text(),s=this.calculateChecksum(n),a=this.parseRecordCount(n);return{checksum:s,timestamp:new Date,records:a}}}catch{cr.debug("State capture API failed:")}return await this.captureMemoryState(t)}calculateChecksum(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return`chk_${Math.abs(e).toString(16)}`}parseRecordCount(t){try{let e=D(t);return e.records??e.count??e.total??e.length??0}catch{return t.split(`
3001
- `).filter(e=>e.trim()).length}}async captureMemoryState(t){let e=`resilience:state:${this.hashServiceName(t)}`,r=await this.memory.get(e);if(r)return r;let i={checksum:`init_${w().slice(0,8)}`,timestamp:new Date,records:0};return await this.memory.set(e,i,{namespace:"chaos-resilience"}),i}hashServiceName(t){let e=0;for(let r of t)e=(e<<5)-e+r.charCodeAt(0),e=e&e;return Math.abs(e).toString(16)}compareServiceStates(t,e){let r=t.checksum===e.checksum,i=t.records===e.records;return r||i}async getCircuitState(t){try{return this.httpClient.getCircuitState(t).state}catch{return"closed"}}async resetCircuit(t){try{this.httpClient.resetCircuit(t)}catch{cr.info(`Resetting circuit breaker for: ${t}`)}}async generateError(t){if(this.isRealServiceUrl(t))try{let e=`${t}/_chaos/error`;await this.httpClient.post(e,{},{timeout:5e3,retries:0});return}catch{cr.debug("Error generation API failed:")}cr.info(`Generating error for: ${t}`)}async sendSuccessfulRequest(t){if(!this.isRealServiceUrl(t))return!0;try{let e=await this.httpClient.get(t,{timeout:5e3,retries:1});return e.success&&e.value.ok}catch{return!0}}async sendRequestBatch(t,e){let r=[];if(!this.isRealServiceUrl(t))return this.simulateRequestBatch(e);for(let i=0;i<e;i++)try{let n=await this.httpClient.get(t,{timeout:2e3,retries:0,circuitBreaker:!1});if(n.success){let s=n.value,a=s.headers.get("Retry-After");r.push({statusCode:s.status,retryAfter:a?parseInt(a,10):void 0})}else r.push({statusCode:500,body:{error:n.error.message}})}catch{return[...r,...this.simulateRequestBatch(e-i)]}return r}simulateRequestBatch(t){let e=[];for(let i=0;i<t;i++)i>=75?e.push({statusCode:429,retryAfter:60,body:{error:"Rate limit exceeded"}}):e.push({statusCode:200});return e}async storeTestResult(t,e,r){await this.memory.set(`resilience:${t}:${e}`,r,{namespace:"chaos-resilience",persist:!0})}sleep(t){return new Promise(e=>setTimeout(e,t))}};ge();var nk={stateSize:10,actionSize:5,hiddenLayers:[64,64],learningRatePG:.01,gammaPG:.99,entropyCoeff:.01},Rc=class extends ve{policy;pgConfig;actions=[];episodeLog=[];constructor(t={}){super("policy-gradient","policy-based"),this.pgConfig={...nk,...t},this.initializeActions(),this.policy=new J({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.pgConfig.learningRatePG})}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.policy.forward(e),i=Ie.forward(r),n=this.sampleAction(i),s=this.actions[n],a=i[n],o=Math.max(.3,Math.min(1,a+.4));return this.episodeLog.push({state:t,action:s,reward:0}),{action:s,confidence:o,reasoning:this.generateReasoning(t,s,a)}}async trainCore(t){let e=this.groupIntoEpisodes(t),r=0;for(let i of e){let n=this.calculateReturns(i);for(let s=0;s<i.length;s++){let{state:a,action:o}=i[s],l=n[s],u=this.prepareState(a),d=this.policy.forward(u),m=Ie.forward(d),p=this.actionToIndex(o),v=-Math.log(m[p]+1e-10)*l;r+=Math.abs(v);let b=new Float32Array(m.length);for(let C=0;C<b.length;C++)C===p?b[C]=-l*(1-m[C]):b[C]=l*m[C];this.policy.backward(b);for(let C of this.policy.layers)C.update(this.pgConfig.learningRatePG)}}return this.episodeLog=[],{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/t.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural Policy Gradient (REINFORCE) for Resource Allocation",capabilities:["Neural policy optimization","Monte Carlo return estimation","Entropy regularization"],hyperparameters:{stateSize:this.pgConfig.stateSize,actionSize:this.pgConfig.actionSize,learningRatePG:this.pgConfig.learningRatePG,gammaPG:this.pgConfig.gammaPG},stats:this.stats}}prepareState(t){let e=t.features.slice(0,this.pgConfig.stateSize);for(;e.length<this.pgConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]=e[i]/r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"allocate",value:{agentType:"tester",count:1}},{type:"allocate",value:{agentType:"analyzer",count:1}},{type:"reallocate",value:{domain:"test-execution"}},{type:"scale-up",value:1},{type:"scale-down",value:1}],this.pgConfig.actionSize=this.actions.length,this.policy=new J({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.pgConfig.learningRatePG})}actionToIndex(t){let e=this.actionToKey(t);for(let r=0;r<this.actions.length;r++)if(this.actionToKey(this.actions[r])===e)return r;return 0}actionToKey(t){return`${t.type}:${JSON.stringify(t.value)}`}sampleAction(t){if(z()<this.config.explorationRate)return Se(0,this.actions.length);let e=z(),r=0;for(let i=0;i<t.length;i++)if(r+=t[i],e<=r)return i;return this.argmax(t)}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}calculateReturns(t){let e=[],r=0;for(let i=t.length-1;i>=0;i--)r=t[i].reward+this.pgConfig.gammaPG*r,e.unshift(r);return e}groupIntoEpisodes(t){let e=[],r=[];for(let i of t)r.push(i),i.done&&(e.push(r),r=[]);return r.length>0&&e.push(r),e}generateReasoning(t,e,r){return`Neural Policy Gradient: ${e.type} (probability: ${r.toFixed(3)})`}async exportCustomData(){return{policy:this.policy.getParameters(),pgConfig:this.pgConfig}}async importCustomData(t){t.policy&&this.policy.setParameters(t.policy),t.pgConfig&&(this.pgConfig={...this.pgConfig,...t.pgConfig}),this.initialized=!0}async resetAlgorithm(){this.policy=new J({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.pgConfig.learningRatePG}),this.episodeLog=[]}};var sk={maxConcurrentWorkflows:3,defaultTimeout:3e5,enableAutomatedExperiments:!1,publishEvents:!0,enablePolicyGradient:!0,enableQESONA:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},me=x.create("chaos-resilience"),Tc=class extends ie{constructor(e,r,i,n={},s){let a={...sk,...n};super(e,"chaos-resilience",a,{verifyFindingTypes:["chaos-experiment","resilience-assessment","failure-injection"],...a.consensusConfig});this.memory=r;this.agentCoordinator=i;this.chaosGovernanceMixin=_p(this.domainName),this.chaosEngineer=new Vi({memory:r,llmRouter:s}),this.loadTester=new zi(r),this.performanceProfiler=new Bi(r)}memory;agentCoordinator;chaosEngineer;loadTester;performanceProfiler;policyGradient;qesona;chaosGovernanceMixin;async onInitialize(){if(this.config.enablePolicyGradient)try{this.policyGradient=new Rc({stateSize:10,actionSize:5,hiddenLayers:[64,64]}),me.info("PolicyGradient algorithm created successfully")}catch(e){throw me.error("Failed to create PolicyGradient:",e instanceof Error?e:void 0),new Error(`PolicyGradient creation failed: ${P(e)}`)}if(this.config.enableQESONA)try{this.qesona=await De({domain:"chaos-resilience",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:5e3,minConfidence:.6}),me.info("PersistentSONAEngine initialized successfully")}catch(e){me.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),me.warn("Continuing without SONA pattern persistence"),this.qesona=void 0}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState(),this.qesona&&(await this.qesona.close(),this.qesona=void 0),this.policyGradient=void 0}getActiveWorkflows(){return super.getActiveWorkflows()}async runChaosSuite(e){let r=w();try{if(this.startWorkflow(r,"chaos-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&me.warn("Topology degraded, using conservative chaos strategy"),this.minCutMixin.shouldPauseOperations())return g(new Error("Chaos suite paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return g(new Error("Agent limit reached, cannot spawn chaos agents"));let i=await this.spawnChaosAgent(r,"coordinator");if(!i.success)return this.failWorkflow(r,i.error.message),g(i.error);this.addAgentToWorkflow(r,i.value);let n=[],s=[],a=0,o=0;for(let u=0;u<e.length;u++){let d=e[u];this.updateWorkflowProgress(r,Math.round((u+1)/e.length*100));let m=await this.chaosEngineer.runExperiment(d);if(m.success){if(n.push(m.value),m.value.hypothesisValidated)a++;else{o++;let p=this.generateRecommendationsFromExperiment(m.value);s.push(...p)}this.config.publishEvents&&await this.publishExperimentCompleted(m.value)}else o++,s.push({priority:"high",category:"experiment-failure",recommendation:`Failed to run experiment ${d}: ${m.error.message}`,effort:"moderate"})}await this.agentCoordinator.stop(i.value),this.completeWorkflow(r);let l={totalExperiments:e.length,passed:a,failed:o,results:n,recommendations:s};return await this.storeReport("chaos-suite",r,l),f(l)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async runLoadTestSuite(e){let r=w();try{if(this.startWorkflow(r,"load-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&me.warn("Topology degraded, using conservative load test parameters"),this.minCutMixin.shouldPauseOperations())return g(new Error("Load test suite paused: topology is in critical state"));let i=await this.spawnLoadTestAgent(r,"orchestrator");if(!i.success)return this.failWorkflow(r,i.error.message),g(i.error);this.addAgentToWorkflow(r,i.value);let n=[],s=[],a=0,o=0;for(let u=0;u<e.length;u++){let d=e[u];this.updateWorkflowProgress(r,Math.round((u+1)/e.length*100));let m=await this.loadTester.runTest(d);if(m.success){n.push(m.value),m.value.status==="completed"?a++:o++;let p=this.detectBottlenecks(m.value);s.push(...p),this.config.publishEvents&&await this.publishLoadTestCompleted(m.value)}else o++}await this.agentCoordinator.stop(i.value),this.completeWorkflow(r);let l={totalTests:e.length,passed:a,failed:o,results:n,bottlenecks:s};return await this.storeReport("load-suite",r,l),f(l)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async assessResilience(e){let r=w();try{if(this.startWorkflow(r,"assessment"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&me.warn("Topology degraded, assessment may be limited"),this.minCutMixin.shouldPauseOperations())return g(new Error("Resilience assessment paused: topology is in critical state"));let i=new Map,n=[],s=[],a=[],o=await this.spawnAssessmentAgent(r);if(!o.success)return this.failWorkflow(r,o.error.message),g(o.error);this.addAgentToWorkflow(r,o.value);for(let d=0;d<e.length;d++){let m=e[d];this.updateWorkflowProgress(r,Math.round((d+1)/e.length*100));let p=await this.performanceProfiler.testRecovery(m,"latency",5e3),h=await this.performanceProfiler.testCircuitBreaker(m),v=await this.performanceProfiler.testRateLimiting(m,100),b=0;if(p.success&&p.value.passed)b+=33.3,n.push(`${m}: Fast recovery (${p.value.recoveryTime}ms)`);else{let C=p.success?p.value.recoveryTime:"unknown";s.push({service:m,type:"recovery",description:"Slow or failed recovery after fault",risk:_s.create(.7)}),a.push({priority:"high",category:"recovery",recommendation:`Improve ${m} recovery time - currently ${C}ms`,effort:"moderate"})}h.success&&h.value.passed?(b+=33.3,n.push(`${m}: Circuit breaker functioning correctly`)):(s.push({service:m,type:"circuit-breaker",description:"Circuit breaker not functioning as expected",risk:_s.create(.6)}),a.push({priority:"medium",category:"circuit-breaker",recommendation:`Review ${m} circuit breaker configuration`,effort:"minor"})),v.success&&v.value.passed?(b+=33.4,n.push(`${m}: Rate limiting effective`)):(s.push({service:m,type:"rate-limiting",description:"Rate limiting not properly configured",risk:_s.create(.5)}),a.push({priority:"medium",category:"rate-limiting",recommendation:`Configure rate limiting for ${m}`,effort:"minor"})),i.set(m,b)}let l=e.length>0?Array.from(i.values()).reduce((d,m)=>d+m,0)/e.length:0;await this.agentCoordinator.stop(o.value),this.completeWorkflow(r);let u={overallScore:l,serviceScores:i,strengths:n,weaknesses:s,recommendations:a};return await this.storeReport("assessment",r,u),f(u)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async generateExperiments(e){let r=w();try{this.startWorkflow(r,"experiment-generation");let i=[];for(let n of e.services){let s=this.generateServiceExperiments(n,e.dependencies);i.push(...s)}for(let n of e.criticalPaths){let s=this.generateCriticalPathExperiment(n,e);i.push(s)}for(let n of i)await this.chaosEngineer.createExperiment(n);return this.completeWorkflow(r),f(i)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async runStrategicChaosSuite(e,r){let i=w();try{if(this.startWorkflow(i,"chaos-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&me.warn("Topology degraded, adjusting strategic chaos parameters"),this.minCutMixin.shouldPauseOperations())return g(new Error("Strategic chaos suite paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return g(new Error("Agent limit reached, cannot spawn chaos agents"));let n=await this.selectChaosStrategy(e,r);if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);let s=n.value.selectedExperiments;if(me.info(`[chaos-resilience] Using ${n.value.strategy} strategy with ${s.length} experiments (confidence: ${n.value.confidence.toFixed(2)})`),s.length===0)return this.completeWorkflow(i),f({totalExperiments:0,passed:0,failed:0,results:[],recommendations:[{priority:"low",category:"strategy",recommendation:"No experiments selected - consider adjusting strategy context",effort:"trivial"}]});let a=await this.spawnChaosAgent(i,"coordinator");if(!a.success)return this.failWorkflow(i,a.error.message),g(a.error);this.addAgentToWorkflow(i,a.value);let o=[],l=[],u=0,d=0;for(let p of s)await this.chaosEngineer.createExperiment(p);for(let p=0;p<s.length;p++){let h=s[p];this.updateWorkflowProgress(i,Math.round((p+1)/s.length*100));let v=await this.chaosEngineer.runExperiment(h.id);if(v.success){if(o.push(v.value),v.value.hypothesisValidated)u++;else{d++;let C=this.generateRecommendationsFromExperiment(v.value);l.push(...C)}let b=v.value.hypothesisValidated?.8:.2;await this.storeResiliencePattern(h,v.value,b),this.config.publishEvents&&await this.publishExperimentCompleted(v.value)}else d++,l.push({priority:"high",category:"experiment-failure",recommendation:`Failed to run experiment ${h.name}: ${v.error.message}`,effort:"moderate"})}await this.agentCoordinator.stop(a.value),this.completeWorkflow(i);let m={totalExperiments:s.length,passed:u,failed:d,results:o,recommendations:l};return await this.storeReport("strategic-chaos-suite",i,m),f(m)}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async getResilienceDashboard(){try{let e=await this.memory.search("chaos:results:*",10),r=await this.memory.search("loadtest:results:*",10),i,n,s=0,a=0,o=0,l=0,u=0;for(let v of e){let b=await this.memory.get(v);b&&((!i||b.startTime>i)&&(i=b.startTime),s+=b.incidents.filter(C=>!C.resolved).length)}for(let v of r){let b=await this.memory.get(v);if(b&&b.timeline.length>0){let C=b.timeline[0].timestamp;(!n||C>n)&&(n=C),u++,b.status==="failed"&&l++}}let d=o>0?a/o:0,m=u>0?l/u*100:0,p="healthy";return s>5||m>25?p="unhealthy":(s>0||m>10)&&(p="degraded"),f({overallHealth:p,lastExperimentDate:i,lastLoadTestDate:n,activeIncidents:s,uptime:99.9,mttr:d,changeFailureRate:m})}catch(e){return g(y(e))}}async spawnChaosAgent(e,r){let i={name:`chaos-${r}-${e.slice(0,8)}`,domain:"chaos-resilience",type:"specialist",capabilities:["chaos-engineering","fault-injection",r],config:{workflowId:e}};return this.agentCoordinator.spawn(i)}async spawnLoadTestAgent(e,r){let i={name:`loadtest-${r}-${e.slice(0,8)}`,domain:"chaos-resilience",type:"specialist",capabilities:["load-testing","performance",r],config:{workflowId:e}};return this.agentCoordinator.spawn(i)}async spawnAssessmentAgent(e){let r={name:`assessment-${e.slice(0,8)}`,domain:"chaos-resilience",type:"analyzer",capabilities:["resilience-assessment","analysis"],config:{workflowId:e}};return this.agentCoordinator.spawn(r)}async publishExperimentCompleted(e){let r={id:w(),type:"chaos-resilience.ExperimentCompleted",timestamp:new Date,source:"chaos-resilience",payload:{experimentId:e.experimentId,status:e.status,hypothesisValidated:e.hypothesisValidated,incidentCount:e.incidents.length}};await this.eventBus.publish(r)}async publishLoadTestCompleted(e){let r={id:w(),type:"chaos-resilience.LoadTestCompleted",timestamp:new Date,source:"chaos-resilience",payload:{testId:e.testId,status:e.status,summary:e.summary,assertionsPassed:e.assertionResults.filter(i=>i.passed).length,assertionsFailed:e.assertionResults.filter(i=>!i.passed).length}};await this.eventBus.publish(r)}generateRecommendationsFromExperiment(e){let r=[];e.hypothesisValidated||r.push({priority:"high",category:"hypothesis-failure",recommendation:`Experiment ${e.experimentId} hypothesis was not validated - review system behavior under fault conditions`,effort:"moderate"}),e.steadyStateVerified||r.push({priority:"critical",category:"steady-state",recommendation:"System did not maintain steady state - investigate stability issues",effort:"major"});for(let i of e.incidents)(i.severity==="critical"||i.severity==="high")&&r.push({priority:i.severity,category:"incident",recommendation:`Address ${i.type}: ${i.message}`,effort:"moderate"});return r}detectBottlenecks(e){let r=[];return e.summary.p95ResponseTime>1e3&&r.push({location:"api",type:"network",description:`P95 response time is ${e.summary.p95ResponseTime}ms (>1000ms)`,impact:e.summary.p95ResponseTime>2e3?"high":"medium",recommendation:"Investigate API response time, consider caching or query optimization"}),e.summary.errorRate>5&&r.push({location:"service",type:"cpu",description:`Error rate is ${e.summary.errorRate.toFixed(2)}% (>5%)`,impact:e.summary.errorRate>10?"high":"medium",recommendation:"Investigate error causes, scale resources if under load"}),e.summary.requestsPerSecond<10&&r.push({location:"backend",type:"io",description:`Low throughput: ${e.summary.requestsPerSecond.toFixed(2)} RPS`,impact:"medium",recommendation:"Review I/O operations, database queries, and connection pooling"}),r}generateServiceExperiments(e,r){let i=[];i.push(this.createExperiment(`${e.name}-latency`,`Test ${e.name} behavior under latency`,"latency",e.name)),i.push(this.createExperiment(`${e.name}-error`,`Test ${e.name} error handling`,"error",e.name)),i.push(this.createExperiment(`${e.name}-cpu-stress`,`Test ${e.name} under CPU stress`,"cpu-stress",e.name));let n=r.filter(s=>s.from===e.name);for(let s of n)s.criticality==="critical"&&i.push(this.createExperiment(`${e.name}-${s.to}-failure`,`Test ${e.name} when ${s.to} fails`,"error",s.to));return i}generateCriticalPathExperiment(e,r){let i=e.join("-");return{id:w(),name:`critical-path-${i}`,description:`Test critical path: ${e.join(" -> ")}`,hypothesis:{statement:"System should handle partial path failure gracefully",metrics:[{metric:"error_rate",operator:"lt",value:10},{metric:"response_time_ms",operator:"lt",value:2e3}],tolerances:[{metric:"error_rate",maxDeviation:5,unit:"percent"}]},steadyState:{description:"All services in path are healthy",probes:e.map(n=>({name:`${n}-health`,type:"http",target:`http://${n}/health`,expected:{status:200},timeout:5e3}))},faults:e.slice(0,-1).map(n=>({id:w(),type:"latency",target:{type:"service",selector:n},parameters:{latencyMs:500},duration:3e4})),blastRadius:{scope:"subset",percentage:50,excludeProduction:!0},rollbackPlan:{automatic:!0,triggerConditions:[{type:"error-rate",condition:"error_rate > 20"},{type:"timeout",condition:"duration > 60000"}],steps:[{order:1,action:"Remove all faults",timeout:5e3},{order:2,action:"Verify service health"}]}}}createExperiment(e,r,i,n){return{id:w(),name:e,description:r,hypothesis:{statement:`${n} should recover within 5 seconds from ${i}`,metrics:[{metric:"response_time_ms",operator:"lt",value:1e3},{metric:"error_rate",operator:"lt",value:5}],tolerances:[{metric:"response_time_ms",maxDeviation:50,unit:"percent"}]},steadyState:{description:`${n} is healthy and responsive`,probes:[{name:`${n}-health`,type:"http",target:`http://${n}/health`,expected:{status:200},timeout:5e3}]},faults:[{id:w(),type:i,target:{type:"service",selector:n},parameters:this.getDefaultFaultParameters(i),duration:3e4}],blastRadius:{scope:"single",excludeProduction:!0},rollbackPlan:{automatic:!0,triggerConditions:[{type:"error-rate",condition:"error_rate > 50"}],steps:[{order:1,action:`Remove ${i} fault`},{order:2,action:"Verify recovery"}]}}}getDefaultFaultParameters(e){return{latency:{latencyMs:500},error:{errorCode:500},timeout:{timeoutMs:3e4},"packet-loss":{packetLossPercent:10},"cpu-stress":{cpuPercent:80},"memory-stress":{memoryBytes:268435456},"disk-stress":{},"network-partition":{},"dns-failure":{},"process-kill":{}}[e]||{}}async storeReport(e,r,i){await this.memory.set(`chaos-resilience:reports:${e}:${r}`,i,{namespace:"chaos-resilience",persist:!0})}async selectChaosStrategy(e,r){if(!this.policyGradient||!this.config.enablePolicyGradient)return f({strategy:"default",selectedExperiments:this.getDefaultExperiments(e.slice(0,3)),confidence:1,reasoning:"Default strategy (PolicyGradient disabled)"});if(e.length===0)return f({strategy:"empty",selectedExperiments:[],confidence:1,reasoning:"No services provided"});try{let i={id:`chaos-strategy-${Date.now()}`,features:[r.riskTolerance,r.availableCapacity/100,e.length/50,e.filter(u=>!u.hasFailover).length/Math.max(1,e.length),e.filter(u=>u.type==="database").length/Math.max(1,e.length),r.environment==="production"?0:1,r.environment==="staging"?1:0,e.filter(u=>u.type==="cache").length/Math.max(1,e.length),e.filter(u=>u.type==="queue").length/Math.max(1,e.length),e.reduce((u,d)=>u+d.replicas,0)/Math.max(1,e.length*5)]},n=await this.policyGradient.predict(i),s=[],a="default";switch(n.action.type){case"allocate":{let u=typeof n.action.value=="object"?n.action.value:null;if(u&&"agentType"in u&&u.agentType==="tester"){let d=e.filter(m=>!m.hasFailover||m.type==="database").slice(0,3);s=this.generateExperimentsForServices(d,["latency","error"]),a="allocate-critical"}break}case"reallocate":{let u=typeof n.action.value=="object"?n.action.value:null;u&&"domain"in u&&u.domain==="test-execution"&&(s=this.generateExperimentsForServices(e.slice(0,5),["cpu-stress","memory-stress"]),a="reallocate-resource-stress");break}case"scale-up":s=this.generateExperimentsForServices(e,["latency","error","timeout"]),a="scale-up-comprehensive";break;case"scale-down":s=this.generateExperimentsForServices(e.slice(0,2),["latency"]),a="scale-down-minimal";break;default:s=this.getDefaultExperiments(e.slice(0,3)),a="default";break}let o=await this.calculateStrategyReward(s,r),l=n.action;return await this.policyGradient.train({state:i,action:l,reward:o,nextState:i,done:!0}),me.info(`[chaos-resilience] PolicyGradient selected ${a} strategy for ${e.length} services (confidence: ${n.confidence.toFixed(2)})`),f({strategy:a,selectedExperiments:s,confidence:n.confidence,reasoning:n.reasoning||`PolicyGradient selected: ${a}`})}catch(i){return me.error("PolicyGradient strategy selection failed:",i instanceof Error?i:void 0),f({strategy:"fallback",selectedExperiments:this.getDefaultExperiments(e.slice(0,3)),confidence:.5,reasoning:"Fallback to default (PolicyGradient error)"})}}generateExperimentsForServices(e,r){let i=[];for(let n of e)for(let s of r)i.push(this.createExperiment(`${n.name}-${s}-${Date.now()}`,`Test ${n.name} with ${s} fault`,s,n.name));return i}getDefaultExperiments(e){return this.generateExperimentsForServices(e,["latency","error"])}async calculateStrategyReward(e,r){let i=.5,n=e.length;(r.riskTolerance>.7&&n>5||r.riskTolerance<.3&&n<=3)&&(i+=.2),(r.availableCapacity>70&&n>5||r.availableCapacity<30&&n<=3)&&(i+=.1);let s=new Set(e.map(a=>a.faults[0]?.type));return i+=Math.min(.1,s.size/5),Math.max(0,Math.min(1,i))}async storeResiliencePattern(e,r,i){if(!(!this.qesona||!this.config.enableQESONA))try{let n={id:`chaos-${e.id}`,features:[e.faults.length/10,e.faults[0]?.duration?e.faults[0].duration/6e4:0,e.steadyState.probes.length/20,e.blastRadius.excludeProduction?1:0,(e.blastRadius.percentage??0)/100,r.hypothesisValidated?1:0,r.steadyStateVerified?1:0,r.incidents.length/10,r.incidents.filter(a=>a.severity==="critical").length/5,i]},s={type:r.hypothesisValidated?"validate":"reject",value:i};this.qesona.createPattern(n,s,{reward:r.hypothesisValidated?i:-i,success:r.hypothesisValidated,quality:i},"defect-prediction","chaos-resilience",{experimentId:e.id,experimentName:e.name,faultType:e.faults[0]?.type,hypothesisValidated:r.hypothesisValidated}),me.info(`Stored resilience pattern for ${e.id} (validated: ${r.hypothesisValidated}, quality: ${i.toFixed(2)})`)}catch(n){me.error("Failed to store resilience pattern:",n instanceof Error?n:void 0)}}async adaptStrategies(e,r){if(!this.qesona||!this.config.enableQESONA)return{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5};try{let i={id:`chaos-adapt-${e.name}-${Date.now()}`,features:[e.hasFailover?0:1,r.riskTolerance,e.type==="api"?1:0,e.type==="database"?1:0,e.type==="cache"?1:0,r.environment==="production"?1:0,r.environment==="staging"?1:0,e.replicas/10,e.type==="worker"?1:0,e.type==="queue"?1:0]},n=await this.qesona.adaptPattern(i,"defect-prediction","chaos-resilience");if(n.success&&n.pattern){let s=n.pattern.outcome.success,a=this.getRecommendedFaults(n.pattern.action.type);return me.info(`[chaos-resilience] QESONA adapted strategy for ${e.name}: shouldRun=${s}, faults=${a.join(",")}, confidence=${n.similarity.toFixed(2)}`),{shouldRunChaos:s,recommendedFaults:a,confidence:n.similarity}}return{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5}}catch(i){return me.error("QESONA strategy adaptation failed:",i instanceof Error?i:void 0),{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5}}}getRecommendedFaults(e){switch(e){case"validate":return["latency","error","timeout"];case"reject":return["latency"];case"allocate":return["latency","cpu-stress"];case"scale-up":return["latency","error","timeout","packet-loss"];case"scale-down":return["latency"];default:return["latency","error"]}}subscribeToEvents(){this.eventBus.subscribe("quality-assessment.DeploymentApproved",this.handleDeploymentApproved.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGateEvaluated.bind(this))}async handleDeploymentApproved(e){if(!this.config.enableAutomatedExperiments)return;let r=e.payload;r.services&&await this.memory.set(`chaos-resilience:pending-assessment:${e.id}`,r.services,{namespace:"chaos-resilience",ttl:3600})}async handleQualityGateEvaluated(e){let r=e.payload;r.passed||await this.memory.set(`chaos-resilience:quality-gate-failures:${e.id}`,r,{namespace:"chaos-resilience",ttl:86400})}async loadWorkflowState(){let e=await this.memory.get("chaos-resilience:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("chaos-resilience:coordinator:workflows",e,{namespace:"chaos-resilience",persist:!0})}async verifyChaosExperiment(e,r){let i=U({id:w(),type:"chaos-experiment",confidence:r,description:`Verify chaos experiment safety: ${e.name} (${e.faultType}) on ${e.target}`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:e.blastRadius==="full"?"critical":r>.9?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(me.info(`Chaos experiment '${e.name}' verified safe by consensus`),!0):(me.warn(`Chaos experiment '${e.name}' NOT verified safe: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyResilienceAssessment(e,r){let i=U({id:w(),type:"resilience-assessment",confidence:r,description:`Verify resilience assessment for ${e.service}: score ${e.overallScore}, ${e.weaknessCount} weaknesses`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:e.overallScore<50?"critical":e.overallScore<70?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(me.info(`Resilience assessment for '${e.service}' verified by consensus`),!0):(me.warn(`Resilience assessment for '${e.service}' NOT verified`),!1)}return!0}async verifyFailureInjection(e,r){let i=U({id:w(),type:"failure-injection",confidence:r,description:`Verify failure injection: ${e.faultType} on ${e.target} for ${e.duration}ms`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:"critical"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(me.info(`Failure injection '${e.faultType}' on '${e.target}' verified safe by consensus`),!0):(me.warn(`Failure injection '${e.faultType}' NOT verified safe: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}};k();var nm=class extends te{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;chaosEngineer=null;loadTester=null;performanceProfiler=null;pluginConfig;get name(){return"chaos-resilience"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{runChaosSuite:this.runChaosSuite.bind(this),runLoadTestSuite:this.runLoadTestSuite.bind(this),assessResilience:this.assessResilience.bind(this),generateExperiments:this.generateExperiments.bind(this),getResilienceDashboard:this.getResilienceDashboard.bind(this),createExperiment:this.createExperiment.bind(this),runExperiment:this.runExperiment.bind(this),abortExperiment:this.abortExperiment.bind(this),verifySteadyState:this.verifySteadyState.bind(this),injectFault:this.injectFault.bind(this),removeFault:this.removeFault.bind(this),createTest:this.createTest.bind(this),runTest:this.runTest.bind(this),runLoadTest:this.runTest.bind(this),stopTest:this.stopTest.bind(this),getRealtimeMetrics:this.getRealtimeMetrics.bind(this),generateFromTraffic:this.generateFromTraffic.bind(this),getExperimentHistory:this.getExperimentHistory.bind(this),testRecovery:this.testRecovery.bind(this),testFailover:this.testFailover.bind(this),testCircuitBreaker:this.testCircuitBreaker.bind(this),testRateLimiting:this.testRateLimiting.bind(this),selectChaosStrategy:this.coordinator.selectChaosStrategy.bind(this.coordinator),runStrategicChaosSuite:this.coordinator.runStrategicChaosSuite.bind(this.coordinator),getCoordinator:()=>this.coordinator,getChaosEngineer:()=>this.chaosEngineer,getChaosEngine:()=>this.chaosEngineer,getLoadTester:()=>this.loadTester,getPerformanceProfiler:()=>this.performanceProfiler,getResilienceAssessor:()=>this.performanceProfiler}}getTaskHandlers(){return new Map([["run-experiment",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.experimentId;return r?this.coordinator.runChaosSuite([r]):g(new Error("Invalid run-experiment payload: missing experimentId"))}],["run-load-test",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.testId;return r?this.coordinator.runLoadTestSuite([r]):g(new Error("Invalid run-load-test payload: missing testId"))}],["assess-resilience",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.services;return!r||r.length===0?g(new Error("Invalid assess-resilience payload: missing services")):this.coordinator.assessResilience(r)}],["inject-fault",async e=>{if(!this.chaosEngineer)return g(new Error("Chaos engineer not initialized"));let r=e.faultType,i=e.target;if(!r||!i)return g(new Error("Invalid inject-fault payload: missing faultType or target"));let n={id:`fault-${Date.now()}`,type:r,target:{type:"service",selector:i},parameters:e.parameters??{},duration:e.duration??3e4,probability:e.probability};return this.chaosEngineer.injectFault(n)}]])}async onInitialize(){this.chaosEngineer=new Vi({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.chaosEngineer),this.loadTester=new zi(this.memory,this.pluginConfig.loadTester),this.performanceProfiler=new Bi(this.memory,this.pluginConfig.performanceProfiler),this.coordinator=new Tc(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.chaosEngineer=null,this.loadTester=null,this.performanceProfiler=null}subscribeToEvents(){this.eventBus.subscribe("quality-assessment.DeploymentApproved",this.handleDeploymentApproved.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("security-compliance.VulnerabilityDetected",this.handleVulnerabilityDetected.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"quality-assessment.DeploymentApproved":await this.handleDeploymentApproved(e);break;case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(e);break;case"security-compliance.VulnerabilityDetected":await this.handleVulnerabilityDetected(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGateEvaluated(e);break;default:break}}async runChaosSuite(e){this.ensureInitialized();try{let r=await this.coordinator.runChaosSuite(e);return r.success?this.trackSuccessfulOperation("chaos-suite"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async runLoadTestSuite(e){this.ensureInitialized();try{let r=await this.coordinator.runLoadTestSuite(e);return r.success?this.trackSuccessfulOperation("load-suite"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async assessResilience(e){this.ensureInitialized();try{return await this.coordinator.assessResilience(e)}catch(r){return this.handleError(r)}}async generateExperiments(e){this.ensureInitialized();try{return await this.coordinator.generateExperiments(e)}catch(r){return this.handleError(r)}}async getResilienceDashboard(){this.ensureInitialized();try{return await this.coordinator.getResilienceDashboard()}catch(e){return this.handleError(e)}}async createExperiment(e){this.ensureInitialized();try{return await this.chaosEngineer.createExperiment(e)}catch(r){return this.handleError(r)}}async runExperiment(e){this.ensureInitialized();try{let r=await this.chaosEngineer.runExperiment(e);return r.success&&await this.publishExperimentEvent(r.value),r}catch(r){return this.handleError(r)}}async abortExperiment(e,r){this.ensureInitialized();try{return await this.chaosEngineer.abortExperiment(e,r)}catch(i){return this.handleError(i)}}async verifySteadyState(e){this.ensureInitialized();try{return await this.chaosEngineer.verifySteadyState(e)}catch(r){return this.handleError(r)}}async injectFault(e){this.ensureInitialized();try{return await this.chaosEngineer.injectFault(e)}catch(r){return this.handleError(r)}}async removeFault(e){this.ensureInitialized();try{return await this.chaosEngineer.removeFault(e)}catch(r){return this.handleError(r)}}async getExperimentHistory(){this.ensureInitialized();try{return{success:!0,value:await this.memory.get("chaos-resilience:experiment-history")??[]}}catch(e){return this.handleError(e)}}async createTest(e){this.ensureInitialized();try{return await this.loadTester.createTest(e)}catch(r){return this.handleError(r)}}async runTest(e){this.ensureInitialized();try{let r=await this.loadTester.runTest(e);return r.success&&await this.publishLoadTestEvent(r.value),r}catch(r){return this.handleError(r)}}async stopTest(e){this.ensureInitialized();try{return await this.loadTester.stopTest(e)}catch(r){return this.handleError(r)}}async getRealtimeMetrics(e){this.ensureInitialized();try{return await this.loadTester.getRealtimeMetrics(e)}catch(r){return this.handleError(r)}}async generateFromTraffic(e,r){this.ensureInitialized();try{return await this.loadTester.generateFromTraffic(e,r)}catch(i){return this.handleError(i)}}async testRecovery(e,r,i){this.ensureInitialized();try{return await this.performanceProfiler.testRecovery(e,r,i)}catch(n){return this.handleError(n)}}async testFailover(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testFailover(e,r)}catch(i){return this.handleError(i)}}async testCircuitBreaker(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testCircuitBreaker(e,r)}catch(i){return this.handleError(i)}}async testRateLimiting(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testRateLimiting(e,r)}catch(i){return this.handleError(i)}}async handleDeploymentApproved(e){let r=e.payload;r.services&&r.services.length>0&&await this.memory.set(`chaos-resilience:pending-assessment:${e.id}`,{services:r.services,triggeredAt:new Date,source:"deployment-approved"},{namespace:"chaos-resilience",ttl:3600})}async handleTestRunCompleted(e){let r=e.payload;await this.memory.set(`chaos-resilience:test-baseline:${r.runId}`,{duration:r.duration,successRate:r.passed/(r.passed+r.failed),timestamp:new Date},{namespace:"chaos-resilience",ttl:86400})}async handleVulnerabilityDetected(e){let r=e.payload;(r.severity==="critical"||r.severity==="high")&&await this.memory.set(`chaos-resilience:security-tests:${r.vulnId}`,{vulnerabilityId:r.vulnId,severity:r.severity,file:r.file,triggeredAt:new Date},{namespace:"chaos-resilience",ttl:86400})}async handleQualityGateEvaluated(e){let r=e.payload;r.checks?.some(n=>n.name==="resilience")&&await this.memory.set(`chaos-resilience:gate-context:${r.gateId}`,{gateId:r.gateId,passed:r.passed,checks:r.checks,timestamp:Date.now()},{namespace:"chaos-resilience",ttl:3600})}async publishExperimentEvent(e){await this.publishEvent("chaos-resilience.ExperimentCompleted",{experimentId:e.experimentId,status:e.status,hypothesisValidated:e.hypothesisValidated,steadyStateVerified:e.steadyStateVerified,faultCount:e.faultResults.length,incidentCount:e.incidents.length,duration:e.endTime?e.endTime.getTime()-e.startTime.getTime():0})}async publishLoadTestEvent(e){await this.publishEvent("chaos-resilience.LoadTestCompleted",{testId:e.testId,status:e.status,duration:e.duration,totalRequests:e.summary.totalRequests,successRate:e.summary.totalRequests>0?e.summary.successfulRequests/e.summary.totalRequests*100:0,p95ResponseTime:e.summary.p95ResponseTime,errorRate:e.summary.errorRate,assertionsPassed:e.assertionResults.filter(r=>r.passed).length,assertionsFailed:e.assertionResults.filter(r=>!r.passed).length})}ensureInitialized(){if(!this._initialized)throw new Error("ChaosResiliencePlugin is not initialized");if(!this.coordinator||!this.chaosEngineer||!this.loadTester||!this.performanceProfiler)throw new Error("ChaosResiliencePlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function Uv(c,t,e,r,i){return new nm(c,t,e,r,i)}_();var ak="learning-optimization",Oe=Object.freeze({namespace:ak}),lr="learning:pattern:",ok=["creation","archived"];function sm(c){if(!c.startsWith(lr))return!1;let t=c.slice(lr.length);if(t.length===0)return!1;let e=t.split(":",1)[0];return!ok.includes(e)}function ck(c,t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.id!="string"||c!==`${lr}${e.id}`?!1:!!e.context&&typeof e.context=="object"}async function Ec(c,t={}){let e=await wr(c,`${lr}*`,{retrieve:t.retrieve,pageSize:t.scanPageSize}),r=[];for(let i of e){if(!sm(i))continue;let n=await c.get(i,t.retrieve);ck(i,n)&&r.push(pe(n,["createdAt","lastUsedAt"]))}return r}var Qv=new Set(["test-generation:test-generated","coverage-analysis:gap-detection","defect-intelligence:defect-prediction","code-intelligence:impact-analysis"]);function lk(c){return c.rewardSource?c.rewardSource:Qv.has(`${c.agentId?.value}:${c.action}`)?"assigned":"measured"}function uk(c){return lk(c)==="measured"}function It(c){let t=c.filter(uk);return{measured:t,assignedExcluded:c.length-t.length}}var dk=/^\/\/ Common actions: (.*)$/m;function mk(c){if(c.rewardSource)return c.rewardSource;let t=dk.exec(c.template?.content??""),e=t?t[1].split(",").map(i=>i.trim()).filter(Boolean):[];return e.length>0&&e.every(i=>Qv.has(`${c.domain}:${i}`))?"assigned":"measured"}function am(c){return c.rewardSource?c.rewardSource:mk(c)==="assigned"?"assigned":"pre-1120"}function hs(c){return am(c)==="measured"}k();_();k();async function Kv(c,t,e=new Date){let r=`${lr}${t.id}`;if(!sm(r))return"missing";let i=await c.get(r,Oe);if(!i||i.id!==t.id||pk(i,t))return"missing";let n=`${lr}archived:${t.id}`;await c.set(n,{...t,archivedAt:e},{...Oe,persist:!0});let s=await c.get(n,Oe);return s&&s.id===t.id?"copied":"failed"}async function Jv(c,t){await c.delete(`${lr}${t.id}`,Oe)}function pk(c,t){let e=r=>new Date(r).getTime();return!Object.is(c.usageCount,t.usageCount)||!Object.is(c.confidence,t.confidence)||!Object.is(c.successRate,t.successRate)||!Object.is(e(c.lastUsedAt),e(t.lastUsedAt))}function Yv(c,t){let e=c.reduce((r,i)=>r+i.usageCount,0);return c.reduce((r,i)=>r+t(i)*(e>0?i.usageCount/e:1/c.length),0)}function Xv(c,t,e=new Date){let r=c.reduce((n,s)=>s.successRate>n.successRate?s:n),i={language:r.context.language,framework:r.context.framework,testType:r.context.testType,codeContext:r.context.codeContext,tags:[...new Set(c.flatMap(n=>n.context.tags))]};return{id:t,type:r.type,domain:r.domain,name:`consolidated-${r.name}`,description:`Consolidated from ${c.length} patterns`,confidence:Yv(c,n=>n.confidence),usageCount:c.reduce((n,s)=>n+s.usageCount,0),successRate:Yv(c,n=>n.successRate),context:i,template:r.template,createdAt:e,lastUsedAt:e,rewardSource:c.every(hs)?"measured":"assigned"}}Pe();hr();var gk={minExperiencesForPattern:5,patternConfidenceThreshold:.7,maxPatternsPerDomain:100,anomalyDeviationThreshold:2,clusterSimilarityThreshold:.8,enableLLMSynthesis:!0,llmModelTier:2,llmMaxTokens:2048},Ac=x.create("learning-optimization/learning-coordinator"),Ze={namespace:"learning-optimization"};function Zv(c){return Ec(c,{retrieve:Ze})}var zr=class{config;memory;llmRouter;flashAttention=null;_nullStore;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...gk,...e}}async initializeFlashAttention(t){return this.flashAttention=await tt("pattern-adaptation",t),Ac.info("FlashAttention initialized for pattern adaptation"),this.flashAttention}injectFlashAttention(t){this.flashAttention=t}isFlashAttentionAvailable(){return this.flashAttention!==null}getFlashAttentionMetrics(){return this.flashAttention?this.flashAttention.getMetrics():[]}async computeSimilarityWithFlashAttention(t,e){if(!this.flashAttention)throw new Error("[LearningCoordinatorService] FlashAttention not initialized. Call initializeFlashAttention() first.");let r=Math.min(t.length,e.length),i=new Float32Array(r),n=new Float32Array(r),s=new Float32Array(r);for(let l=0;l<r;l++)i[l]=t[l],n[l]=e[l],s[l]=1;let a=await this.flashAttention.computeFlashAttention(i,n,s,1,r),o=Math.abs(a[0]);return Math.min(1,o)}async batchComputeSimilarities(t,e,r=5){if(!this.flashAttention)throw new Error("[LearningCoordinatorService] FlashAttention not initialized. Call initializeFlashAttention() first.");let i=new Float32Array(t),n=e.map(s=>new Float32Array(s));return this.flashAttention.computeTestSimilarity(i,n,r)}disposeFlashAttention(){this.flashAttention&&(this.flashAttention.dispose(),this.flashAttention=null)}isLLMSynthesisAvailable(){return this.config.enableLLMSynthesis&&this.llmRouter!==void 0}getModelForTier(t){return ae(t)}async synthesizePatternsWithLLM(t){if(!this.isLLMSynthesisAvailable())return null;try{let e=t.slice(0,10).map(i=>`- ${i.name}: ${i.type} (confidence: ${i.confidence.toFixed(2)})`).join(`
3000
+ 3. Recommended safety measures`}],maxTokens:this.config.llmMaxTokens})).content}catch{return H.warn("LLM analysis failed:"),null}}validateExperiment(t){return t.id?t.name?t.hypothesis?!t.steadyState||t.steadyState.probes.length===0?g(new Error("At least one steady state probe is required")):!t.faults||t.faults.length===0?g(new Error("At least one fault injection is required")):t.rollbackPlan?t.blastRadius.excludeProduction===!1&&!t.rollbackPlan.automatic?g(new Error("Production experiments require automatic rollback")):f(void 0):g(new Error("Rollback plan is required")):g(new Error("Experiment hypothesis is required")):g(new Error("Experiment name is required")):g(new Error("Experiment ID is required"))}validateFault(t){return t.id?t.type?t.target?t.duration<0?g(new Error("Fault duration must be non-negative")):t.probability!==void 0&&(t.probability<0||t.probability>1)?g(new Error("Fault probability must be between 0 and 1")):f(void 0):g(new Error("Fault target is required")):g(new Error("Fault type is required")):g(new Error("Fault ID is required"))}createExecution(t){return{experimentId:t.id,startTime:new Date,result:{experimentId:t.id,status:"running",startTime:new Date,hypothesisValidated:!1,steadyStateVerified:!1,faultResults:[],metrics:[],incidents:[]}}}finalizeExecution(t){t.result.endTime=new Date;let e={experimentId:t.result.experimentId,status:t.result.status,startTime:t.result.startTime,endTime:t.result.endTime,hypothesisValidated:t.result.hypothesisValidated,steadyStateVerified:t.result.steadyStateVerified,faultResults:t.result.faultResults,metrics:t.result.metrics,incidents:t.result.incidents};return this.memory.set(`chaos:results:${t.experimentId}:${Date.now()}`,e,{namespace:"chaos-resilience",persist:!0}),e}async executeProbe(t){try{switch(t.type){case"http":return await this.executeHttpProbe(t);case"tcp":return await this.executeTcpProbe(t);case"command":return await this.executeCommandProbe(t);case"metric":return await this.executeMetricProbe(t);default:return!1}}catch{return!1}}async executeHttpProbe(t){try{let e=await this.httpClient.get(t.target,{timeout:t.timeout??5e3,retries:1,circuitBreaker:!1});if(!e.success)return H.info(`HTTP probe failed: ${t.name} -> ${e.error.message}`),!1;let r=e.value;if(t.expectedStatus!==void 0){let i=r.status===t.expectedStatus;return i||H.info(`HTTP probe ${t.name}: expected status ${t.expectedStatus}, got ${r.status}`),i}return r.ok}catch(e){return H.info(`HTTP probe error: ${t.name} -> ${P(e)}`),!1}}async executeTcpProbe(t){return new Promise(e=>{try{let[r,i]=t.target.split(":"),n=parseInt(i,10);if(!r||isNaN(n)){H.info(`TCP probe invalid target: ${t.target} (expected host:port)`),e(!1);return}let s=t.timeout??5e3,a=new Wv.Socket,o=setTimeout(()=>{a.destroy(),H.info(`TCP probe timeout: ${t.name} -> ${t.target}`),e(!1)},s);a.connect(n,r,()=>{clearTimeout(o),a.destroy(),e(!0)}),a.on("error",l=>{clearTimeout(o),a.destroy(),H.info(`TCP probe error: ${t.name} -> ${l.message}`),e(!1)})}catch(r){H.info(`TCP probe exception: ${t.name} -> ${P(r)}`),e(!1)}})}static ALLOWED_PROBE_COMMANDS=["curl","wget","nc","netcat","ping","nslookup","dig","ps","pgrep","cat","head","tail","ls","stat","echo","test","[","node","npm"];async executeCommandProbe(t){return new Promise(e=>{let r=t.timeout??1e4,i=Qo(t.target,c.ALLOWED_PROBE_COMMANDS);if(!i.valid){H.info(`Command probe ${t.name} blocked: ${i.error}`),H.info(`Blocked patterns: ${i.blockedPatterns?.join(", ")||"none"}`),e(!1);return}let s=(i.sanitizedCommand||t.target).trim().split(/\s+/),a=s[0],o=s.slice(1);Hv(a,o,{timeout:r},(l,u,d)=>{if(l){H.info(`Command probe failed: ${t.name} -> ${l.message}`),e(!1);return}if(t.expectedOutput!==void 0){let m=u.trim().includes(t.expectedOutput);m||H.info(`Command probe ${t.name}: output did not contain expected value`),e(m);return}e(!0)})})}async executeMetricProbe(t){try{let e=await this.httpClient.get(t.target,{timeout:t.timeout??5e3,retries:1,circuitBreaker:!1});if(!e.success)return H.info(`Metric probe failed: ${t.name} -> ${e.error.message}`),!1;let r=e.value;if(!r.ok)return H.info(`Metric probe HTTP error: ${t.name} -> ${r.status}`),!1;let i=await r.text(),n;try{let s=D(i);n=typeof s.value=="number"?s.value:parseFloat(s.value)}catch{n=parseFloat(i)}if(isNaN(n))return H.info(`Metric probe ${t.name}: could not parse metric value from response`),!1;if(t.threshold!==void 0){let{operator:s,value:a}=t.threshold;switch(s){case"lt":return n<a;case"gt":return n>a;case"lte":return n<=a;case"gte":return n>=a;case"eq":return n===a;default:return!0}}return!0}catch(e){return H.info(`Metric probe error: ${t.name} -> ${P(e)}`),!1}}async performFaultInjection(t){let r={latency:async()=>this.injectLatency(t),error:async()=>this.injectError(t),timeout:async()=>this.injectTimeout(t),"packet-loss":async()=>this.injectPacketLoss(t),"cpu-stress":async()=>this.injectCpuStress(t),"memory-stress":async()=>this.injectMemoryStress(t),"disk-stress":async()=>this.injectDiskStress(t),"network-partition":async()=>this.injectNetworkPartition(t),"dns-failure":async()=>this.injectDnsFailure(t),"process-kill":async()=>this.injectProcessKill(t)}[t.type];return r?r():g(new Error(`Unknown fault type: ${t.type}`))}async injectLatency(t){let e=t.parameters.latencyMs??100;return H.info(`Latency injection configured: ${e}ms for ${t.target.selector}`),H.info("Note: Actual latency injection requires network proxy (e.g., Toxiproxy, tc)"),f(1)}async injectError(t){let e=t.parameters.errorCode??500;return H.info(`Error injection configured: ${e} for ${t.target.selector}`),H.info("Note: Actual error injection requires service mesh (e.g., Istio, Linkerd)"),f(1)}async injectTimeout(t){return H.info(`Timeout injection configured for ${t.target.selector}`),H.info("Note: Actual timeout injection requires network proxy configuration"),f(1)}async injectPacketLoss(t){let e=t.parameters.packetLossPercent??10;return H.info(`Packet loss configured: ${e}% for ${t.target.selector}`),H.info("Note: Actual packet loss requires tc/iptables (Linux) or similar"),f(1)}async injectCpuStress(t){let e=t.parameters.cpuPercent??80,r=t.parameters.cores??1,i=t.duration;H.info(`Injecting CPU stress: ${e}% on ${r} core(s) for ${i}ms`);let n=Date.now(),s=setInterval(()=>{if(Date.now()-n>=i){clearInterval(s);return}let a=10*(e/100),o=Date.now();for(;Date.now()-o<a;)z()*z()},10);return this.stressWorkers.set(t.id,s),f(r)}async injectMemoryStress(t){let e=t.parameters.memoryBytes??104857600,r=Math.round(e/(1024*1024));H.info(`Injecting memory stress: ${r}MB allocation`);try{let n=Math.ceil(e/1048576),s=[];for(let a=0;a<n;a++){let o=Math.min(1048576,e-a*1048576),l=new Array(o).fill(z());s.push(l)}return this.stressWorkers.set(t.id,s),H.info(`Memory stress active: ${s.length} chunks allocated`),f(1)}catch(i){return g(new Error(`Failed to allocate memory: ${P(i)}`))}}async injectDiskStress(t){return H.info(`Disk stress configured for ${t.target.selector}`),H.info("Note: Actual disk stress requires file system write permissions"),f(1)}async injectNetworkPartition(t){return H.info(`Network partition configured for ${t.target.selector}`),H.info("Note: Actual network partition requires iptables/firewall rules"),f(1)}async injectDnsFailure(t){return H.info(`DNS failure configured for ${t.target.selector}`),H.info("Note: Actual DNS failure requires DNS server or /etc/hosts modification"),f(1)}async injectProcessKill(t){let e=t.target.selector;return H.info(`Process kill configured for pattern: ${e}`),H.info("Note: Actual process kill requires appropriate permissions"),this.config.enableDryRun?(H.info(`Would kill processes matching: ${e}`),f(0)):f(1)}async performFaultRemoval(t){H.info(`Removing fault: ${t.id} (${t.type})`);let e=this.stressWorkers.get(t.id);e&&(typeof e=="object"&&"unref"in e&&clearInterval(e),this.stressWorkers.delete(t.id))}async collectMetricsDuringExperiment(t,e){let r=e.hypothesis.metrics.map(s=>s.metric),i=Date.now(),n=Math.max(...e.faults.map(s=>s.duration),this.config.defaultTimeout);for(;Date.now()-i<Math.min(n,5e3);){for(let s of r){let a={timestamp:new Date,name:s,value:this.collectRealMetricValue(s),labels:{experiment:e.id}};t.result.metrics.push(a)}await this.sleep(this.config.safetyCheckInterval)}}collectRealMetricValue(t){return this.metricsCollector.getChaosMetricValue(t)}validateHypothesis(t,e){for(let r of t.metrics){let i=e.filter(s=>s.name===r.metric);if(i.length===0)return!1;let n=i.reduce((s,a)=>s+a.value,0)/i.length;if(!this.checkMetricExpectation(n,r))return!1}for(let r of t.tolerances){let i=e.filter(o=>o.name===r.metric);if(i.length===0)continue;let n=i.map(o=>o.value),s=this.calculateDeviation(n);if((r.unit==="percent"?s/n[0]*100:s)>r.maxDeviation)return!1}return!0}checkMetricExpectation(t,e){let{operator:r,value:i}=e;switch(r){case"eq":return t===i;case"lt":return t<i;case"gt":return t>i;case"lte":return t<=i;case"gte":return t>=i;case"between":{let[n,s]=i;return t>=n&&t<=s}default:return!1}}calculateDeviation(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n,0)/t.length,r=t.map(i=>Math.pow(i-e,2));return Math.sqrt(r.reduce((i,n)=>i+n,0)/t.length)}determineExperimentStatus(t,e){return!t.result.steadyStateVerified||!e?"failed":t.result.hypothesisValidated?"completed":t.result.faultResults.filter(i=>!i.injected).length>0?"failed":"completed"}async rollbackExperiment(t){for(let e of t.rollbackPlan.steps.sort((r,i)=>r.order-i.order)){H.info(`Executing rollback step ${e.order}: ${e.action}`);try{await this.executeRollbackAction(e.action,e.target,e.timeout)}catch(r){H.error(`Rollback step ${e.order} failed: ${P(r)}`)}}for(let e of t.faults)await this.removeFault(e.id)}async executeRollbackAction(t,e,r=3e4){t.startsWith("http://")||t.startsWith("https://")?await this.executeHttpRollback(t,r):t.startsWith("cmd:")?await this.executeCommandRollback(t.slice(4),r):e&&(e.startsWith("http://")||e.startsWith("https://"))?await this.executeHttpRollback(`${e}/_chaos/${t}`,r):await this.executeBuiltInRollback(t,e,r)}async executeHttpRollback(t,e){let r=await this.httpClient.post(t,{},{timeout:e,retries:1});if(!r.success)throw new Error(`HTTP rollback failed: ${r.error.message}`)}static ALLOWED_ROLLBACK_COMMANDS=["kill","pkill","rm","rmdir","mv","cp","systemctl","service","docker","kubectl","iptables","tc","echo","true"];executeCommandRollback(t,e){return new Promise((r,i)=>{let n=Qo(t,c.ALLOWED_ROLLBACK_COMMANDS);if(!n.valid){i(new Error(`Rollback command blocked: ${n.error}`));return}let a=(n.sanitizedCommand||t).trim().split(/\s+/),o=a[0],l=a.slice(1);Hv(o,l,{timeout:e},(u,d,m)=>{u?i(new Error(`Command rollback failed: ${u.message}. ${m}`)):r()})})}async executeBuiltInRollback(t,e,r){let i=t.toLowerCase();i.includes("remove")||i.includes("clear")?e&&H.info(`Clearing state for target: ${e}`):i.includes("restart")?H.info(`Restart requested for: ${e||"service"}`):i.includes("restore")?H.info(`Restore requested for: ${e||"system"}`):H.info(`Rollback action logged: ${t}`),await this.sleep(100)}sleep(t){return new Promise(e=>setTimeout(e,t))}};k();ge();var ik={defaultTimeout:3e5,maxVirtualUsers:1e3,reportingInterval:1e3,enableDetailedMetrics:!0,connectionPoolSize:100},zi=class{constructor(t,e={}){this.memory=t;this.config={...ik,...e},this.httpClient=new gt}memory;config;activeTests=new Map;httpClient;async createTest(t){try{let e=this.validateTest(t);return e.success?(await this.memory.set(`loadtest:tests:${t.id}`,t,{namespace:"chaos-resilience",persist:!0}),f(t.id)):g(e.error)}catch(e){return g(y(e))}}async runTest(t){try{let e=await this.memory.get(`loadtest:tests:${t}`);if(!e)return g(new Error(`Load test not found: ${t}`));if(this.activeTests.has(t))return g(new Error(`Load test ${t} is already running`));if(e.profile.virtualUsers.max>this.config.maxVirtualUsers)return g(new Error(`Virtual users (${e.profile.virtualUsers.max}) exceeds maximum (${this.config.maxVirtualUsers})`));let r=this.createExecution(e);this.activeTests.set(t,r);try{return await this.executeLoadTest(r,e),r.result.assertionResults=this.evaluateAssertions(e.assertions,r.result.summary),r.result.status=this.determineTestStatus(r.result),f(this.finalizeExecution(r))}catch(i){return r.result.status="failed",r.result.errors.push({type:"execution_error",message:P(i),count:1,firstOccurrence:new Date,lastOccurrence:new Date}),f(this.finalizeExecution(r))}finally{this.activeTests.delete(t)}}catch(e){return g(y(e))}}async stopTest(t){try{let e=this.activeTests.get(t);return e?(e.aborted=!0,e.result.status="aborted",f(this.finalizeExecution(e))):g(new Error(`No active load test found: ${t}`))}catch(e){return g(y(e))}}async getRealtimeMetrics(t){try{let e=this.activeTests.get(t);if(!e)return g(new Error(`No active load test found: ${t}`));let r=e.result.timeline[e.result.timeline.length-1];return r?f(r):g(new Error("No metrics available yet"))}catch(e){return g(y(e))}}async generateFromTraffic(t,e){try{if(t.requests.length===0)return g(new Error("Traffic sample contains no requests"));if(e<=0)return g(new Error("Multiplier must be positive"));let r=t.requests.reduce((p,h)=>p+h.frequency,0),i=t.requests.reduce((p,h)=>p+h.avgResponseTime*h.frequency,0)/r,n=t.requests.map(p=>({name:`${p.method} ${p.url}`,weight:p.frequency/r,steps:[{type:"request",target:{url:p.url,method:p.method}},{type:"think",duration:Math.max(100,i*.5)}]})),a=r/t.duration*e,o=Math.ceil(a*(i/1e3)),l={virtualUsers:{start:Math.ceil(o*.1),max:Math.min(o,this.config.maxVirtualUsers),pattern:"ramp"},duration:Math.max(6e4,t.duration*e),rampUp:3e4,rampDown:15e3},u=[{metric:"p95",operator:"lt",value:i*2},{metric:"error-rate",operator:"lt",value:5},{metric:"throughput",operator:"gte",value:a*.9}],d=e>5?"stress":"load",m={id:w(),name:`Generated from ${t.source} (${e}x)`,type:d,target:{url:t.requests[0].url,method:t.requests[0].method},profile:l,scenarios:n,assertions:u};return f(m)}catch(r){return g(y(r))}}validateTest(t){return t.id?t.name?!t.target||!t.target.url?g(new Error("Test target URL is required")):t.profile?t.profile.virtualUsers.max<=0?g(new Error("Maximum virtual users must be positive")):t.profile.duration<=0?g(new Error("Test duration must be positive")):f(void 0):g(new Error("Test profile is required")):g(new Error("Test name is required")):g(new Error("Test ID is required"))}createExecution(t){return{testId:t.id,startTime:new Date,aborted:!1,result:{testId:t.id,status:"completed",duration:0,summary:this.createEmptySummary(),timeline:[],errors:[],assertionResults:[]}}}createEmptySummary(){return{totalRequests:0,successfulRequests:0,failedRequests:0,requestsPerSecond:0,avgResponseTime:0,p50ResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,maxResponseTime:0,errorRate:0}}async executeLoadTest(t,e){let r=Date.now(),i=e.profile.duration,n=[],s=new Map,a=this.getExecutionStrategy(e.type);for(;Date.now()-r<i&&!t.aborted;){let o=Date.now()-r,l=this.calculateCurrentVirtualUsers(e.profile,o,i),u=await this.executeBatch(e,l,a);n.push(...u.responseTimes);for(let m of u.errors){let p=s.get(m);p?(p.count++,p.lastOccurrence=new Date):s.set(m,{type:"request_error",message:m,count:1,firstOccurrence:new Date,lastOccurrence:new Date})}t.result.summary.totalRequests+=u.totalRequests,t.result.summary.successfulRequests+=u.successfulRequests,t.result.summary.failedRequests+=u.failedRequests;let d={timestamp:new Date,virtualUsers:l,requestsPerSecond:u.totalRequests,avgResponseTime:u.responseTimes.length>0?u.responseTimes.reduce((m,p)=>m+p,0)/u.responseTimes.length:0,errorRate:u.totalRequests>0?u.failedRequests/u.totalRequests*100:0};t.result.timeline.push(d),await this.sleep(this.config.reportingInterval)}if(t.result.duration=Date.now()-r,t.result.errors=Array.from(s.values()),n.length>0){let o=n.sort((l,u)=>l-u);t.result.summary.avgResponseTime=o.reduce((l,u)=>l+u,0)/o.length,t.result.summary.p50ResponseTime=this.percentile(o,50),t.result.summary.p95ResponseTime=this.percentile(o,95),t.result.summary.p99ResponseTime=this.percentile(o,99),t.result.summary.maxResponseTime=o[o.length-1]}t.result.summary.requestsPerSecond=t.result.summary.totalRequests/(t.result.duration/1e3),t.result.summary.errorRate=t.result.summary.totalRequests>0?t.result.summary.failedRequests/t.result.summary.totalRequests*100:0}getExecutionStrategy(t){switch(t){case"load":return{requestMultiplier:1,errorInjectionRate:0};case"stress":return{requestMultiplier:1.5,errorInjectionRate:.01};case"spike":return{requestMultiplier:3,errorInjectionRate:.02};case"soak":return{requestMultiplier:.8,errorInjectionRate:0};case"breakpoint":return{requestMultiplier:2,errorInjectionRate:.05};default:return{requestMultiplier:1,errorInjectionRate:0}}}calculateCurrentVirtualUsers(t,e,r){let{virtualUsers:i,rampUp:n=0,rampDown:s=0}=t,{start:a,max:o,pattern:l}=i;switch(l){case"constant":return o;case"ramp":if(e<n)return Math.round(a+(o-a)*(e/n));if(e>r-s){let u=(r-e)/s;return Math.round(a+(o-a)*u)}return o;case"step":{let d=r/5,m=Math.floor(e/d),p=(o-a)/5;return Math.round(a+p*m)}case"spike":return e%3e4<5e3?o:a;default:return o}}async executeBatch(t,e,r){let i=Math.round(e*r.requestMultiplier),n=Math.min(i,this.config.connectionPoolSize),s=this.createBatches(i,n),a=[];for(let u of s){let d=Date.now(),m=await Promise.all(u.map(()=>this.executeRequest(t,r)));a.push(...m);let p=Date.now()-d,h=1e3/Math.max(e,1)*u.length;p<h&&await this.sleep(h-p)}let o=a.filter(u=>u.success).map(u=>u.latency),l=a.filter(u=>!u.success).map(u=>u.error||"Unknown error");return{totalRequests:a.length,successfulRequests:a.filter(u=>u.success).length,failedRequests:a.filter(u=>!u.success).length,responseTimes:o,errors:l}}async executeRequest(t,e){let r=Date.now(),i=r;if(e.errorInjectionRate>0&&z()<e.errorInjectionRate)return{status:0,latency:Date.now()-r,success:!1,error:"Simulated error injection",timestamp:i};try{let{url:n,method:s="GET",headers:a,body:o}=t.target,l={headers:a,timeout:this.config.defaultTimeout,retries:0,circuitBreaker:!1},u;switch(s.toUpperCase()){case"POST":u=await this.httpClient.post(n,o,l);break;case"PUT":u=await this.httpClient.put(n,o,l);break;case"DELETE":u=await this.httpClient.delete(n,l);break;default:u=await this.httpClient.get(n,l);break}if(u.success){let d=u.value;return{status:d.status,latency:Date.now()-r,success:d.ok,error:d.ok?void 0:`HTTP ${d.status}: ${d.statusText}`,timestamp:i}}else return{status:u.error.status??0,latency:Date.now()-r,success:!1,error:u.error.message,timestamp:i}}catch(n){return{status:0,latency:Date.now()-r,success:!1,error:P(n),timestamp:i}}}createBatches(t,e){let r=[],i=t;for(;i>0;){let n=Math.min(i,e);r.push(Array.from({length:n},(s,a)=>a)),i-=n}return r}percentile(t,e){if(t.length===0)return 0;let r=Math.ceil(e/100*t.length)-1;return t[Math.max(0,Math.min(r,t.length-1))]}evaluateAssertions(t,e){return t.map(r=>{let i=this.getMetricValue(r.metric,e),n=this.checkAssertion(r,i);return{assertion:r,passed:n,actualValue:i}})}getMetricValue(t,e){switch(t){case"response-time":return e.avgResponseTime;case"throughput":return e.requestsPerSecond;case"error-rate":return e.errorRate;case"p95":return e.p95ResponseTime;case"p99":return e.p99ResponseTime;default:return 0}}checkAssertion(t,e){switch(t.operator){case"lt":return e<t.value;case"gt":return e>t.value;case"lte":return e<=t.value;case"gte":return e>=t.value;default:return!1}}determineTestStatus(t){return t.status==="aborted"?"aborted":t.assertionResults.filter(r=>!r.passed).length>0||t.summary.errorRate>10?"failed":"completed"}finalizeExecution(t){let e={testId:t.result.testId,status:t.result.status,duration:t.result.duration,summary:t.result.summary,timeline:t.result.timeline,errors:t.result.errors,assertionResults:t.result.assertionResults};return this.memory.set(`loadtest:results:${t.testId}:${Date.now()}`,e,{namespace:"chaos-resilience",persist:!0}),e}sleep(t){return new Promise(e=>setTimeout(e,t))}};_();k();ge();X();var nk={defaultTimeout:6e4,healthCheckInterval:1e3,maxRetries:3,recoveryCheckDelay:500,simulateRandomFailures:!1},cr=x.create("chaos-resilience/performance-profiler"),Bi=class{constructor(t,e={}){this.memory=t;this.config={...nk,...e},this.httpClient=is()}memory;config;httpClient;async testRecovery(t,e,r){let i=w();try{let n=[],s=await this.checkServiceHealth(t);if(n.push({timestamp:new Date,event:"Initial health check",status:s?"healthy":"unhealthy"}),!s)return f({service:t,faultType:e,recoveryTime:0,expectedRecoveryTime:r,passed:!1,timeline:n});n.push({timestamp:new Date,event:`Injecting fault: ${e}`,status:"degraded"}),await this.injectFault(t,e);let a=await this.checkServiceHealth(t);n.push({timestamp:new Date,event:"Post-fault health check",status:a?"healthy":"unhealthy"}),n.push({timestamp:new Date,event:"Removing fault",status:"degraded"}),await this.removeFault(t,e);let o=Date.now(),l=0,u=!1,d=r*2;for(;Date.now()-o<d;){if(await this.checkServiceHealth(t)){l=Date.now()-o,u=!0,n.push({timestamp:new Date,event:"Service recovered",status:"healthy"});break}n.push({timestamp:new Date,event:"Recovery check - still degraded",status:"degraded"}),await this.sleep(this.config.recoveryCheckDelay)}u||n.push({timestamp:new Date,event:"Recovery timeout exceeded",status:"unhealthy"});let m={service:t,faultType:e,recoveryTime:l,expectedRecoveryTime:r,passed:u&&l<=r,timeline:n};return await this.storeTestResult("recovery",i,m),f(m)}catch(n){return g(y(n))}}async testFailover(t,e){let r=w();try{let i=[],n=1,[s,a]=await Promise.all([this.checkServiceHealth(t),this.checkServiceHealth(e)]);if(i.push({order:n++,action:"Verify primary service health",duration:0,success:s}),i.push({order:n++,action:"Verify secondary service health",duration:0,success:a}),!s||!a)return f({primaryService:t,secondaryService:e,failoverTime:0,dataLoss:!0,passed:!1,steps:i});let o=await this.captureServiceState(t);i.push({order:n++,action:"Capture primary service state",duration:0,success:!0});let l=Date.now();await this.injectFault(t,"process-kill"),i.push({order:n++,action:"Trigger primary service failure",duration:Date.now()-l,success:!0});let u=Date.now(),d=!1,m=0;for(;Date.now()-u<this.config.defaultTimeout;){if(await this.checkServiceIsActive(e)){m=Date.now()-l,d=!0;break}await this.sleep(this.config.healthCheckInterval)}i.push({order:n++,action:"Detect failover completion",duration:m,success:d});let p=await this.captureServiceState(e),h=!this.compareServiceStates(o,p);i.push({order:n++,action:"Verify data integrity on secondary",duration:0,success:!h}),await this.removeFault(t,"process-kill"),i.push({order:n++,action:"Restore primary service",duration:0,success:!0});let v={primaryService:t,secondaryService:e,failoverTime:m,dataLoss:h,passed:d&&!h,steps:i};return await this.storeTestResult("failover",r,v),f(v)}catch(i){return g(y(i))}}async testCircuitBreaker(t,e){let r=w();try{let i=e?.errorThreshold??5,n=e?.timeout??this.config.defaultTimeout,s=e?.halfOpenRequests??3;await this.getCircuitState(t)!=="closed"&&await this.resetCircuit(t);let o=0,l=!1;for(let b=0;b<i*2;b++)if(await this.generateError(t),o++,await this.getCircuitState(t)==="open"){l=!0;break}let u=!1,d=Date.now();for(;Date.now()-d<n;){if(await this.getCircuitState(t)==="half-open"){u=!0;break}await this.sleep(this.config.healthCheckInterval)}let m="correct";if(u){let b=0;for(let S=0;S<s;S++)await this.sendSuccessfulRequest(t)&&b++;await this.getCircuitState(t)!=="closed"&&b===s&&(m="incorrect")}let p=!1,h=Date.now();for(;Date.now()-h<n;){if(await this.getCircuitState(t)==="closed"){p=!0;break}await this.sendSuccessfulRequest(t),await this.sleep(this.config.healthCheckInterval)}let v={service:t,opened:l,openedAfterErrors:o,closedAfterRecovery:p,halfOpenBehavior:m,passed:l&&p&&m==="correct"};return await this.storeTestResult("circuit-breaker",r,v),f(v)}catch(i){return g(y(i))}}async testRateLimiting(t,e){let r=w();try{let i=0,n={statusCode:429,retryAfter:void 0,body:void 0},s=[1,5,10,25,50,100,200],a=0,o=!1;for(let m of s){if(o)break;let p=await this.sendRequestBatch(t,m);a+=m;for(let h of p)if(h.statusCode===429){o=!0,i=a-(m-p.indexOf(h)),n=h;break}}o||(i=a);let l=e*.2,u=Math.abs(i-e)<=l||!o,d={service:t,expectedLimit:e,actualLimit:i,passed:o&&u,responseWhenLimited:n};return await this.storeTestResult("rate-limit",r,d),f(d)}catch(i){return g(y(i))}}async checkServiceHealth(t){if(!this.isRealServiceUrl(t))return this.simulateHealthCheck();try{return await this.httpClient.healthCheck(t)}catch{return this.simulateHealthCheck()}}isRealServiceUrl(t){return t.startsWith("http://")||t.startsWith("https://")}simulateHealthCheck(){return this.config.simulateRandomFailures?z()>.05:!0}async checkServiceIsActive(t){if(!this.isRealServiceUrl(t))return this.simulateServiceActive();try{let e=await this.httpClient.get(t,{timeout:5e3,retries:1});return e.success&&e.value.ok}catch{return this.simulateServiceActive()}}simulateServiceActive(){return this.config.simulateRandomFailures?z()>.1:!0}async injectFault(t,e){if(this.isRealServiceUrl(t))try{let r=`${t}/_chaos/inject`;await this.httpClient.post(r,{faultType:e},{timeout:5e3,retries:0});return}catch{cr.debug("Fault injection API failed:")}cr.info(`Injecting fault ${e} into service: ${t}`),await this.sleep(100)}async removeFault(t,e){if(this.isRealServiceUrl(t))try{let r=`${t}/_chaos/remove`;await this.httpClient.post(r,{faultType:e},{timeout:5e3,retries:0});return}catch{cr.debug("Fault removal API failed:")}cr.info(`Removing fault ${e} from service: ${t}`),await this.sleep(50)}async captureServiceState(t){if(this.isRealServiceUrl(t))try{let r=`${t}/_state`,i=await this.httpClient.get(r,{timeout:5e3,retries:1});if(i.success&&i.value.ok){let n=await i.value.text(),s=this.calculateChecksum(n),a=this.parseRecordCount(n);return{checksum:s,timestamp:new Date,records:a}}}catch{cr.debug("State capture API failed:")}return await this.captureMemoryState(t)}calculateChecksum(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return`chk_${Math.abs(e).toString(16)}`}parseRecordCount(t){try{let e=D(t);return e.records??e.count??e.total??e.length??0}catch{return t.split(`
3001
+ `).filter(e=>e.trim()).length}}async captureMemoryState(t){let e=`resilience:state:${this.hashServiceName(t)}`,r=await this.memory.get(e);if(r)return r;let i={checksum:`init_${w().slice(0,8)}`,timestamp:new Date,records:0};return await this.memory.set(e,i,{namespace:"chaos-resilience"}),i}hashServiceName(t){let e=0;for(let r of t)e=(e<<5)-e+r.charCodeAt(0),e=e&e;return Math.abs(e).toString(16)}compareServiceStates(t,e){let r=t.checksum===e.checksum,i=t.records===e.records;return r||i}async getCircuitState(t){try{return this.httpClient.getCircuitState(t).state}catch{return"closed"}}async resetCircuit(t){try{this.httpClient.resetCircuit(t)}catch{cr.info(`Resetting circuit breaker for: ${t}`)}}async generateError(t){if(this.isRealServiceUrl(t))try{let e=`${t}/_chaos/error`;await this.httpClient.post(e,{},{timeout:5e3,retries:0});return}catch{cr.debug("Error generation API failed:")}cr.info(`Generating error for: ${t}`)}async sendSuccessfulRequest(t){if(!this.isRealServiceUrl(t))return!0;try{let e=await this.httpClient.get(t,{timeout:5e3,retries:1});return e.success&&e.value.ok}catch{return!0}}async sendRequestBatch(t,e){let r=[];if(!this.isRealServiceUrl(t))return this.simulateRequestBatch(e);for(let i=0;i<e;i++)try{let n=await this.httpClient.get(t,{timeout:2e3,retries:0,circuitBreaker:!1});if(n.success){let s=n.value,a=s.headers.get("Retry-After");r.push({statusCode:s.status,retryAfter:a?parseInt(a,10):void 0})}else r.push({statusCode:500,body:{error:n.error.message}})}catch{return[...r,...this.simulateRequestBatch(e-i)]}return r}simulateRequestBatch(t){let e=[];for(let i=0;i<t;i++)i>=75?e.push({statusCode:429,retryAfter:60,body:{error:"Rate limit exceeded"}}):e.push({statusCode:200});return e}async storeTestResult(t,e,r){await this.memory.set(`resilience:${t}:${e}`,r,{namespace:"chaos-resilience",persist:!0})}sleep(t){return new Promise(e=>setTimeout(e,t))}};ge();var sk={stateSize:10,actionSize:5,hiddenLayers:[64,64],learningRatePG:.01,gammaPG:.99,entropyCoeff:.01},Rc=class extends ve{policy;pgConfig;actions=[];episodeLog=[];constructor(t={}){super("policy-gradient","policy-based"),this.pgConfig={...sk,...t},this.initializeActions(),this.policy=new J({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.pgConfig.learningRatePG})}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.policy.forward(e),i=Ie.forward(r),n=this.sampleAction(i),s=this.actions[n],a=i[n],o=Math.max(.3,Math.min(1,a+.4));return this.episodeLog.push({state:t,action:s,reward:0}),{action:s,confidence:o,reasoning:this.generateReasoning(t,s,a)}}async trainCore(t){let e=this.groupIntoEpisodes(t),r=0;for(let i of e){let n=this.calculateReturns(i);for(let s=0;s<i.length;s++){let{state:a,action:o}=i[s],l=n[s],u=this.prepareState(a),d=this.policy.forward(u),m=Ie.forward(d),p=this.actionToIndex(o),v=-Math.log(m[p]+1e-10)*l;r+=Math.abs(v);let b=new Float32Array(m.length);for(let C=0;C<b.length;C++)C===p?b[C]=-l*(1-m[C]):b[C]=l*m[C];this.policy.backward(b);for(let C of this.policy.layers)C.update(this.pgConfig.learningRatePG)}}return this.episodeLog=[],{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/t.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural Policy Gradient (REINFORCE) for Resource Allocation",capabilities:["Neural policy optimization","Monte Carlo return estimation","Entropy regularization"],hyperparameters:{stateSize:this.pgConfig.stateSize,actionSize:this.pgConfig.actionSize,learningRatePG:this.pgConfig.learningRatePG,gammaPG:this.pgConfig.gammaPG},stats:this.stats}}prepareState(t){let e=t.features.slice(0,this.pgConfig.stateSize);for(;e.length<this.pgConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]=e[i]/r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"allocate",value:{agentType:"tester",count:1}},{type:"allocate",value:{agentType:"analyzer",count:1}},{type:"reallocate",value:{domain:"test-execution"}},{type:"scale-up",value:1},{type:"scale-down",value:1}],this.pgConfig.actionSize=this.actions.length,this.policy=new J({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.pgConfig.learningRatePG})}actionToIndex(t){let e=this.actionToKey(t);for(let r=0;r<this.actions.length;r++)if(this.actionToKey(this.actions[r])===e)return r;return 0}actionToKey(t){return`${t.type}:${JSON.stringify(t.value)}`}sampleAction(t){if(z()<this.config.explorationRate)return Se(0,this.actions.length);let e=z(),r=0;for(let i=0;i<t.length;i++)if(r+=t[i],e<=r)return i;return this.argmax(t)}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}calculateReturns(t){let e=[],r=0;for(let i=t.length-1;i>=0;i--)r=t[i].reward+this.pgConfig.gammaPG*r,e.unshift(r);return e}groupIntoEpisodes(t){let e=[],r=[];for(let i of t)r.push(i),i.done&&(e.push(r),r=[]);return r.length>0&&e.push(r),e}generateReasoning(t,e,r){return`Neural Policy Gradient: ${e.type} (probability: ${r.toFixed(3)})`}async exportCustomData(){return{policy:this.policy.getParameters(),pgConfig:this.pgConfig}}async importCustomData(t){t.policy&&this.policy.setParameters(t.policy),t.pgConfig&&(this.pgConfig={...this.pgConfig,...t.pgConfig}),this.initialized=!0}async resetAlgorithm(){this.policy=new J({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new Q).concat([new K]),learningRate:this.pgConfig.learningRatePG}),this.episodeLog=[]}};var ak={maxConcurrentWorkflows:3,defaultTimeout:3e5,enableAutomatedExperiments:!1,publishEvents:!0,enablePolicyGradient:!0,enableQESONA:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},me=x.create("chaos-resilience"),Tc=class extends ie{constructor(e,r,i,n={},s){let a={...ak,...n};super(e,"chaos-resilience",a,{verifyFindingTypes:["chaos-experiment","resilience-assessment","failure-injection"],...a.consensusConfig});this.memory=r;this.agentCoordinator=i;this.chaosGovernanceMixin=_p(this.domainName),this.chaosEngineer=new Vi({memory:r,llmRouter:s}),this.loadTester=new zi(r),this.performanceProfiler=new Bi(r)}memory;agentCoordinator;chaosEngineer;loadTester;performanceProfiler;policyGradient;qesona;chaosGovernanceMixin;async onInitialize(){if(this.config.enablePolicyGradient)try{this.policyGradient=new Rc({stateSize:10,actionSize:5,hiddenLayers:[64,64]}),me.info("PolicyGradient algorithm created successfully")}catch(e){throw me.error("Failed to create PolicyGradient:",e instanceof Error?e:void 0),new Error(`PolicyGradient creation failed: ${P(e)}`)}if(this.config.enableQESONA)try{this.qesona=await De({domain:"chaos-resilience",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:5e3,minConfidence:.6}),me.info("PersistentSONAEngine initialized successfully")}catch(e){me.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),me.warn("Continuing without SONA pattern persistence"),this.qesona=void 0}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState(),this.qesona&&(await this.qesona.close(),this.qesona=void 0),this.policyGradient=void 0}getActiveWorkflows(){return super.getActiveWorkflows()}async runChaosSuite(e){let r=w();try{if(this.startWorkflow(r,"chaos-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&me.warn("Topology degraded, using conservative chaos strategy"),this.minCutMixin.shouldPauseOperations())return g(new Error("Chaos suite paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return g(new Error("Agent limit reached, cannot spawn chaos agents"));let i=await this.spawnChaosAgent(r,"coordinator");if(!i.success)return this.failWorkflow(r,i.error.message),g(i.error);this.addAgentToWorkflow(r,i.value);let n=[],s=[],a=0,o=0;for(let u=0;u<e.length;u++){let d=e[u];this.updateWorkflowProgress(r,Math.round((u+1)/e.length*100));let m=await this.chaosEngineer.runExperiment(d);if(m.success){if(n.push(m.value),m.value.hypothesisValidated)a++;else{o++;let p=this.generateRecommendationsFromExperiment(m.value);s.push(...p)}this.config.publishEvents&&await this.publishExperimentCompleted(m.value)}else o++,s.push({priority:"high",category:"experiment-failure",recommendation:`Failed to run experiment ${d}: ${m.error.message}`,effort:"moderate"})}await this.agentCoordinator.stop(i.value),this.completeWorkflow(r);let l={totalExperiments:e.length,passed:a,failed:o,results:n,recommendations:s};return await this.storeReport("chaos-suite",r,l),f(l)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async runLoadTestSuite(e){let r=w();try{if(this.startWorkflow(r,"load-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&me.warn("Topology degraded, using conservative load test parameters"),this.minCutMixin.shouldPauseOperations())return g(new Error("Load test suite paused: topology is in critical state"));let i=await this.spawnLoadTestAgent(r,"orchestrator");if(!i.success)return this.failWorkflow(r,i.error.message),g(i.error);this.addAgentToWorkflow(r,i.value);let n=[],s=[],a=0,o=0;for(let u=0;u<e.length;u++){let d=e[u];this.updateWorkflowProgress(r,Math.round((u+1)/e.length*100));let m=await this.loadTester.runTest(d);if(m.success){n.push(m.value),m.value.status==="completed"?a++:o++;let p=this.detectBottlenecks(m.value);s.push(...p),this.config.publishEvents&&await this.publishLoadTestCompleted(m.value)}else o++}await this.agentCoordinator.stop(i.value),this.completeWorkflow(r);let l={totalTests:e.length,passed:a,failed:o,results:n,bottlenecks:s};return await this.storeReport("load-suite",r,l),f(l)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async assessResilience(e){let r=w();try{if(this.startWorkflow(r,"assessment"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&me.warn("Topology degraded, assessment may be limited"),this.minCutMixin.shouldPauseOperations())return g(new Error("Resilience assessment paused: topology is in critical state"));let i=new Map,n=[],s=[],a=[],o=await this.spawnAssessmentAgent(r);if(!o.success)return this.failWorkflow(r,o.error.message),g(o.error);this.addAgentToWorkflow(r,o.value);for(let d=0;d<e.length;d++){let m=e[d];this.updateWorkflowProgress(r,Math.round((d+1)/e.length*100));let p=await this.performanceProfiler.testRecovery(m,"latency",5e3),h=await this.performanceProfiler.testCircuitBreaker(m),v=await this.performanceProfiler.testRateLimiting(m,100),b=0;if(p.success&&p.value.passed)b+=33.3,n.push(`${m}: Fast recovery (${p.value.recoveryTime}ms)`);else{let C=p.success?p.value.recoveryTime:"unknown";s.push({service:m,type:"recovery",description:"Slow or failed recovery after fault",risk:_s.create(.7)}),a.push({priority:"high",category:"recovery",recommendation:`Improve ${m} recovery time - currently ${C}ms`,effort:"moderate"})}h.success&&h.value.passed?(b+=33.3,n.push(`${m}: Circuit breaker functioning correctly`)):(s.push({service:m,type:"circuit-breaker",description:"Circuit breaker not functioning as expected",risk:_s.create(.6)}),a.push({priority:"medium",category:"circuit-breaker",recommendation:`Review ${m} circuit breaker configuration`,effort:"minor"})),v.success&&v.value.passed?(b+=33.4,n.push(`${m}: Rate limiting effective`)):(s.push({service:m,type:"rate-limiting",description:"Rate limiting not properly configured",risk:_s.create(.5)}),a.push({priority:"medium",category:"rate-limiting",recommendation:`Configure rate limiting for ${m}`,effort:"minor"})),i.set(m,b)}let l=e.length>0?Array.from(i.values()).reduce((d,m)=>d+m,0)/e.length:0;await this.agentCoordinator.stop(o.value),this.completeWorkflow(r);let u={overallScore:l,serviceScores:i,strengths:n,weaknesses:s,recommendations:a};return await this.storeReport("assessment",r,u),f(u)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async generateExperiments(e){let r=w();try{this.startWorkflow(r,"experiment-generation");let i=[];for(let n of e.services){let s=this.generateServiceExperiments(n,e.dependencies);i.push(...s)}for(let n of e.criticalPaths){let s=this.generateCriticalPathExperiment(n,e);i.push(s)}for(let n of i)await this.chaosEngineer.createExperiment(n);return this.completeWorkflow(r),f(i)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async runStrategicChaosSuite(e,r){let i=w();try{if(this.startWorkflow(i,"chaos-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&me.warn("Topology degraded, adjusting strategic chaos parameters"),this.minCutMixin.shouldPauseOperations())return g(new Error("Strategic chaos suite paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return g(new Error("Agent limit reached, cannot spawn chaos agents"));let n=await this.selectChaosStrategy(e,r);if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);let s=n.value.selectedExperiments;if(me.info(`[chaos-resilience] Using ${n.value.strategy} strategy with ${s.length} experiments (confidence: ${n.value.confidence.toFixed(2)})`),s.length===0)return this.completeWorkflow(i),f({totalExperiments:0,passed:0,failed:0,results:[],recommendations:[{priority:"low",category:"strategy",recommendation:"No experiments selected - consider adjusting strategy context",effort:"trivial"}]});let a=await this.spawnChaosAgent(i,"coordinator");if(!a.success)return this.failWorkflow(i,a.error.message),g(a.error);this.addAgentToWorkflow(i,a.value);let o=[],l=[],u=0,d=0;for(let p of s)await this.chaosEngineer.createExperiment(p);for(let p=0;p<s.length;p++){let h=s[p];this.updateWorkflowProgress(i,Math.round((p+1)/s.length*100));let v=await this.chaosEngineer.runExperiment(h.id);if(v.success){if(o.push(v.value),v.value.hypothesisValidated)u++;else{d++;let C=this.generateRecommendationsFromExperiment(v.value);l.push(...C)}let b=v.value.hypothesisValidated?.8:.2;await this.storeResiliencePattern(h,v.value,b),this.config.publishEvents&&await this.publishExperimentCompleted(v.value)}else d++,l.push({priority:"high",category:"experiment-failure",recommendation:`Failed to run experiment ${h.name}: ${v.error.message}`,effort:"moderate"})}await this.agentCoordinator.stop(a.value),this.completeWorkflow(i);let m={totalExperiments:s.length,passed:u,failed:d,results:o,recommendations:l};return await this.storeReport("strategic-chaos-suite",i,m),f(m)}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async getResilienceDashboard(){try{let e=await this.memory.search("chaos:results:*",10),r=await this.memory.search("loadtest:results:*",10),i,n,s=0,a=0,o=0,l=0,u=0;for(let v of e){let b=await this.memory.get(v);b&&((!i||b.startTime>i)&&(i=b.startTime),s+=b.incidents.filter(C=>!C.resolved).length)}for(let v of r){let b=await this.memory.get(v);if(b&&b.timeline.length>0){let C=b.timeline[0].timestamp;(!n||C>n)&&(n=C),u++,b.status==="failed"&&l++}}let d=o>0?a/o:0,m=u>0?l/u*100:0,p="healthy";return s>5||m>25?p="unhealthy":(s>0||m>10)&&(p="degraded"),f({overallHealth:p,lastExperimentDate:i,lastLoadTestDate:n,activeIncidents:s,uptime:99.9,mttr:d,changeFailureRate:m})}catch(e){return g(y(e))}}async spawnChaosAgent(e,r){let i={name:`chaos-${r}-${e.slice(0,8)}`,domain:"chaos-resilience",type:"specialist",capabilities:["chaos-engineering","fault-injection",r],config:{workflowId:e}};return this.agentCoordinator.spawn(i)}async spawnLoadTestAgent(e,r){let i={name:`loadtest-${r}-${e.slice(0,8)}`,domain:"chaos-resilience",type:"specialist",capabilities:["load-testing","performance",r],config:{workflowId:e}};return this.agentCoordinator.spawn(i)}async spawnAssessmentAgent(e){let r={name:`assessment-${e.slice(0,8)}`,domain:"chaos-resilience",type:"analyzer",capabilities:["resilience-assessment","analysis"],config:{workflowId:e}};return this.agentCoordinator.spawn(r)}async publishExperimentCompleted(e){let r={id:w(),type:"chaos-resilience.ExperimentCompleted",timestamp:new Date,source:"chaos-resilience",payload:{experimentId:e.experimentId,status:e.status,hypothesisValidated:e.hypothesisValidated,incidentCount:e.incidents.length}};await this.eventBus.publish(r)}async publishLoadTestCompleted(e){let r={id:w(),type:"chaos-resilience.LoadTestCompleted",timestamp:new Date,source:"chaos-resilience",payload:{testId:e.testId,status:e.status,summary:e.summary,assertionsPassed:e.assertionResults.filter(i=>i.passed).length,assertionsFailed:e.assertionResults.filter(i=>!i.passed).length}};await this.eventBus.publish(r)}generateRecommendationsFromExperiment(e){let r=[];e.hypothesisValidated||r.push({priority:"high",category:"hypothesis-failure",recommendation:`Experiment ${e.experimentId} hypothesis was not validated - review system behavior under fault conditions`,effort:"moderate"}),e.steadyStateVerified||r.push({priority:"critical",category:"steady-state",recommendation:"System did not maintain steady state - investigate stability issues",effort:"major"});for(let i of e.incidents)(i.severity==="critical"||i.severity==="high")&&r.push({priority:i.severity,category:"incident",recommendation:`Address ${i.type}: ${i.message}`,effort:"moderate"});return r}detectBottlenecks(e){let r=[];return e.summary.p95ResponseTime>1e3&&r.push({location:"api",type:"network",description:`P95 response time is ${e.summary.p95ResponseTime}ms (>1000ms)`,impact:e.summary.p95ResponseTime>2e3?"high":"medium",recommendation:"Investigate API response time, consider caching or query optimization"}),e.summary.errorRate>5&&r.push({location:"service",type:"cpu",description:`Error rate is ${e.summary.errorRate.toFixed(2)}% (>5%)`,impact:e.summary.errorRate>10?"high":"medium",recommendation:"Investigate error causes, scale resources if under load"}),e.summary.requestsPerSecond<10&&r.push({location:"backend",type:"io",description:`Low throughput: ${e.summary.requestsPerSecond.toFixed(2)} RPS`,impact:"medium",recommendation:"Review I/O operations, database queries, and connection pooling"}),r}generateServiceExperiments(e,r){let i=[];i.push(this.createExperiment(`${e.name}-latency`,`Test ${e.name} behavior under latency`,"latency",e.name)),i.push(this.createExperiment(`${e.name}-error`,`Test ${e.name} error handling`,"error",e.name)),i.push(this.createExperiment(`${e.name}-cpu-stress`,`Test ${e.name} under CPU stress`,"cpu-stress",e.name));let n=r.filter(s=>s.from===e.name);for(let s of n)s.criticality==="critical"&&i.push(this.createExperiment(`${e.name}-${s.to}-failure`,`Test ${e.name} when ${s.to} fails`,"error",s.to));return i}generateCriticalPathExperiment(e,r){let i=e.join("-");return{id:w(),name:`critical-path-${i}`,description:`Test critical path: ${e.join(" -> ")}`,hypothesis:{statement:"System should handle partial path failure gracefully",metrics:[{metric:"error_rate",operator:"lt",value:10},{metric:"response_time_ms",operator:"lt",value:2e3}],tolerances:[{metric:"error_rate",maxDeviation:5,unit:"percent"}]},steadyState:{description:"All services in path are healthy",probes:e.map(n=>({name:`${n}-health`,type:"http",target:`http://${n}/health`,expected:{status:200},timeout:5e3}))},faults:e.slice(0,-1).map(n=>({id:w(),type:"latency",target:{type:"service",selector:n},parameters:{latencyMs:500},duration:3e4})),blastRadius:{scope:"subset",percentage:50,excludeProduction:!0},rollbackPlan:{automatic:!0,triggerConditions:[{type:"error-rate",condition:"error_rate > 20"},{type:"timeout",condition:"duration > 60000"}],steps:[{order:1,action:"Remove all faults",timeout:5e3},{order:2,action:"Verify service health"}]}}}createExperiment(e,r,i,n){return{id:w(),name:e,description:r,hypothesis:{statement:`${n} should recover within 5 seconds from ${i}`,metrics:[{metric:"response_time_ms",operator:"lt",value:1e3},{metric:"error_rate",operator:"lt",value:5}],tolerances:[{metric:"response_time_ms",maxDeviation:50,unit:"percent"}]},steadyState:{description:`${n} is healthy and responsive`,probes:[{name:`${n}-health`,type:"http",target:`http://${n}/health`,expected:{status:200},timeout:5e3}]},faults:[{id:w(),type:i,target:{type:"service",selector:n},parameters:this.getDefaultFaultParameters(i),duration:3e4}],blastRadius:{scope:"single",excludeProduction:!0},rollbackPlan:{automatic:!0,triggerConditions:[{type:"error-rate",condition:"error_rate > 50"}],steps:[{order:1,action:`Remove ${i} fault`},{order:2,action:"Verify recovery"}]}}}getDefaultFaultParameters(e){return{latency:{latencyMs:500},error:{errorCode:500},timeout:{timeoutMs:3e4},"packet-loss":{packetLossPercent:10},"cpu-stress":{cpuPercent:80},"memory-stress":{memoryBytes:268435456},"disk-stress":{},"network-partition":{},"dns-failure":{},"process-kill":{}}[e]||{}}async storeReport(e,r,i){await this.memory.set(`chaos-resilience:reports:${e}:${r}`,i,{namespace:"chaos-resilience",persist:!0})}async selectChaosStrategy(e,r){if(!this.policyGradient||!this.config.enablePolicyGradient)return f({strategy:"default",selectedExperiments:this.getDefaultExperiments(e.slice(0,3)),confidence:1,reasoning:"Default strategy (PolicyGradient disabled)"});if(e.length===0)return f({strategy:"empty",selectedExperiments:[],confidence:1,reasoning:"No services provided"});try{let i={id:`chaos-strategy-${Date.now()}`,features:[r.riskTolerance,r.availableCapacity/100,e.length/50,e.filter(u=>!u.hasFailover).length/Math.max(1,e.length),e.filter(u=>u.type==="database").length/Math.max(1,e.length),r.environment==="production"?0:1,r.environment==="staging"?1:0,e.filter(u=>u.type==="cache").length/Math.max(1,e.length),e.filter(u=>u.type==="queue").length/Math.max(1,e.length),e.reduce((u,d)=>u+d.replicas,0)/Math.max(1,e.length*5)]},n=await this.policyGradient.predict(i),s=[],a="default";switch(n.action.type){case"allocate":{let u=typeof n.action.value=="object"?n.action.value:null;if(u&&"agentType"in u&&u.agentType==="tester"){let d=e.filter(m=>!m.hasFailover||m.type==="database").slice(0,3);s=this.generateExperimentsForServices(d,["latency","error"]),a="allocate-critical"}break}case"reallocate":{let u=typeof n.action.value=="object"?n.action.value:null;u&&"domain"in u&&u.domain==="test-execution"&&(s=this.generateExperimentsForServices(e.slice(0,5),["cpu-stress","memory-stress"]),a="reallocate-resource-stress");break}case"scale-up":s=this.generateExperimentsForServices(e,["latency","error","timeout"]),a="scale-up-comprehensive";break;case"scale-down":s=this.generateExperimentsForServices(e.slice(0,2),["latency"]),a="scale-down-minimal";break;default:s=this.getDefaultExperiments(e.slice(0,3)),a="default";break}let o=await this.calculateStrategyReward(s,r),l=n.action;return await this.policyGradient.train({state:i,action:l,reward:o,nextState:i,done:!0}),me.info(`[chaos-resilience] PolicyGradient selected ${a} strategy for ${e.length} services (confidence: ${n.confidence.toFixed(2)})`),f({strategy:a,selectedExperiments:s,confidence:n.confidence,reasoning:n.reasoning||`PolicyGradient selected: ${a}`})}catch(i){return me.error("PolicyGradient strategy selection failed:",i instanceof Error?i:void 0),f({strategy:"fallback",selectedExperiments:this.getDefaultExperiments(e.slice(0,3)),confidence:.5,reasoning:"Fallback to default (PolicyGradient error)"})}}generateExperimentsForServices(e,r){let i=[];for(let n of e)for(let s of r)i.push(this.createExperiment(`${n.name}-${s}-${Date.now()}`,`Test ${n.name} with ${s} fault`,s,n.name));return i}getDefaultExperiments(e){return this.generateExperimentsForServices(e,["latency","error"])}async calculateStrategyReward(e,r){let i=.5,n=e.length;(r.riskTolerance>.7&&n>5||r.riskTolerance<.3&&n<=3)&&(i+=.2),(r.availableCapacity>70&&n>5||r.availableCapacity<30&&n<=3)&&(i+=.1);let s=new Set(e.map(a=>a.faults[0]?.type));return i+=Math.min(.1,s.size/5),Math.max(0,Math.min(1,i))}async storeResiliencePattern(e,r,i){if(!(!this.qesona||!this.config.enableQESONA))try{let n={id:`chaos-${e.id}`,features:[e.faults.length/10,e.faults[0]?.duration?e.faults[0].duration/6e4:0,e.steadyState.probes.length/20,e.blastRadius.excludeProduction?1:0,(e.blastRadius.percentage??0)/100,r.hypothesisValidated?1:0,r.steadyStateVerified?1:0,r.incidents.length/10,r.incidents.filter(a=>a.severity==="critical").length/5,i]},s={type:r.hypothesisValidated?"validate":"reject",value:i};this.qesona.createPattern(n,s,{reward:r.hypothesisValidated?i:-i,success:r.hypothesisValidated,quality:i},"defect-prediction","chaos-resilience",{experimentId:e.id,experimentName:e.name,faultType:e.faults[0]?.type,hypothesisValidated:r.hypothesisValidated}),me.info(`Stored resilience pattern for ${e.id} (validated: ${r.hypothesisValidated}, quality: ${i.toFixed(2)})`)}catch(n){me.error("Failed to store resilience pattern:",n instanceof Error?n:void 0)}}async adaptStrategies(e,r){if(!this.qesona||!this.config.enableQESONA)return{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5};try{let i={id:`chaos-adapt-${e.name}-${Date.now()}`,features:[e.hasFailover?0:1,r.riskTolerance,e.type==="api"?1:0,e.type==="database"?1:0,e.type==="cache"?1:0,r.environment==="production"?1:0,r.environment==="staging"?1:0,e.replicas/10,e.type==="worker"?1:0,e.type==="queue"?1:0]},n=await this.qesona.adaptPattern(i,"defect-prediction","chaos-resilience");if(n.success&&n.pattern){let s=n.pattern.outcome.success,a=this.getRecommendedFaults(n.pattern.action.type);return me.info(`[chaos-resilience] QESONA adapted strategy for ${e.name}: shouldRun=${s}, faults=${a.join(",")}, confidence=${n.similarity.toFixed(2)}`),{shouldRunChaos:s,recommendedFaults:a,confidence:n.similarity}}return{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5}}catch(i){return me.error("QESONA strategy adaptation failed:",i instanceof Error?i:void 0),{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5}}}getRecommendedFaults(e){switch(e){case"validate":return["latency","error","timeout"];case"reject":return["latency"];case"allocate":return["latency","cpu-stress"];case"scale-up":return["latency","error","timeout","packet-loss"];case"scale-down":return["latency"];default:return["latency","error"]}}subscribeToEvents(){this.eventBus.subscribe("quality-assessment.DeploymentApproved",this.handleDeploymentApproved.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGateEvaluated.bind(this))}async handleDeploymentApproved(e){if(!this.config.enableAutomatedExperiments)return;let r=e.payload;r.services&&await this.memory.set(`chaos-resilience:pending-assessment:${e.id}`,r.services,{namespace:"chaos-resilience",ttl:3600})}async handleQualityGateEvaluated(e){let r=e.payload;r.passed||await this.memory.set(`chaos-resilience:quality-gate-failures:${e.id}`,r,{namespace:"chaos-resilience",ttl:86400})}async loadWorkflowState(){let e=await this.memory.get("chaos-resilience:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("chaos-resilience:coordinator:workflows",e,{namespace:"chaos-resilience",persist:!0})}async verifyChaosExperiment(e,r){let i=U({id:w(),type:"chaos-experiment",confidence:r,description:`Verify chaos experiment safety: ${e.name} (${e.faultType}) on ${e.target}`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:e.blastRadius==="full"?"critical":r>.9?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(me.info(`Chaos experiment '${e.name}' verified safe by consensus`),!0):(me.warn(`Chaos experiment '${e.name}' NOT verified safe: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyResilienceAssessment(e,r){let i=U({id:w(),type:"resilience-assessment",confidence:r,description:`Verify resilience assessment for ${e.service}: score ${e.overallScore}, ${e.weaknessCount} weaknesses`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:e.overallScore<50?"critical":e.overallScore<70?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(me.info(`Resilience assessment for '${e.service}' verified by consensus`),!0):(me.warn(`Resilience assessment for '${e.service}' NOT verified`),!1)}return!0}async verifyFailureInjection(e,r){let i=U({id:w(),type:"failure-injection",confidence:r,description:`Verify failure injection: ${e.faultType} on ${e.target} for ${e.duration}ms`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:"critical"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(me.info(`Failure injection '${e.faultType}' on '${e.target}' verified safe by consensus`),!0):(me.warn(`Failure injection '${e.faultType}' NOT verified safe: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}};k();var nm=class extends te{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;chaosEngineer=null;loadTester=null;performanceProfiler=null;pluginConfig;get name(){return"chaos-resilience"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{runChaosSuite:this.runChaosSuite.bind(this),runLoadTestSuite:this.runLoadTestSuite.bind(this),assessResilience:this.assessResilience.bind(this),generateExperiments:this.generateExperiments.bind(this),getResilienceDashboard:this.getResilienceDashboard.bind(this),createExperiment:this.createExperiment.bind(this),runExperiment:this.runExperiment.bind(this),abortExperiment:this.abortExperiment.bind(this),verifySteadyState:this.verifySteadyState.bind(this),injectFault:this.injectFault.bind(this),removeFault:this.removeFault.bind(this),createTest:this.createTest.bind(this),runTest:this.runTest.bind(this),runLoadTest:this.runTest.bind(this),stopTest:this.stopTest.bind(this),getRealtimeMetrics:this.getRealtimeMetrics.bind(this),generateFromTraffic:this.generateFromTraffic.bind(this),getExperimentHistory:this.getExperimentHistory.bind(this),testRecovery:this.testRecovery.bind(this),testFailover:this.testFailover.bind(this),testCircuitBreaker:this.testCircuitBreaker.bind(this),testRateLimiting:this.testRateLimiting.bind(this),selectChaosStrategy:this.coordinator.selectChaosStrategy.bind(this.coordinator),runStrategicChaosSuite:this.coordinator.runStrategicChaosSuite.bind(this.coordinator),getCoordinator:()=>this.coordinator,getChaosEngineer:()=>this.chaosEngineer,getChaosEngine:()=>this.chaosEngineer,getLoadTester:()=>this.loadTester,getPerformanceProfiler:()=>this.performanceProfiler,getResilienceAssessor:()=>this.performanceProfiler}}getTaskHandlers(){return new Map([["run-experiment",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.experimentId;return r?this.coordinator.runChaosSuite([r]):g(new Error("Invalid run-experiment payload: missing experimentId"))}],["run-load-test",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.testId;return r?this.coordinator.runLoadTestSuite([r]):g(new Error("Invalid run-load-test payload: missing testId"))}],["assess-resilience",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.services;return!r||r.length===0?g(new Error("Invalid assess-resilience payload: missing services")):this.coordinator.assessResilience(r)}],["inject-fault",async e=>{if(!this.chaosEngineer)return g(new Error("Chaos engineer not initialized"));let r=e.faultType,i=e.target;if(!r||!i)return g(new Error("Invalid inject-fault payload: missing faultType or target"));let n={id:`fault-${Date.now()}`,type:r,target:{type:"service",selector:i},parameters:e.parameters??{},duration:e.duration??3e4,probability:e.probability};return this.chaosEngineer.injectFault(n)}]])}async onInitialize(){this.chaosEngineer=new Vi({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.chaosEngineer),this.loadTester=new zi(this.memory,this.pluginConfig.loadTester),this.performanceProfiler=new Bi(this.memory,this.pluginConfig.performanceProfiler),this.coordinator=new Tc(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.chaosEngineer=null,this.loadTester=null,this.performanceProfiler=null}subscribeToEvents(){this.eventBus.subscribe("quality-assessment.DeploymentApproved",this.handleDeploymentApproved.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("security-compliance.VulnerabilityDetected",this.handleVulnerabilityDetected.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"quality-assessment.DeploymentApproved":await this.handleDeploymentApproved(e);break;case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(e);break;case"security-compliance.VulnerabilityDetected":await this.handleVulnerabilityDetected(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGateEvaluated(e);break;default:break}}async runChaosSuite(e){this.ensureInitialized();try{let r=await this.coordinator.runChaosSuite(e);return r.success?this.trackSuccessfulOperation("chaos-suite"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async runLoadTestSuite(e){this.ensureInitialized();try{let r=await this.coordinator.runLoadTestSuite(e);return r.success?this.trackSuccessfulOperation("load-suite"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async assessResilience(e){this.ensureInitialized();try{return await this.coordinator.assessResilience(e)}catch(r){return this.handleError(r)}}async generateExperiments(e){this.ensureInitialized();try{return await this.coordinator.generateExperiments(e)}catch(r){return this.handleError(r)}}async getResilienceDashboard(){this.ensureInitialized();try{return await this.coordinator.getResilienceDashboard()}catch(e){return this.handleError(e)}}async createExperiment(e){this.ensureInitialized();try{return await this.chaosEngineer.createExperiment(e)}catch(r){return this.handleError(r)}}async runExperiment(e){this.ensureInitialized();try{let r=await this.chaosEngineer.runExperiment(e);return r.success&&await this.publishExperimentEvent(r.value),r}catch(r){return this.handleError(r)}}async abortExperiment(e,r){this.ensureInitialized();try{return await this.chaosEngineer.abortExperiment(e,r)}catch(i){return this.handleError(i)}}async verifySteadyState(e){this.ensureInitialized();try{return await this.chaosEngineer.verifySteadyState(e)}catch(r){return this.handleError(r)}}async injectFault(e){this.ensureInitialized();try{return await this.chaosEngineer.injectFault(e)}catch(r){return this.handleError(r)}}async removeFault(e){this.ensureInitialized();try{return await this.chaosEngineer.removeFault(e)}catch(r){return this.handleError(r)}}async getExperimentHistory(){this.ensureInitialized();try{return{success:!0,value:await this.memory.get("chaos-resilience:experiment-history")??[]}}catch(e){return this.handleError(e)}}async createTest(e){this.ensureInitialized();try{return await this.loadTester.createTest(e)}catch(r){return this.handleError(r)}}async runTest(e){this.ensureInitialized();try{let r=await this.loadTester.runTest(e);return r.success&&await this.publishLoadTestEvent(r.value),r}catch(r){return this.handleError(r)}}async stopTest(e){this.ensureInitialized();try{return await this.loadTester.stopTest(e)}catch(r){return this.handleError(r)}}async getRealtimeMetrics(e){this.ensureInitialized();try{return await this.loadTester.getRealtimeMetrics(e)}catch(r){return this.handleError(r)}}async generateFromTraffic(e,r){this.ensureInitialized();try{return await this.loadTester.generateFromTraffic(e,r)}catch(i){return this.handleError(i)}}async testRecovery(e,r,i){this.ensureInitialized();try{return await this.performanceProfiler.testRecovery(e,r,i)}catch(n){return this.handleError(n)}}async testFailover(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testFailover(e,r)}catch(i){return this.handleError(i)}}async testCircuitBreaker(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testCircuitBreaker(e,r)}catch(i){return this.handleError(i)}}async testRateLimiting(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testRateLimiting(e,r)}catch(i){return this.handleError(i)}}async handleDeploymentApproved(e){let r=e.payload;r.services&&r.services.length>0&&await this.memory.set(`chaos-resilience:pending-assessment:${e.id}`,{services:r.services,triggeredAt:new Date,source:"deployment-approved"},{namespace:"chaos-resilience",ttl:3600})}async handleTestRunCompleted(e){let r=e.payload;await this.memory.set(`chaos-resilience:test-baseline:${r.runId}`,{duration:r.duration,successRate:r.passed/(r.passed+r.failed),timestamp:new Date},{namespace:"chaos-resilience",ttl:86400})}async handleVulnerabilityDetected(e){let r=e.payload;(r.severity==="critical"||r.severity==="high")&&await this.memory.set(`chaos-resilience:security-tests:${r.vulnId}`,{vulnerabilityId:r.vulnId,severity:r.severity,file:r.file,triggeredAt:new Date},{namespace:"chaos-resilience",ttl:86400})}async handleQualityGateEvaluated(e){let r=e.payload;r.checks?.some(n=>n.name==="resilience")&&await this.memory.set(`chaos-resilience:gate-context:${r.gateId}`,{gateId:r.gateId,passed:r.passed,checks:r.checks,timestamp:Date.now()},{namespace:"chaos-resilience",ttl:3600})}async publishExperimentEvent(e){await this.publishEvent("chaos-resilience.ExperimentCompleted",{experimentId:e.experimentId,status:e.status,hypothesisValidated:e.hypothesisValidated,steadyStateVerified:e.steadyStateVerified,faultCount:e.faultResults.length,incidentCount:e.incidents.length,duration:e.endTime?e.endTime.getTime()-e.startTime.getTime():0})}async publishLoadTestEvent(e){await this.publishEvent("chaos-resilience.LoadTestCompleted",{testId:e.testId,status:e.status,duration:e.duration,totalRequests:e.summary.totalRequests,successRate:e.summary.totalRequests>0?e.summary.successfulRequests/e.summary.totalRequests*100:0,p95ResponseTime:e.summary.p95ResponseTime,errorRate:e.summary.errorRate,assertionsPassed:e.assertionResults.filter(r=>r.passed).length,assertionsFailed:e.assertionResults.filter(r=>!r.passed).length})}ensureInitialized(){if(!this._initialized)throw new Error("ChaosResiliencePlugin is not initialized");if(!this.coordinator||!this.chaosEngineer||!this.loadTester||!this.performanceProfiler)throw new Error("ChaosResiliencePlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function Uv(c,t,e,r,i){return new nm(c,t,e,r,i)}_();var ok="learning-optimization",Oe=Object.freeze({namespace:ok}),lr="learning:pattern:",ck=["creation","archived"];function sm(c){if(!c.startsWith(lr))return!1;let t=c.slice(lr.length);if(t.length===0)return!1;let e=t.split(":",1)[0];return!ck.includes(e)}function lk(c,t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.id!="string"||c!==`${lr}${e.id}`?!1:!!e.context&&typeof e.context=="object"}async function Ec(c,t={}){let e=await wr(c,`${lr}*`,{retrieve:t.retrieve,pageSize:t.scanPageSize}),r=[];for(let i of e){if(!sm(i))continue;let n=await c.get(i,t.retrieve);lk(i,n)&&r.push(pe(n,["createdAt","lastUsedAt"]))}return r}var Qv=new Set(["test-generation:test-generated","coverage-analysis:gap-detection","defect-intelligence:defect-prediction","code-intelligence:impact-analysis"]);function uk(c){return c.rewardSource?c.rewardSource:Qv.has(`${c.agentId?.value}:${c.action}`)?"assigned":"measured"}function dk(c){return uk(c)==="measured"}function It(c){let t=c.filter(dk);return{measured:t,assignedExcluded:c.length-t.length}}var mk=/^\/\/ Common actions: (.*)$/m;function pk(c){if(c.rewardSource)return c.rewardSource;let t=mk.exec(c.template?.content??""),e=t?t[1].split(",").map(i=>i.trim()).filter(Boolean):[];return e.length>0&&e.every(i=>Qv.has(`${c.domain}:${i}`))?"assigned":"measured"}function am(c){return c.rewardSource?c.rewardSource:pk(c)==="assigned"?"assigned":"pre-1120"}function hs(c){return am(c)==="measured"}k();_();k();async function Kv(c,t,e=new Date){let r=`${lr}${t.id}`;if(!sm(r))return"missing";let i=await c.get(r,Oe);if(!i||i.id!==t.id||gk(i,t))return"missing";let n=`${lr}archived:${t.id}`;await c.set(n,{...t,archivedAt:e},{...Oe,persist:!0});let s=await c.get(n,Oe);return s&&s.id===t.id?"copied":"failed"}async function Jv(c,t){await c.delete(`${lr}${t.id}`,Oe)}function gk(c,t){let e=r=>new Date(r).getTime();return!Object.is(c.usageCount,t.usageCount)||!Object.is(c.confidence,t.confidence)||!Object.is(c.successRate,t.successRate)||!Object.is(e(c.lastUsedAt),e(t.lastUsedAt))}function Yv(c,t){let e=c.reduce((r,i)=>r+i.usageCount,0);return c.reduce((r,i)=>r+t(i)*(e>0?i.usageCount/e:1/c.length),0)}function Xv(c,t,e=new Date){let r=c.reduce((n,s)=>s.successRate>n.successRate?s:n),i={language:r.context.language,framework:r.context.framework,testType:r.context.testType,codeContext:r.context.codeContext,tags:[...new Set(c.flatMap(n=>n.context.tags))]};return{id:t,type:r.type,domain:r.domain,name:`consolidated-${r.name}`,description:`Consolidated from ${c.length} patterns`,confidence:Yv(c,n=>n.confidence),usageCount:c.reduce((n,s)=>n+s.usageCount,0),successRate:Yv(c,n=>n.successRate),context:i,template:r.template,createdAt:e,lastUsedAt:e,rewardSource:c.every(hs)?"measured":"assigned"}}Pe();hr();var hk={minExperiencesForPattern:5,patternConfidenceThreshold:.7,maxPatternsPerDomain:100,anomalyDeviationThreshold:2,clusterSimilarityThreshold:.8,enableLLMSynthesis:!0,llmModelTier:2,llmMaxTokens:2048},Ac=x.create("learning-optimization/learning-coordinator"),Ze={namespace:"learning-optimization"};function Zv(c){return Ec(c,{retrieve:Ze})}var zr=class{config;memory;llmRouter;flashAttention=null;_nullStore;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...hk,...e}}async initializeFlashAttention(t){return this.flashAttention=await tt("pattern-adaptation",t),Ac.info("FlashAttention initialized for pattern adaptation"),this.flashAttention}injectFlashAttention(t){this.flashAttention=t}isFlashAttentionAvailable(){return this.flashAttention!==null}getFlashAttentionMetrics(){return this.flashAttention?this.flashAttention.getMetrics():[]}async computeSimilarityWithFlashAttention(t,e){if(!this.flashAttention)throw new Error("[LearningCoordinatorService] FlashAttention not initialized. Call initializeFlashAttention() first.");let r=Math.min(t.length,e.length),i=new Float32Array(r),n=new Float32Array(r),s=new Float32Array(r);for(let l=0;l<r;l++)i[l]=t[l],n[l]=e[l],s[l]=1;let a=await this.flashAttention.computeFlashAttention(i,n,s,1,r),o=Math.abs(a[0]);return Math.min(1,o)}async batchComputeSimilarities(t,e,r=5){if(!this.flashAttention)throw new Error("[LearningCoordinatorService] FlashAttention not initialized. Call initializeFlashAttention() first.");let i=new Float32Array(t),n=e.map(s=>new Float32Array(s));return this.flashAttention.computeTestSimilarity(i,n,r)}disposeFlashAttention(){this.flashAttention&&(this.flashAttention.dispose(),this.flashAttention=null)}isLLMSynthesisAvailable(){return this.config.enableLLMSynthesis&&this.llmRouter!==void 0}getModelForTier(t){return ae(t)}async synthesizePatternsWithLLM(t){if(!this.isLLMSynthesisAvailable())return null;try{let e=t.slice(0,10).map(i=>`- ${i.name}: ${i.type} (confidence: ${i.confidence.toFixed(2)})`).join(`
3002
3002
  `);return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze these learned QE patterns and synthesize insights:
3003
3003
  ${e}
3004
3004
 
3005
3005
  Provide:
3006
3006
  1. Common themes across patterns
3007
3007
  2. Potential pattern combinations
3008
- 3. Recommendations for pattern application`}],maxTokens:this.config.llmMaxTokens})).content}catch{return Ac.warn("LLM synthesis failed:"),null}}async learnPattern(t){try{let{measured:e,assignedExcluded:r}=It(t);if(e.length<this.config.minExperiencesForPattern){let d=r>0?` (${r} with an assigned reward excluded)`:"";return g(new Error(`Need at least ${this.config.minExperiencesForPattern} measured experiences to learn a pattern${d}`))}let i=this.extractCommonActions(e),n=this.calculateSuccessRate(e);if(n<this.config.patternConfidenceThreshold)return g(new Error(`Success rate ${n} below threshold ${this.config.patternConfidenceThreshold}`));let s=this.inferPatternType(e),a=e[0].domain,o=this.generatePatternTemplate(e,i),l=this.extractPatternContext(e),u={id:w(),type:s,domain:a,name:`${s}-${a}-${Date.now()}`,description:`Learned pattern from ${e.length} experiences with ${n*100}% success rate`,confidence:n,usageCount:0,successRate:n,context:l,template:o,createdAt:new Date,lastUsedAt:new Date,rewardSource:"measured"};return await this.storePattern(u),await this.recordPatternCreation(u,e),f(u)}catch(e){return g(y(e))}}async findMatchingPatterns(t,e=10){try{let r=(await Zv(this.memory)).filter(i=>hs(i)&&this.matchesContext(i,t));return r.sort((i,n)=>{let s=i.confidence*.6+i.successRate*.4;return n.confidence*.6+n.successRate*.4-s}),f(r.slice(0,e))}catch(r){return g(y(r))}}async applyPattern(t,e){try{let r=t.template.content;for(let i of t.template.variables){let n=(Object.hasOwn(e,i.name)?e[i.name]:void 0)??i.defaultValue;if(i.required&&n===void 0)return g(new Error(`Required variable ${i.name} not provided`));r=r.replace(new RegExp(`\\{\\{${i.name}\\}\\}`,"g"),String(n??""))}return await this.updatePatternUsage(t.id),f(r)}catch(r){return g(y(r))}}async updatePatternFeedback(t,e){try{let r=`learning:pattern:${t}`,i=await this.memory.get(r,Ze);if(!i)return g(new Error(`Pattern ${t} not found`));let n=.1,s=n*(e?1:0)+(1-n)*i.successRate,a=Math.min(i.usageCount/100,1),o=s*.7+a*.3,l={...i,successRate:s,confidence:o,usageCount:i.usageCount+1,lastUsedAt:new Date};return await this.memory.set(r,l,{namespace:"learning-optimization",persist:!0}),f(void 0)}catch(r){return g(y(r))}}async consolidatePatterns(t){try{if(t.length<2)return g(new Error("Need at least 2 patterns to consolidate"));let e=[];for(let a of t){let o=await this.memory.get(`learning:pattern:${a}`,Ze);o&&e.push(o)}if(e.length<2)return g(new Error("Not enough valid patterns found"));let r=Xv(e,w()),i=new Date,n=0;for(let a of e)await Kv(this.memory,a,i)!=="copied"&&n++;if(n>0)return g(new Error(`${n} of ${e.length} source patterns could not be archived (archive copy not verified); nothing was merged and every source pattern was left active`));await this.storePattern(r);let s=await this.memory.get(`learning:pattern:${r.id}`,Ze);if(!s||s.id!==r.id)return g(new Error("Consolidated pattern could not be read back; nothing was merged and every source pattern was left active"));for(let a of e)await Jv(this.memory,a);return f(r)}catch(e){return g(y(e))}}async getPatternStats(t){try{let e=(await Zv(this.memory)).filter(d=>!t||d.domain===t),r=e.filter(hs),i=e.filter(d=>am(d)==="pre-1120").length,n=e.length-r.length-i,s={"test-pattern":0,"fix-pattern":0,"optimization-pattern":0,"detection-pattern":0,"workflow-pattern":0,"failure-pattern":0},a={"test-generation":0,"test-execution":0,"coverage-analysis":0,"quality-assessment":0,"defect-intelligence":0,"requirements-validation":0,"code-intelligence":0,"security-compliance":0,"contract-testing":0,"visual-accessibility":0,"chaos-resilience":0,"learning-optimization":0,"enterprise-integration":0,coordination:0},o=0,l=0;for(let d of r)s[d.type]++,a[d.domain]++,o+=d.confidence,l+=d.successRate;let u=r.sort((d,m)=>m.successRate-d.successRate).slice(0,10);return f({totalPatterns:r.length,byType:s,byDomain:a,avgConfidence:r.length>0?o/r.length:0,avgSuccessRate:r.length>0?l/r.length:0,topPatterns:u,...n>0?{assignedPatternsExcluded:n}:{},...i>0?{legacyPatternsExcluded:i}:{}})}catch(e){return g(y(e))}}async recordExperience(t){try{let e=w(),r={...t,id:e,timestamp:new Date};return await this.memory.set(`learning:experience:${e}`,r,{namespace:"learning-optimization",ttl:86400*30}),await this.indexExperience(r),!t.result.success&&t.appliedPatternIds?.length&&await this.recordPatternNulls(r),f(e)}catch(e){return g(y(e))}}async getNullStore(){if(this._nullStore!==void 0)return this._nullStore||void 0;try{let{getUnifiedPersistence:t}=await import("./unified-persistence-UCV7YETW.js"),e=t();if(!e.isInitialized()){this._nullStore=null;return}let{PatternNullStore:r}=await import("./pattern-null-store-RFNVA46O.js");return this._nullStore=new r(e.getDatabase()),this._nullStore}catch(t){this._nullStore=null,Ac.warn("Null store wiring skipped",{error:t instanceof Error?t.message:String(t)});return}}async recordPatternNulls(t){let e=await this.getNullStore();if(!e)return;let r=`${t.domain}:${t.action}`;for(let i of t.appliedPatternIds??[])try{e.recordNull({patternId:i,contextFingerprint:r,failureMode:String(t.result.outcome?.error??t.action),evidenceClass:"EXECUTED"})}catch(n){Ac.warn("Failed to record pattern null",{patternId:i,error:n instanceof Error?n.message:String(n)})}}async getExperiences(t,e){try{return f(await this.getExperiencesByDomainAndTime(t,e))}catch(r){return g(y(r))}}async getExperiencesByIds(t){try{let e=[];for(let r of new Set(t)){let i=await this.memory.get(`learning:experience:${r}`,Ze);i&&e.push(i)}return f(e)}catch(e){return g(y(e))}}async mineExperiences(t,e){try{let r=await this.getExperiencesByDomainAndTime(t,e),{measured:i,assignedExcluded:n}=It(r),s={experienceCount:r.length,measuredExperienceCount:i.length,assignedRewardsExcluded:n};if(i.length===0)return f({...s,evidenceStatus:"insufficient-evidence",successRate:null,avgReward:null,patterns:[],anomalies:[],recommendations:[r.length===0?"No experiences found in the given time range":`No measured outcomes in the given time range; ${n} experience(s) with an assigned reward were not scored`]});let a=this.calculateSuccessRate(i),o=this.calculateAverageReward(i),l=await this.extractPatternsFromExperiences(i),u=this.detectAnomalies(i),d=this.generateRecommendations(i,a,u);return f({...s,successRate:a,avgReward:o,patterns:l,anomalies:u,recommendations:d})}catch(r){return g(y(r))}}calculateReward(t,e){let r=t.outcome[e.metric]??0,i;e.direction==="maximize"?i=Math.min(r/100,1):i=Math.max(1-r/100,0);let n=0;for(let o of e.constraints){let l=t.outcome[o.metric]??0;this.isConstraintViolated(o,l)&&(n+=.2)}let s=t.success?.5:0,a=Math.max(0,i+s-n);return Math.min(1,a)}async getReplayBuffer(t,e=100){try{let r=await this.memory.search(`learning:experience:index:agent:${t.value}:*`,e,Ze),i=[];for(let n of r){let s="learning-optimization:",a=n.startsWith(s)?n.slice(s.length):n,o=await this.memory.get(a,Ze);if(o){let l=pe(await this.memory.get(`learning:experience:${o}`,Ze),["timestamp"]);l&&i.push(l)}}return i.sort((n,s)=>s.timestamp.getTime()-n.timestamp.getTime()),f(i.slice(0,e))}catch(r){return g(y(r))}}async clusterExperiences(t){try{if(t.length===0)return f([]);let e=new Map;for(let n of t){let s=!1;for(let[a,o]of e)if(this.actionsSimilar(n.action,a)){o.push(n),s=!0;break}s||e.set(n.action,[n])}let r=[],i=0;for(let[n,s]of e)if(s.length>=2){let a=this.calculateCentroid(s),o=this.extractCommonActions(s),{measured:l}=It(s),u=l.length>0?this.calculateAverageReward(l):null;r.push({id:`cluster-${i++}`,centroid:a,experiences:s,commonActions:o,avgReward:u})}return f(r)}catch(e){return g(y(e))}}async storePattern(t){await this.memory.set(`learning:pattern:${t.id}`,t,{namespace:"learning-optimization",persist:!0})}async updatePatternUsage(t){let e=`learning:pattern:${t}`,r=await this.memory.get(e,Ze);if(r){let i={...r,usageCount:r.usageCount+1,lastUsedAt:new Date};await this.memory.set(e,i,{namespace:"learning-optimization",persist:!0})}}async recordPatternCreation(t,e){await this.memory.set(`learning:pattern:creation:${t.id}`,{patternId:t.id,experienceIds:e.map(r=>r.id),createdAt:new Date},{namespace:"learning-optimization",persist:!0})}async indexExperience(t){await this.memory.set(`learning:experience:index:agent:${t.agentId.value}:${t.id}`,t.id,{namespace:"learning-optimization",ttl:86400*30}),await this.memory.set(`learning:experience:index:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",ttl:86400*30})}async getExperiencesByDomainAndTime(t,e){let r=await this.memory.search(`learning:experience:index:domain:${t}:*`,1e3,Ze),i=[];for(let n of r){let s="learning-optimization:",a=n.startsWith(s)?n.slice(s.length):n,o=await this.memory.get(a,Ze);if(o){let l=await this.memory.get(`learning:experience:${o}`,Ze);if(l){let u=l.timestamp instanceof Date?l.timestamp:new Date(l.timestamp);e.contains(u)&&i.push({...l,timestamp:u})}}}return i}async extractPatternsFromExperiences(t){let e=new Map;for(let i of t){let n=e.get(i.action)||[];n.push(i),e.set(i.action,n)}let r=[];for(let[i,n]of e)if(n.length>=this.config.minExperiencesForPattern){let s=await this.learnPattern(n);s.success&&r.push(s.value)}return r}matchesContext(t,e){if(e.language&&t.context.language!==e.language||e.framework&&t.context.framework!==e.framework||e.testType&&t.context.testType!==e.testType)return!1;if(e.tags.length>0){let r=Array.isArray(t.context.tags)?t.context.tags:[];if(!e.tags.some(n=>r.includes(n)))return!1}return!0}extractCommonActions(t){let e=new Map;for(let r of t){let i=e.get(r.action)||0;e.set(r.action,i+1)}return Array.from(e.entries()).filter(([r,i])=>i>=t.length*.3).map(([r])=>r)}calculateAverageReward(t){return t.length===0?0:t.reduce((r,i)=>r+i.reward,0)/t.length}calculateSuccessRate(t){return t.length===0?0:t.filter(r=>r.result.success).length/t.length}inferPatternType(t){let e=t.map(r=>r.action.toLowerCase());return e.some(r=>r.includes("test")||r.includes("generate"))?"test-pattern":e.some(r=>r.includes("fix")||r.includes("repair"))?"fix-pattern":e.some(r=>r.includes("optimize")||r.includes("improve"))?"optimization-pattern":e.some(r=>r.includes("detect")||r.includes("find"))?"detection-pattern":e.some(r=>r.includes("workflow")||r.includes("process"))?"workflow-pattern":e.some(r=>r.includes("fail")||r.includes("error"))?"failure-pattern":"workflow-pattern"}generatePatternTemplate(t,e){let r=[{name:"domain",type:"string",required:!0,description:"Target domain for the pattern"},{name:"action",type:"string",required:!0,defaultValue:e[0],description:"Primary action to execute"}];return{type:"workflow",content:`// Pattern learned from ${t.length} experiences
3008
+ 3. Recommendations for pattern application`}],maxTokens:this.config.llmMaxTokens})).content}catch{return Ac.warn("LLM synthesis failed:"),null}}async learnPattern(t){try{let{measured:e,assignedExcluded:r}=It(t);if(e.length<this.config.minExperiencesForPattern){let d=r>0?` (${r} with an assigned reward excluded)`:"";return g(new Error(`Need at least ${this.config.minExperiencesForPattern} measured experiences to learn a pattern${d}`))}let i=this.extractCommonActions(e),n=this.calculateSuccessRate(e);if(n<this.config.patternConfidenceThreshold)return g(new Error(`Success rate ${n} below threshold ${this.config.patternConfidenceThreshold}`));let s=this.inferPatternType(e),a=e[0].domain,o=this.generatePatternTemplate(e,i),l=this.extractPatternContext(e),u={id:w(),type:s,domain:a,name:`${s}-${a}-${Date.now()}`,description:`Learned pattern from ${e.length} experiences with ${n*100}% success rate`,confidence:n,usageCount:0,successRate:n,context:l,template:o,createdAt:new Date,lastUsedAt:new Date,rewardSource:"measured"};return await this.storePattern(u),await this.recordPatternCreation(u,e),f(u)}catch(e){return g(y(e))}}async findMatchingPatterns(t,e=10){try{let r=(await Zv(this.memory)).filter(i=>hs(i)&&this.matchesContext(i,t));return r.sort((i,n)=>{let s=i.confidence*.6+i.successRate*.4;return n.confidence*.6+n.successRate*.4-s}),f(r.slice(0,e))}catch(r){return g(y(r))}}async applyPattern(t,e){try{let r=t.template.content;for(let i of t.template.variables){let n=(Object.hasOwn(e,i.name)?e[i.name]:void 0)??i.defaultValue;if(i.required&&n===void 0)return g(new Error(`Required variable ${i.name} not provided`));r=r.replace(new RegExp(`\\{\\{${i.name}\\}\\}`,"g"),String(n??""))}return await this.updatePatternUsage(t.id),f(r)}catch(r){return g(y(r))}}async updatePatternFeedback(t,e){try{let r=`learning:pattern:${t}`,i=await this.memory.get(r,Ze);if(!i)return g(new Error(`Pattern ${t} not found`));let n=.1,s=n*(e?1:0)+(1-n)*i.successRate,a=Math.min(i.usageCount/100,1),o=s*.7+a*.3,l={...i,successRate:s,confidence:o,usageCount:i.usageCount+1,lastUsedAt:new Date};return await this.memory.set(r,l,{namespace:"learning-optimization",persist:!0}),f(void 0)}catch(r){return g(y(r))}}async consolidatePatterns(t){try{if(t.length<2)return g(new Error("Need at least 2 patterns to consolidate"));let e=[];for(let a of t){let o=await this.memory.get(`learning:pattern:${a}`,Ze);o&&e.push(o)}if(e.length<2)return g(new Error("Not enough valid patterns found"));let r=Xv(e,w()),i=new Date,n=0;for(let a of e)await Kv(this.memory,a,i)!=="copied"&&n++;if(n>0)return g(new Error(`${n} of ${e.length} source patterns could not be archived (archive copy not verified); nothing was merged and every source pattern was left active`));await this.storePattern(r);let s=await this.memory.get(`learning:pattern:${r.id}`,Ze);if(!s||s.id!==r.id)return g(new Error("Consolidated pattern could not be read back; nothing was merged and every source pattern was left active"));for(let a of e)await Jv(this.memory,a);return f(r)}catch(e){return g(y(e))}}async getPatternStats(t){try{let e=(await Zv(this.memory)).filter(d=>!t||d.domain===t),r=e.filter(hs),i=e.filter(d=>am(d)==="pre-1120").length,n=e.length-r.length-i,s={"test-pattern":0,"fix-pattern":0,"optimization-pattern":0,"detection-pattern":0,"workflow-pattern":0,"failure-pattern":0},a={"test-generation":0,"test-execution":0,"coverage-analysis":0,"quality-assessment":0,"defect-intelligence":0,"requirements-validation":0,"code-intelligence":0,"security-compliance":0,"contract-testing":0,"visual-accessibility":0,"chaos-resilience":0,"learning-optimization":0,"enterprise-integration":0,coordination:0},o=0,l=0;for(let d of r)s[d.type]++,a[d.domain]++,o+=d.confidence,l+=d.successRate;let u=r.sort((d,m)=>m.successRate-d.successRate).slice(0,10);return f({totalPatterns:r.length,byType:s,byDomain:a,avgConfidence:r.length>0?o/r.length:0,avgSuccessRate:r.length>0?l/r.length:0,topPatterns:u,...n>0?{assignedPatternsExcluded:n}:{},...i>0?{legacyPatternsExcluded:i}:{}})}catch(e){return g(y(e))}}async recordExperience(t){try{let e=w(),r={...t,id:e,timestamp:new Date};return await this.memory.set(`learning:experience:${e}`,r,{namespace:"learning-optimization",ttl:86400*30}),await this.indexExperience(r),!t.result.success&&t.appliedPatternIds?.length&&await this.recordPatternNulls(r),f(e)}catch(e){return g(y(e))}}async getNullStore(){if(this._nullStore!==void 0)return this._nullStore||void 0;try{let{getUnifiedPersistence:t}=await import("./unified-persistence-5ZOUPKHF.js"),e=t();if(!e.isInitialized()){this._nullStore=null;return}let{PatternNullStore:r}=await import("./pattern-null-store-QGPUIV6M.js");return this._nullStore=new r(e.getDatabase()),this._nullStore}catch(t){this._nullStore=null,Ac.warn("Null store wiring skipped",{error:t instanceof Error?t.message:String(t)});return}}async recordPatternNulls(t){let e=await this.getNullStore();if(!e)return;let r=`${t.domain}:${t.action}`;for(let i of t.appliedPatternIds??[])try{e.recordNull({patternId:i,contextFingerprint:r,failureMode:String(t.result.outcome?.error??t.action),evidenceClass:"EXECUTED"})}catch(n){Ac.warn("Failed to record pattern null",{patternId:i,error:n instanceof Error?n.message:String(n)})}}async getExperiences(t,e){try{return f(await this.getExperiencesByDomainAndTime(t,e))}catch(r){return g(y(r))}}async getExperiencesByIds(t){try{let e=[];for(let r of new Set(t)){let i=await this.memory.get(`learning:experience:${r}`,Ze);i&&e.push(i)}return f(e)}catch(e){return g(y(e))}}async mineExperiences(t,e){try{let r=await this.getExperiencesByDomainAndTime(t,e),{measured:i,assignedExcluded:n}=It(r),s={experienceCount:r.length,measuredExperienceCount:i.length,assignedRewardsExcluded:n};if(i.length===0)return f({...s,evidenceStatus:"insufficient-evidence",successRate:null,avgReward:null,patterns:[],anomalies:[],recommendations:[r.length===0?"No experiences found in the given time range":`No measured outcomes in the given time range; ${n} experience(s) with an assigned reward were not scored`]});let a=this.calculateSuccessRate(i),o=this.calculateAverageReward(i),l=await this.extractPatternsFromExperiences(i),u=this.detectAnomalies(i),d=this.generateRecommendations(i,a,u);return f({...s,successRate:a,avgReward:o,patterns:l,anomalies:u,recommendations:d})}catch(r){return g(y(r))}}calculateReward(t,e){let r=t.outcome[e.metric]??0,i;e.direction==="maximize"?i=Math.min(r/100,1):i=Math.max(1-r/100,0);let n=0;for(let o of e.constraints){let l=t.outcome[o.metric]??0;this.isConstraintViolated(o,l)&&(n+=.2)}let s=t.success?.5:0,a=Math.max(0,i+s-n);return Math.min(1,a)}async getReplayBuffer(t,e=100){try{let r=await this.memory.search(`learning:experience:index:agent:${t.value}:*`,e,Ze),i=[];for(let n of r){let s="learning-optimization:",a=n.startsWith(s)?n.slice(s.length):n,o=await this.memory.get(a,Ze);if(o){let l=pe(await this.memory.get(`learning:experience:${o}`,Ze),["timestamp"]);l&&i.push(l)}}return i.sort((n,s)=>s.timestamp.getTime()-n.timestamp.getTime()),f(i.slice(0,e))}catch(r){return g(y(r))}}async clusterExperiences(t){try{if(t.length===0)return f([]);let e=new Map;for(let n of t){let s=!1;for(let[a,o]of e)if(this.actionsSimilar(n.action,a)){o.push(n),s=!0;break}s||e.set(n.action,[n])}let r=[],i=0;for(let[n,s]of e)if(s.length>=2){let a=this.calculateCentroid(s),o=this.extractCommonActions(s),{measured:l}=It(s),u=l.length>0?this.calculateAverageReward(l):null;r.push({id:`cluster-${i++}`,centroid:a,experiences:s,commonActions:o,avgReward:u})}return f(r)}catch(e){return g(y(e))}}async storePattern(t){await this.memory.set(`learning:pattern:${t.id}`,t,{namespace:"learning-optimization",persist:!0})}async updatePatternUsage(t){let e=`learning:pattern:${t}`,r=await this.memory.get(e,Ze);if(r){let i={...r,usageCount:r.usageCount+1,lastUsedAt:new Date};await this.memory.set(e,i,{namespace:"learning-optimization",persist:!0})}}async recordPatternCreation(t,e){await this.memory.set(`learning:pattern:creation:${t.id}`,{patternId:t.id,experienceIds:e.map(r=>r.id),createdAt:new Date},{namespace:"learning-optimization",persist:!0})}async indexExperience(t){await this.memory.set(`learning:experience:index:agent:${t.agentId.value}:${t.id}`,t.id,{namespace:"learning-optimization",ttl:86400*30}),await this.memory.set(`learning:experience:index:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",ttl:86400*30})}async getExperiencesByDomainAndTime(t,e){let r=await this.memory.search(`learning:experience:index:domain:${t}:*`,1e3,Ze),i=[];for(let n of r){let s="learning-optimization:",a=n.startsWith(s)?n.slice(s.length):n,o=await this.memory.get(a,Ze);if(o){let l=await this.memory.get(`learning:experience:${o}`,Ze);if(l){let u=l.timestamp instanceof Date?l.timestamp:new Date(l.timestamp);e.contains(u)&&i.push({...l,timestamp:u})}}}return i}async extractPatternsFromExperiences(t){let e=new Map;for(let i of t){let n=e.get(i.action)||[];n.push(i),e.set(i.action,n)}let r=[];for(let[i,n]of e)if(n.length>=this.config.minExperiencesForPattern){let s=await this.learnPattern(n);s.success&&r.push(s.value)}return r}matchesContext(t,e){if(e.language&&t.context.language!==e.language||e.framework&&t.context.framework!==e.framework||e.testType&&t.context.testType!==e.testType)return!1;if(e.tags.length>0){let r=Array.isArray(t.context.tags)?t.context.tags:[];if(!e.tags.some(n=>r.includes(n)))return!1}return!0}extractCommonActions(t){let e=new Map;for(let r of t){let i=e.get(r.action)||0;e.set(r.action,i+1)}return Array.from(e.entries()).filter(([r,i])=>i>=t.length*.3).map(([r])=>r)}calculateAverageReward(t){return t.length===0?0:t.reduce((r,i)=>r+i.reward,0)/t.length}calculateSuccessRate(t){return t.length===0?0:t.filter(r=>r.result.success).length/t.length}inferPatternType(t){let e=t.map(r=>r.action.toLowerCase());return e.some(r=>r.includes("test")||r.includes("generate"))?"test-pattern":e.some(r=>r.includes("fix")||r.includes("repair"))?"fix-pattern":e.some(r=>r.includes("optimize")||r.includes("improve"))?"optimization-pattern":e.some(r=>r.includes("detect")||r.includes("find"))?"detection-pattern":e.some(r=>r.includes("workflow")||r.includes("process"))?"workflow-pattern":e.some(r=>r.includes("fail")||r.includes("error"))?"failure-pattern":"workflow-pattern"}generatePatternTemplate(t,e){let r=[{name:"domain",type:"string",required:!0,description:"Target domain for the pattern"},{name:"action",type:"string",required:!0,defaultValue:e[0],description:"Primary action to execute"}];return{type:"workflow",content:`// Pattern learned from ${t.length} experiences
3009
3009
  // Common actions: ${e.join(", ")}
3010
3010
  // Apply to domain: {{domain}}
3011
- // Execute action: {{action}}`,variables:r}}extractPatternContext(t){let e=new Set,r,i;for(let n of t){let s=n.state.context;if(s.language&&(r=s.language),s.framework&&(i=s.framework),s.tags&&Array.isArray(s.tags))for(let a of s.tags)e.add(a)}return{language:r,framework:i,tags:Array.from(e)}}detectAnomalies(t){let e=[],r=this.calculateAverageReward(t),i=this.calculateStdDev(t.map(n=>n.reward));for(let n of t){let s=Math.abs(n.reward-r)/(i||1);if(s>this.config.anomalyDeviationThreshold){let a="outlier-reward";n.result.success&&n.reward<r?a="unexpected-success":!n.result.success&&n.reward>r&&(a="unexpected-failure"),e.push({experienceId:n.id,type:a,description:`Reward ${n.reward.toFixed(2)} deviates ${s.toFixed(2)} std from mean ${r.toFixed(2)}`,deviation:s})}}return e}calculateStdDev(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n,0)/t.length,r=t.map(i=>Math.pow(i-e,2));return Math.sqrt(r.reduce((i,n)=>i+n,0)/t.length)}generateRecommendations(t,e,r){let i=[];return e<.5&&i.push("Low success rate detected. Consider reviewing the approach or gathering more training data."),r.length>t.length*.1&&i.push("High anomaly rate detected. Investigate unexpected outcomes for potential improvements."),t.reduce((s,a)=>s+a.result.duration,0)/t.length>6e4&&i.push("Average operation duration is high. Consider optimizing performance."),t.length<10&&i.push("Limited experience data. Collect more data points for better insights."),i.length===0&&i.push("Performance metrics are within acceptable ranges. Continue monitoring."),i}actionsSimilar(t,e){let r=s=>s.toLowerCase().replace(/[^a-z]/g,""),i=r(t),n=r(e);return!!(i===n||i.includes(n)||n.includes(i))}calculateCentroid(t){let e=Ve(),r=Ve();for(let i of t)for(let[n,s]of Object.entries(i.state.metrics))e[n]=(e[n]||0)+s,r[n]=(r[n]||0)+1;for(let i of Object.keys(e))e[i]/=r[i];return{context:{},metrics:e}}isConstraintViolated(t,e){switch(t.operator){case"lt":return e>=t.value;case"gt":return e<=t.value;case"lte":return e>t.value;case"gte":return e<t.value;case"eq":return e!==t.value;default:return!1}}};k();var hk={maxKnowledgeItems:1e3,relevanceThreshold:.5,transferDecayFactor:.1,crossDomainBoost:.2},Br=class{constructor(t,e={}){this.memory=t;this.config={...hk,...e}}memory;config;async shareKnowledge(t,e){try{await this.memory.set(`learning:knowledge:shared:${t.id}`,t,{namespace:"learning-optimization",persist:!0});for(let r of e)await this.memory.set(`learning:knowledge:access:${r.value}:${t.id}`,{knowledgeId:t.id,agentId:r.value,sharedAt:new Date,accessed:!1},{namespace:"learning-optimization",ttl:86400*7});return await this.recordSharingEvent(t,e),f(void 0)}catch(r){return g(y(r))}}async queryKnowledge(t){try{let e=[],r=await wr(this.memory,"learning:knowledge:shared:*",{retrieve:Oe,pageSize:this.config.maxKnowledgeItems});for(let i of r){let n=pe(await this.memory.get(i,{namespace:"learning-optimization"}),["createdAt","expiresAt"]);n&&this.matchesQuery(n,t)&&e.push(n)}if(e.sort((i,n)=>n.relevanceScore-i.relevanceScore||(i.id<n.id?-1:i.id>n.id?1:0)),t.embedding&&t.embedding.length>0){let i=await this.memory.vectorSearch(t.embedding,t.limit||10);for(let n of i){let s=pe(await this.memory.get(n.key,{namespace:"learning-optimization"}),["createdAt","expiresAt"]);s&&!e.some(a=>a.id===s.id)&&this.matchesQuery(s,t)&&e.push(s)}}return f(e.slice(0,t.limit||100))}catch(e){return g(y(e))}}async synthesizeKnowledge(t){try{if(t.length<2)return g(new Error("Need at least 2 knowledge items to synthesize"));let e=[];for(let l of t){let u=await this.getKnowledgeById(l);u&&e.push(u)}if(e.length<2)return g(new Error("Not enough valid knowledge items found"));let r=this.determineSynthesizedType(e),i=this.determineSynthesizedDomain(e),n=this.mergeKnowledgeContent(e),s=e.reduce((l,u)=>l+u.relevanceScore,0)/e.length,a=Math.min(1,s+this.config.crossDomainBoost),o={id:w(),type:r,domain:i,content:n,sourceAgentId:e[0].sourceAgentId,targetDomains:this.mergeTargetDomains(e),relevanceScore:a,version:1,createdAt:new Date};return await this.storeKnowledge(o),await this.recordSynthesisEvent(o,t),f(o)}catch(e){return g(y(e))}}async transferKnowledge(t,e){try{if(t.domain===e)return g(new Error("Cannot transfer knowledge to the same domain"));let r=this.calculateTransferredRelevance(t,e);if(r<this.config.relevanceThreshold)return g(new Error(`Transferred relevance ${r} below threshold ${this.config.relevanceThreshold}`));let i=await this.adaptContentForDomain(t.content,t.domain,e),n={id:w(),type:t.type,domain:e,content:i,sourceAgentId:t.sourceAgentId,targetDomains:[e],relevanceScore:r,version:t.version+1,createdAt:new Date};return await this.storeKnowledge(n),await this.recordTransferEvent(t,n),f(n)}catch(r){return g(y(r))}}async validateRelevance(t,e){try{let r=t.relevanceScore;if(e.language&&t.content.metadata?.language===e.language&&(r+=.1),e.framework&&t.content.metadata?.framework===e.framework&&(r+=.1),e.tags.length>0&&t.content.metadata?.tags){let a=t.content.metadata.tags,o=e.tags.filter(l=>a.includes(l));r+=o.length/e.tags.length*.2}let n=(Date.now()-t.createdAt.getTime())/(1e3*60*60*24),s=Math.exp(-this.config.transferDecayFactor*n/30);return r*=s,t.expiresAt&&new Date>t.expiresAt&&(r*=.5),f(Math.min(1,Math.max(0,r)))}catch(r){return g(y(r))}}async createKnowledge(t,e,r,i,n=[],s){try{let a={id:w(),type:t,domain:e,content:{format:this.inferContentFormat(r),data:r,metadata:s},sourceAgentId:i,targetDomains:n,relevanceScore:1,version:1,createdAt:new Date};return await this.storeKnowledge(a),t==="embedding"&&Array.isArray(r)&&await this.memory.storeVector(`learning:knowledge:vector:${a.id}`,r,{knowledgeId:a.id}),f(a)}catch(a){return g(y(a))}}async getKnowledgeById(t){return pe(await this.memory.get(`learning:knowledge:shared:${t}`,{namespace:"learning-optimization"}),["createdAt","expiresAt"])||null}async bulkTransfer(t,e,r){try{let i=`learning:knowledge:project:${t}:`,n=(await wr(this.memory,`${i}*`,{retrieve:Oe})).filter(a=>a.startsWith(i)&&!a.slice(i.length).includes(":")),s=[];for(let a of n){let o=pe(await this.memory.get(a,Oe),["createdAt","expiresAt"]);if(!o||r?.types&&!r.types.includes(o.type)||r?.minRelevance&&o.relevanceScore<r.minRelevance)continue;let l=await this.adaptContentForProject(o.content,t,e),u={...o,id:w(),content:l,relevanceScore:o.relevanceScore*(1-this.config.transferDecayFactor),version:o.version+1,createdAt:new Date};await this.memory.set(`learning:knowledge:project:${e}:${u.id}`,u,{namespace:"learning-optimization",persist:!0}),s.push({knowledgeId:u.id,sourceDomain:o.domain,targetDomain:o.domain,originalRelevance:o.relevanceScore,transferredRelevance:u.relevanceScore,adaptations:["project-context-adapted"]})}return f(s)}catch(i){return g(y(i))}}async storeKnowledge(t){await this.memory.set(`learning:knowledge:shared:${t.id}`,t,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:knowledge:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:knowledge:type:${t.type}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}matchesQuery(t,e){if(e.type&&t.type!==e.type||e.domain&&t.domain!==e.domain||e.minRelevance!==void 0&&t.relevanceScore<e.minRelevance)return!1;if(e.tags&&e.tags.length>0){let r=t.content.metadata?.tags||[];if(!e.tags.some(n=>r.includes(n)))return!1}return!0}determineSynthesizedType(t){let e=new Map;for(let n of t)e.set(n.type,(e.get(n.type)||0)+1);let r=t[0].type,i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}determineSynthesizedDomain(t){let e=new Map;for(let n of t)e.set(n.domain,(e.get(n.domain)||0)+1);let r=t[0].domain,i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}mergeKnowledgeContent(t){let e={},r=[];for(let i of t)if(r.push(i.content.data),i.content.metadata)for(let[n,s]of Object.entries(i.content.metadata))if(Array.isArray(s)){let a=e[n]||[];e[n]=[...new Set([...a,...s])]}else e[n]=s;return{format:"json",data:{synthesized:!0,sources:r},metadata:{...e,synthesizedFrom:t.map(i=>i.id),synthesizedAt:new Date().toISOString()}}}mergeTargetDomains(t){let e=new Set;for(let r of t){e.add(r.domain);for(let i of r.targetDomains)e.add(i)}return Array.from(e)}calculateTransferredRelevance(t,e){let r=t.relevanceScore;r*=1-this.config.transferDecayFactor;let i=this.getDomainCompatibility(t.domain,e);return r*=i,t.targetDomains.includes(e)&&(r+=this.config.crossDomainBoost),Math.min(1,Math.max(0,r))}getDomainCompatibility(t,e){let r={"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"],"enterprise-integration":["contract-testing","security-compliance","quality-assessment"],coordination:Ne.filter(i=>i!=="coordination")};return t===e?1:r[t]?.includes(e)?.8:.5}async adaptContentForDomain(t,e,r){return{...t,metadata:{...t.metadata||{},adaptedFrom:e,adaptedTo:r,adaptedAt:new Date().toISOString()}}}async adaptContentForProject(t,e,r){return{...t,metadata:{...t.metadata||{},sourceProject:e,targetProject:r,transferredAt:new Date().toISOString()}}}inferContentFormat(t){return typeof t=="string"?"text":Array.isArray(t)&&t.every(e=>typeof e=="number")?"embedding":"json"}async recordSharingEvent(t,e){await this.memory.set(`learning:knowledge:events:share:${t.id}:${Date.now()}`,{type:"share",knowledgeId:t.id,targetAgents:e.map(r=>r.value),timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}async recordSynthesisEvent(t,e){await this.memory.set(`learning:knowledge:events:synthesis:${t.id}`,{type:"synthesis",synthesizedId:t.id,sourceIds:e,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}async recordTransferEvent(t,e){await this.memory.set(`learning:knowledge:events:transfer:${e.id}`,{type:"transfer",originalId:t.id,transferredId:e.id,originalDomain:t.domain,targetDomain:e.domain,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}};k();var fk={defaultConfidenceLevel:.95,minSamplesForOptimization:20,maxOptimizationIterations:100,improvementThreshold:.05,explorationRate:.1},fs={namespace:"learning-optimization"},yk=.2,vk=.2,bk=["__proto__","constructor","prototype"];function ys(c){return!bk.includes(c)}var qr=class{constructor(t,e={}){this.memory=t;this.config={...fk,...e}}memory;config;async optimizeStrategy(t,e,r){try{let{measured:i,assignedExcluded:n}=It(r);if(i.length<this.config.minSamplesForOptimization){let R=n>0?` (${n} with an assigned reward excluded)`:"";return g(new Error(`Need at least ${this.config.minSamplesForOptimization} measured experiences for optimization${R}`))}let s=[...i].sort((R,E)=>eb(R)-eb(E)),a=Math.max(1,Math.floor(s.length*yk)),o=s.slice(0,-a),l=s.slice(-a),u=await this.optimizeParameters(t.parameters,o,e),d={name:`${t.name}-optimized`,parameters:u,expectedOutcome:this.predictOutcome(u,o)},m=await this.validateOptimization(t,d,l),p=this.calculateImprovement(this.scoreParameters(t.parameters,l,e),this.scoreParameters(u,l,e),e),h=m.length>0?m.filter(R=>R.passed).length/m.length:0,v=[];p===void 0&&v.push("improvement"),m.length===0&&v.push("confidence");let b={method:"held-out",trainingSamples:o.length,heldOutSamples:l.length,estimated:p===void 0?[]:["improvement"],...v.length>0?{unmeasured:v}:{}},C=this.inferDomainFromExperiences(i),S={id:w(),domain:C,objective:e,currentStrategy:t,optimizedStrategy:d,improvement:p??0,confidence:h,validationResults:m,evaluation:b};return await this.storeOptimizationResult(S),f(S)}catch(i){return g(y(i))}}async runABTest(t,e,r){try{let i=await this.collectStrategyMetrics(t,r.metric),n=await this.collectStrategyMetrics(e,r.metric),s=Math.max(1,r.minSamples);if(i.length<s||n.length<s){let h={winner:"inconclusive",evidenceStatus:"insufficient-evidence",unmeasured:[r.metric,"stdDev","pValue"],strategyAMetrics:{samples:i.length},strategyBMetrics:{samples:n.length},sampleSizeA:i.length,sampleSizeB:n.length};return await this.storeABTestResult(t,e,h),f(h)}let a=this.calculateMean(i),o=this.calculateMean(n),l=this.calculateStdDev(i),u=this.calculateStdDev(n),d=this.calculatePValue(i,n),m;d!==void 0&&d<1-r.confidenceLevel?m=a>o?"A":"B":m="inconclusive";let p={winner:m,strategyAMetrics:{[r.metric]:a,stdDev:l,samples:i.length},strategyBMetrics:{[r.metric]:o,stdDev:u,samples:n.length},...d===void 0?{unmeasured:["pValue"],pValueUnavailableReason:"zero-variance"}:{pValue:d},sampleSizeA:i.length,sampleSizeB:n.length};return await this.storeABTestResult(t,e,p),f(p)}catch(i){return g(y(i))}}async recommendStrategy(t){try{let e=await this.memory.search("learning:strategy:optimized:*",100,{namespace:"learning-optimization"}),r=[];for(let i of e){let n="learning-optimization:",s=i.startsWith(n)?i.slice(n.length):i,a=await this.memory.get(s,{namespace:"learning-optimization"});if(a&&t.tags.includes(a.domain)&&t.tags.includes(a.objective.metric)&&(!t.objective||t.tags.includes(t.objective.metric)&&a.objective.metric===t.objective.metric&&a.objective.direction===t.objective.direction)&&a.confidence>.6){let o=this.scoreContextMatch(a,t),l=a.improvement*a.confidence;r.push({strategy:a.optimizedStrategy,score:o*.4+l*.6})}}return r.length===0?f({name:"default-strategy",parameters:this.getDefaultParameters(t),expectedOutcome:{}}):(r.sort((i,n)=>n.score-i.score),f(r[0].strategy))}catch(e){return g(y(e))}}async evaluateStrategy(t,e){try{let{measured:r,assignedExcluded:i}=It(e);if(r.length===0)return f({strategy:t,metrics:{},strengths:[],weaknesses:[],improvementAreas:[],evidenceStatus:"insufficient-evidence",...i>0?{assignedRewardsExcluded:i}:{}});let n={},s=this.calculateSuccessRate(r),a=this.calculateAverageDuration(r),o=this.calculateAverageReward(r);n.success_rate=s,n.avg_duration_ms=a,n.avg_reward=o;let l=[];s>.8&&l.push("High success rate"),a<5e3&&l.push("Fast execution"),o>.7&&l.push("Consistently good rewards");let u=[];s<.5&&u.push("Low success rate needs investigation"),a>3e4&&u.push("Slow execution time"),o<.3&&u.push("Low reward values");let d=this.identifyImprovementAreas(t,n,r),m={strategy:t,metrics:n,strengths:l,weaknesses:u,improvementAreas:d};return await this.storeStrategyEvaluation(m),f(m)}catch(r){return g(y(r))}}async trackMetrics(t,e){try{let r={strategyId:t,metrics:e,timestamp:new Date,samples:1},i=`learning:metrics:history:${t}:${Date.now()}`;return await this.memory.set(i,r,{namespace:"learning-optimization",ttl:86400*30}),await this.updateAggregatedMetrics(t,e),f(void 0)}catch(r){return g(y(r))}}async getMetricsHistory(t,e=100){try{let r=await this.searchLearningKeys(`learning:metrics:history:${t}:*`,e),i=[];for(let n of r){let s=pe(await this.memory.get(n,fs),["timestamp"]);s&&i.push(s)}return i.sort((n,s)=>n.timestamp.getTime()-s.timestamp.getTime()),f(i)}catch(r){return g(y(r))}}async gridSearchOptimize(t,e,r){try{let i=this.generateParameterCombinations(t),n={},s=e.direction==="maximize"?-1/0:1/0;for(let a of i){let o=this.scoreParameters(a,r,e);(e.direction==="maximize"?o>s:o<s)&&(s=o,n=a)}return f(n)}catch(i){return g(y(i))}}async searchLearningKeys(t,e){let r=`${fs.namespace}:`;return(await this.memory.search(t,e,fs)).map(n=>n.startsWith(r)?n.slice(r.length):n)}async optimizeParameters(t,e,r){let i={...t};for(let[n,s]of Object.entries(t))if(ys(n)&&typeof s=="number"){let a=[-.1,-.05,0,.05,.1],o=0,l=this.scoreParameters(i,e,r);for(let u of a){let d={...i,[n]:s*(1+u)},m=this.scoreParameters(d,e,r);(r.direction==="maximize"?m>l:m<l)&&(l=m,o=u)}i[n]=s*(1+o)}return i}scoreParameters(t,e,r){let i=0,n=0;for(let s of e){let a=s.result.success?1:.5,o=this.calculateParamSimilarity(t,s.state.context),l=s.result.outcome[r.metric]??0;i+=o*l*a,n+=a}return n>0?i/n:0}calculateParamSimilarity(t,e){let r=0,i=0;for(let[n,s]of Object.entries(t))if(e[n]!==void 0)if(i++,typeof s=="number"&&typeof e[n]=="number"){let a=Math.abs(s-e[n]),o=Math.max(Math.abs(s),Math.abs(e[n]),1);r+=1-a/o}else s===e[n]&&r++;return i>0?r/i:.5}predictOutcome(t,e){let r={},i={},n={};for(let s of e)if(s.result.success)for(let[a,o]of Object.entries(s.result.outcome))ys(a)&&typeof o=="number"&&(i[a]=(i[a]||0)+o,n[a]=(n[a]||0)+1);for(let[s,a]of Object.entries(i))ys(s)&&(r[s]=a/n[s]);return r}async validateOptimization(t,e,r){let i=[],n=Object.entries(e.expectedOutcome);if(n.length===0)return i;for(let s of r){let a=n.filter(([l])=>typeof s.result.outcome[l]=="number");if(a.length===0)continue;let o=a.every(([l,u])=>{let d=s.result.outcome[l];return Math.abs(d-u)/Math.max(u,1)<vk});i.push({testId:s.id,passed:o,metrics:s.state.metrics})}return i}calculateImprovement(t,e,r){if(t===0)return;let i=e-t,n=r.direction==="maximize"?i/t:-i/t;return Math.max(-1,Math.min(1,n))}inferDomainFromExperiences(t){let e=new Map;for(let n of t)e.set(n.domain,(e.get(n.domain)||0)+1);let r="learning-optimization",i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}async collectStrategyMetrics(t,e){let r=await this.searchLearningKeys(`learning:metrics:history:${t.name}:*`,1e3),i=[];for(let n of r){let a=(await this.memory.get(n,fs))?.metrics[e];typeof a=="number"&&Number.isFinite(a)&&i.push(a)}return i}calculateMean(t){return t.length===0?0:t.reduce((e,r)=>e+r,0)/t.length}calculateStdDev(t){if(t.length===0)return 0;let e=this.calculateMean(t),r=t.map(i=>Math.pow(i-e,2));return Math.sqrt(r.reduce((i,n)=>i+n,0)/t.length)}calculatePValue(t,e){let r=this.calculateMean(t),i=this.calculateMean(e),n=Math.pow(this.calculateStdDev(t),2),s=Math.pow(this.calculateStdDev(e),2),a=t.length,o=e.length,l=Math.sqrt(n/a+s/o);if(l===0)return;let u=Math.abs(r-i)/l,d=2*(1-this.normalCDF(u));return Math.max(0,Math.min(1,d))}normalCDF(t){let e=.254829592,r=-.284496736,i=1.421413741,n=-1.453152027,s=1.061405429,a=.3275911,o=t<0?-1:1;t=Math.abs(t)/Math.sqrt(2);let l=1/(1+a*t),u=1-((((s*l+n)*l+i)*l+r)*l+e)*l*Math.exp(-t*t);return .5*(1+o*u)}scoreContextMatch(t,e){let r=0,i=0;return e.tags.some(n=>n===t.objective.metric)&&(r+=1),i+=1,e.tags.some(n=>n===t.domain)&&(r+=1),i+=1,i>0?r/i:.5}getDefaultParameters(t){let e={timeout:3e4,retryCount:3,concurrency:4};return t.framework&&(e.framework=t.framework),t.language&&(e.language=t.language),e}calculateSuccessRate(t){return t.length===0?0:t.filter(e=>e.result.success).length/t.length}calculateAverageDuration(t){return t.length===0?0:t.reduce((e,r)=>e+r.result.duration,0)/t.length}calculateAverageReward(t){return t.length===0?0:t.reduce((e,r)=>e+r.reward,0)/t.length}identifyImprovementAreas(t,e,r){let i=[];e.success_rate<.8&&i.push("Increase success rate by tuning parameters"),e.avg_duration_ms>1e4&&i.push("Optimize for faster execution"),e.avg_reward<.5&&i.push("Improve reward through better strategy selection");let n=t.parameters;return n.retryCount<2&&i.push("Consider increasing retry count for resilience"),n.concurrency>8&&i.push("High concurrency may cause resource contention"),i}generateParameterCombinations(t){let e=Object.keys(t);if(e.length===0)return[{}];let r=[];function i(n,s){if(n===e.length){r.push({...s});return}let a=e[n];if(!ys(a)){i(n+1,s);return}for(let o of t[a])s[a]=o,i(n+1,s)}return i(0,{}),r}async updateAggregatedMetrics(t,e){let r=`learning:metrics:aggregated:${t}`,n=(await this.memory.get(r,fs))?.metrics||{};for(let[s,a]of Object.entries(e))ys(s)&&(n[s]||(n[s]={sum:0,count:0}),n[s].sum+=a,n[s].count+=1);await this.memory.set(r,{metrics:n,updatedAt:new Date},{namespace:"learning-optimization",persist:!0})}async storeOptimizationResult(t){await this.memory.set(`learning:strategy:optimized:${t.id}`,t,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:strategy:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}async storeABTestResult(t,e,r){let i=w();await this.memory.set(`learning:abtest:${i}`,{testId:i,strategyA:t.name,strategyB:e.name,result:r,timestamp:new Date},{namespace:"learning-optimization",persist:!0})}async storeStrategyEvaluation(t){let e=w();await this.memory.set(`learning:evaluation:${e}`,{...t,evaluatedAt:new Date},{namespace:"learning-optimization",ttl:86400*7})}};function eb(c){let t=new Date(c.timestamp).getTime();return Number.isNaN(t)?0:t}k();hr();var wk={metricsRetentionDays:90,anomalyThreshold:2.5,trendWindowSize:7,alertThresholds:{error_rate:.05,latency_p99:5e3,memory_usage:.9,cpu_usage:.8}},Gr=class{constructor(t,e={}){this.memory=t;this.config={...wk,...e}}memory;config;async recordMetric(t,e,r,i,n=[]){try{let s={id:w(),name:t,value:e,unit:r,domain:i,tags:n,timestamp:new Date};return await this.memory.set(`production:metric:${s.id}`,s,{namespace:"learning-optimization",ttl:this.config.metricsRetentionDays*86400}),await this.indexMetric(s),await this.checkForAnomalies(s),f(s.id)}catch(s){return g(y(s))}}async recordMetricsBatch(t){try{let e=[];for(let r of t){let i=await this.recordMetric(r.name,r.value,r.unit,r.domain,r.tags);i.success&&e.push(i.value)}return f(e)}catch(e){return g(y(e))}}async getMetricsHistory(t,e,r){try{let i=r?`production:metric:index:${t}:${r}:*`:`production:metric:index:${t}:*`,n=await this.memory.search(i,1e3),s=[];for(let a of n){let o=await this.memory.get(a);if(o){let l=pe(await this.memory.get(`production:metric:${o}`),["timestamp"]);l&&e.contains(l.timestamp)&&s.push(l)}}return s.sort((a,o)=>a.timestamp.getTime()-o.timestamp.getTime()),f(s)}catch(i){return g(y(i))}}async recordIncident(t,e,r,i,n){try{let s={id:w(),severity:t,title:e,description:r,domain:i,metrics:n,startedAt:new Date};return await this.memory.set(`production:incident:${s.id}`,s,{namespace:"learning-optimization",persist:!0}),await this.indexIncident(s),await this.createExperienceFromIncident(s),f(s)}catch(s){return g(y(s))}}async resolveIncident(t,e,r){try{let i=pe(await this.memory.get(`production:incident:${t}`),["startedAt","resolvedAt"]);if(!i)return g(new Error(`Incident ${t} not found`));let n={...i,rootCause:e,resolution:r,resolvedAt:new Date};return await this.memory.set(`production:incident:${t}`,n,{namespace:"learning-optimization",persist:!0}),await this.updateExperienceWithResolution(n),f(n)}catch(i){return g(y(i))}}async getRecentIncidents(t=10,e){try{let r=e?`production:incident:index:domain:${e}:*`:"production:incident:*",i=await this.memory.search(r,t*2),n=[];for(let a of i)if(a.includes(":index:")){let o=await this.memory.get(a);if(o){let l=pe(await this.memory.get(`production:incident:${o}`),["startedAt","resolvedAt"]);l&&n.push(l)}}else{let o=pe(await this.memory.get(a),["startedAt","resolvedAt"]);o&&n.push(o)}n.sort((a,o)=>o.startedAt.getTime()-a.startedAt.getTime());let s=Array.from(new Map(n.map(a=>[a.id,a])).values());return f(s.slice(0,t))}catch(r){return g(y(r))}}async getProductionHealth(){try{let t=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","code-intelligence","security-compliance","learning-optimization"],e={},r={},i="healthy",n=0,s=0;for(let d of t){let m=await this.getDomainHealth(d);e[d]=m,m.status==="degraded"&&n++,m.status==="unhealthy"&&s++;for(let[p,h]of Object.entries(m.metrics))r[`${d}_${p}`]=h}s>0?i="unhealthy":n>t.length/3&&(i="degraded");let a=await this.calculateTrends(),o=await this.getRecentIncidents(5),l=o.success?o.value:[],u=this.generateHealthRecommendations(e,r,l);return f({overall:i,domains:e,metrics:r,trends:a,recentIncidents:l,recommendations:u})}catch(t){return g(y(t))}}async getDomainHealth(t){let e=Vt.lastNDays(1),r=await this.getMetricsHistory("*",e,t),i=Ve();if(r.success)for(let o of r.value)i[o.name],i[o.name]=o.value;let n=await this.getRecentIncidents(100,t),s=n.success?n.value.filter(o=>!o.resolvedAt).length:0,a="healthy";return s>2?a="unhealthy":s>0&&(a="degraded"),i.error_rate>this.config.alertThresholds.error_rate?a="unhealthy":i.latency_p99>this.config.alertThresholds.latency_p99&&(a="degraded"),{status:a,metrics:i,activeIncidents:s}}async calculateTrends(){let t=[],e=["error_rate","latency_p99","success_rate"],r=this.config.trendWindowSize;for(let i of e)for(let n=0;n<r;n++){let s=new Date;s.setDate(s.getDate()-n),s.setHours(0,0,0,0);let a=new Date(s);a.setHours(23,59,59,999);let o=Vt.create(s,a),l=await this.getMetricsHistory(i,o);if(l.success&&l.value.length>0){let u=l.value.reduce((d,m)=>d+m.value,0)/l.value.length;t.push({timestamp:s,metric:i,value:u})}}return t}generateHealthRecommendations(t,e,r){let i=[];for(let[a,o]of Object.entries(t))o.status==="unhealthy"?i.push(`Domain ${a} is unhealthy. Review active incidents and metrics.`):o.status==="degraded"&&i.push(`Domain ${a} is degraded. Monitor closely.`);for(let[a,o]of Object.entries(e)){let l=a.split("_").slice(-2).join("_"),u=this.config.alertThresholds[l];u&&o>u&&i.push(`Metric ${a} (${o.toFixed(2)}) exceeds threshold (${u})`)}let n=r.filter(a=>!a.resolvedAt);return n.length>3&&i.push(`${n.length} unresolved incidents require attention`),r.reduce((a,o)=>(a[o.severity]=(a[o.severity]||0)+1,a),{}).critical>2&&i.push("Multiple critical incidents detected. Consider system-wide review."),i.length===0&&i.push("All systems operating within normal parameters."),i}async extractInsights(t,e){try{let r=await this.getMetricsHistory("*",t,e),i=r.success?r.value:[],n=await this.getRecentIncidents(50,e),s=n.success?n.value:[],a=i.length,o=s.filter(p=>p.resolvedAt),l=s.length>0?o.length/s.length:1,u=this.calculateRewardFromIncidents(s),d=this.generateInsightRecommendations(i,s),m=this.detectMetricAnomalies(i);return f({experienceCount:a,successRate:l,avgReward:u,patterns:[],anomalies:m,recommendations:d})}catch(r){return g(y(r))}}async recordMilestone(t,e,r){try{let i={name:t,achievedAt:new Date,domain:e};return await this.memory.set(`production:milestone:${w()}`,{...i,metrics:r},{namespace:"learning-optimization",persist:!0}),f(i)}catch(i){return g(y(i))}}async getRecentMilestones(t=10){try{let e=await this.memory.search("production:milestone:*",t),r=[];for(let i of e){let n=pe(await this.memory.get(i),["achievedAt"]);n&&r.push(n)}return r.sort((i,n)=>n.achievedAt.getTime()-i.achievedAt.getTime()),f(r.slice(0,t))}catch(e){return g(y(e))}}async indexMetric(t){await this.memory.set(`production:metric:index:${t.name}:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",ttl:this.config.metricsRetentionDays*86400})}async indexIncident(t){await this.memory.set(`production:incident:index:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`production:incident:index:severity:${t.severity}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}async checkForAnomalies(t){let e=Vt.lastNDays(7),r=await this.getMetricsHistory(t.name,e,t.domain);if(!r.success||r.value.length<10)return;let i=r.value.map(o=>o.value),n=i.reduce((o,l)=>o+l,0)/i.length,s=Math.sqrt(i.reduce((o,l)=>o+Math.pow(l-n,2),0)/i.length),a=Math.abs(t.value-n)/(s||1);a>this.config.anomalyThreshold&&await this.memory.set(`production:anomaly:${w()}`,{metricId:t.id,metricName:t.name,value:t.value,mean:n,stdDev:s,deviation:a,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*7})}async createExperienceFromIncident(t){let e={context:{incidentId:t.id,severity:t.severity,domain:t.domain},metrics:t.metrics},r={success:!1,outcome:t.metrics,duration:0},i={id:w(),agentId:{value:"production-intel",domain:"learning-optimization",type:"analyzer"},domain:t.domain,action:`incident-${t.severity}`,state:e,result:r,reward:this.calculateIncidentReward(t),timestamp:t.startedAt};await this.memory.set(`learning:experience:${i.id}`,i,{namespace:"learning-optimization",ttl:86400*30})}async updateExperienceWithResolution(t){if(!t.resolvedAt)return;let e={context:{incidentId:t.id,rootCause:t.rootCause,resolution:t.resolution},metrics:t.metrics},r=t.resolvedAt.getTime()-t.startedAt.getTime(),i={success:!0,outcome:{...t.metrics,resolution_time_ms:r},duration:r},n={id:w(),agentId:{value:"production-intel",domain:"learning-optimization",type:"analyzer"},domain:t.domain,action:`resolution-${t.severity}`,state:e,result:i,reward:1-this.calculateIncidentReward(t),timestamp:t.resolvedAt};await this.memory.set(`learning:experience:${n.id}`,n,{namespace:"learning-optimization",ttl:86400*30})}calculateIncidentReward(t){return-({critical:.9,high:.7,medium:.4,low:.2}[t.severity]||.5)}calculateRewardFromIncidents(t){if(t.length===0)return .8;let e={critical:.1,high:.3,medium:.6,low:.8},r=0,i=0;for(let n of t){let s=e[n.severity]||.5,a=n.resolvedAt?.2:0;r+=s+a,i++}return i>0?r/i:.8}generateInsightRecommendations(t,e){let r=[],i=new Map;for(let n of t){let s=i.get(n.name)||[];s.push(n.value),i.set(n.name,s)}for(let[n,s]of i){let a=this.calculateTrendDirection(s);a==="increasing"&&n.includes("error")?r.push(`${n} is trending upward. Investigate root causes.`):a==="decreasing"&&n.includes("success")&&r.push(`${n} is declining. Review recent changes.`)}if(e.length>0){let n=new Map;for(let s of e)n.set(s.domain,(n.get(s.domain)||0)+1);for(let[s,a]of n)a>3&&r.push(`Domain ${s} has ${a} incidents. Consider preventive measures.`)}return r}detectMetricAnomalies(t){let e=[],r=new Map;for(let i of t){let n=r.get(i.name)||[];n.push(i),r.set(i.name,n)}for(let[i,n]of r){if(n.length<5)continue;let s=n.map(l=>l.value),a=s.reduce((l,u)=>l+u,0)/s.length,o=Math.sqrt(s.reduce((l,u)=>l+Math.pow(u-a,2),0)/s.length);for(let l of n){let u=Math.abs(l.value-a)/(o||1);u>this.config.anomalyThreshold&&e.push({experienceId:l.id,type:"outlier-reward",description:`${i} value ${l.value.toFixed(2)} is ${u.toFixed(1)} std deviations from mean`,deviation:u})}}return e}calculateTrendDirection(t){if(t.length<3)return"stable";let e=t.slice(0,Math.floor(t.length/2)),r=t.slice(Math.floor(t.length/2)),i=e.reduce((a,o)=>a+o,0)/e.length,s=(r.reduce((a,o)=>a+o,0)/r.length-i)/(i||1);return s>.1?"increasing":s<-.1?"decreasing":"stable"}};async function tb(c,t,e){await c.set(`learning:strategy:current:${t}`,e,{namespace:"learning-optimization",persist:!0})}function rb(c,t){let e=c.map(r=>r.result.outcome[t]??0).filter(r=>!isNaN(r));return e.length===0?0:e.reduce((r,i)=>r+i,0)/e.length}function ib(c){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":Ne.filter(e=>e!=="learning-optimization"),"enterprise-integration":["contract-testing","security-compliance","quality-assessment"],coordination:Ne.filter(e=>e!=="coordination")}[c]||[]}function nb(c){let t=[],e=new Set;for(let r of c){if(e.has(r.id))continue;let i=[r];e.add(r.id);for(let n of c)e.has(n.id)||r.type===n.type&&r.domain===n.domain&&Ck(r.context,n.context)&&(i.push(n),e.add(n.id));i.length>=2&&t.push(i)}return t}function Ck(c,t){return c.tags.some(e=>t.tags.includes(e))}function sb(c,t,e){let r=JSON.stringify({patternCount:c.length,knowledgeCount:t.length,strategyCount:e.length,patternIds:c.map(n=>n.id).sort(),knowledgeIds:t.map(n=>n.id).sort(),strategyIds:e.map(n=>n.id).sort()}),i=0;for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);i=(i<<5)-i+s,i=i&i}return Math.abs(i).toString(16)}_();var qi=x.create("learning-optimization/consensus");async function ab(c,t,e,r){let i=U({id:w(),type:"pattern-recommendation",confidence:t,description:`Verify pattern recommendation: ${c.name} (${c.type}) for domain ${c.domain}`,payload:c,detectedBy:"learning-optimization-coordinator",severity:t>.9?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(qi.info(`Pattern recommendation '${c.name}' verified by consensus`),!0):(qi.warn(`Pattern recommendation '${c.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function ob(c,t,e,r){let i=U({id:w(),type:"optimization-suggestion",confidence:t,description:`Verify optimization: ${c.metric} from ${c.currentValue} to ${c.targetValue} via ${c.strategy}`,payload:c,detectedBy:"learning-optimization-coordinator",severity:t>.85?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(qi.info(`Optimization suggestion for '${c.metric}' verified by consensus`),!0):(qi.warn(`Optimization suggestion for '${c.metric}' NOT verified`),!1)}return!0}async function cb(c,t,e,r){let i=U({id:w(),type:"cross-domain-insight",confidence:t,description:`Verify cross-domain insight: ${c.description}`,payload:c,detectedBy:"learning-optimization-coordinator",severity:"high"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(qi.info(`Cross-domain insight verified by consensus for ${c.targetDomains.length} target domains`),!0):(qi.warn(`Cross-domain insight NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}var Tk={maxConcurrentWorkflows:3,defaultTimeout:12e4,enableAutoOptimization:!0,publishEvents:!0,learningCycleIntervalMs:36e5,enableDreamScheduler:!0,dreamCycleIntervalMs:36e5,enableExperienceTrigger:!0,experienceThreshold:50,enableQualityGateFailureTrigger:!0,autoApplyHighConfidenceInsights:!1,autoApplyConfidenceThreshold:.8,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Be=x.create("learning-optimization"),xc=class extends ie{constructor(e,r,i,n={},s){let a={...Tk,...n};super(e,"learning-optimization",a,{verifyFindingTypes:["pattern-recommendation","optimization-suggestion","cross-domain-insight"]});this.memory=r;this.agentCoordinator=i;this.learningService=new zr({memory:r,llmRouter:s}),this.transferService=new Br(r),this.optimizerService=new qr(r),this.productionIntel=new Gr(r)}memory;agentCoordinator;learningService;transferService;optimizerService;productionIntel;sona=null;dreamScheduler=null;async onInitialize(){try{this.sona=await De({domain:"learning-optimization",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.5}),Be.info("PersistentSONAEngine initialized for pattern learning")}catch(e){Be.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),Be.warn("Continuing without SONA pattern persistence"),this.sona=null}if(this.config.enableDreamScheduler)try{let e=await Rs();await e.initialize(),this.dreamScheduler=Dm({dreamEngine:e,eventBus:this.eventBus,memoryBackend:this.memory},{autoScheduleIntervalMs:this.config.dreamCycleIntervalMs,enableExperienceTrigger:this.config.enableExperienceTrigger,experienceThreshold:this.config.experienceThreshold,enableQualityGateFailureTrigger:this.config.enableQualityGateFailureTrigger,autoApplyHighConfidenceInsights:this.config.autoApplyHighConfidenceInsights,insightConfidenceThreshold:this.config.autoApplyConfidenceThreshold}),await this.dreamScheduler.initialize(),this.dreamScheduler.start(),Be.info("DreamScheduler initialized and started")}catch{Be.warn("Failed to initialize DreamScheduler:")}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){if(await this.saveWorkflowState(),this.dreamScheduler){try{await this.dreamScheduler.dispose(),Be.info("DreamScheduler disposed")}catch(e){Be.error("Error disposing DreamScheduler:",e instanceof Error?e:void 0)}this.dreamScheduler=null}if(this.initialized&&this.sona)try{await this.sona.close()}catch(e){Be.error("Error closing SONA engine:",e instanceof Error?e:void 0)}}getActiveWorkflows(){return super.getActiveWorkflows()}async runLearningCycle(e){let r=w();try{if(this.startWorkflow(r,"learning-cycle"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Be.warn("Topology degraded, using conservative strategy for learning cycle"),this.minCutMixin.shouldPauseOperations())return g(new Error("Learning cycle paused: topology is in critical state"));let i=await this.spawnLearningAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),g(i.error);this.addAgentToWorkflow(r,i.value);let n=Vt.lastNDays(1),s=await this.getExperiencesForDomain(e,n),a=s.success?It(s.value).measured:[];this.updateWorkflowProgress(r,20);let o=await this.learningService.mineExperiences(e,n),l=o.success?o.value.patterns.length:0;this.updateWorkflowProgress(r,50);let u=0,d=[];if(a.length>=10){let h={metric:"success_rate",direction:"maximize",constraints:[]},v=await this.getCurrentStrategy(e),b=await this.optimizerService.optimizeStrategy(v,h,a);if(b.success){u=1;let C=b.value.optimizedStrategy.expectedOutcome[h.metric];typeof C=="number"&&d.push({metric:h.metric,before:this.calculateMetricValue(a,h.metric),after:C,percentChange:b.value.improvement*100,estimated:!0})}}this.updateWorkflowProgress(r,80);let m=0;o.success&&o.value.recommendations.length>0&&(await this.transferService.createKnowledge("heuristic",e,o.value.recommendations,{value:`learning-agent-${r.slice(0,8)}`,domain:"learning-optimization",type:"analyzer"},[e])).success&&(m=1),this.completeWorkflow(r),await this.agentCoordinator.stop(i.value);let p={domain:e,experiencesProcessed:a.length,patternsLearned:l,strategiesOptimized:u,knowledgeGenerated:m,improvements:d};return this.config.publishEvents&&l>0&&await this.publishPatternConsolidated(l,[e]),f(p)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async optimizeAllStrategies(){let e=w();try{if(this.startWorkflow(e,"optimization"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Be.warn("Topology degraded, using conservative optimization strategy"),this.minCutMixin.shouldPauseOperations())return g(new Error("Optimization paused: topology is in critical state"));let r={},i=0,n=0,s=0,a=Ne.filter(l=>l!=="learning-optimization");for(let l=0;l<a.length;l++){let u=a[l];this.updateWorkflowProgress(e,Math.round(l/a.length*100));let d=Vt.lastNDays(7),m=await this.getExperiencesForDomain(u,d);if(!m.success||m.value.length<10)continue;let p=m.value,h={metric:"success_rate",direction:"maximize",constraints:[]},v=await this.getCurrentStrategy(u),b=await this.optimizerService.optimizeStrategy(v,h,p);b.success&&(i++,n+=b.value.improvement,s++,r[u]={strategiesOptimized:1,avgImprovement:b.value.improvement,bestStrategy:b.value.optimizedStrategy},await this.storeStrategy(u,b.value.optimizedStrategy))}this.completeWorkflow(e);let o={domainsOptimized:s,totalStrategies:i,avgImprovement:i>0?n/i:0,improvementEstimated:!0,byDomain:r};return this.config.publishEvents&&i>0&&await this.publishOptimizationApplied(o),f(o)}catch(r){return this.failWorkflow(e,String(r)),g(y(r))}}async shareCrossDomainLearnings(){let e=w();try{if(this.startWorkflow(e,"transfer"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Be.warn("Topology degraded, limiting cross-domain transfer scope"),this.minCutMixin.shouldPauseOperations())return g(new Error("Cross-domain sharing paused: topology is in critical state"));let r=0,i=[],n=0,s=0,a=0,o=await this.transferService.queryKnowledge({minRelevance:.7,limit:100});if(!o.success)return this.failWorkflow(e,o.error.message),g(o.error);let l=o.value;for(let m of l){let p=this.getRelatedDomains(m.domain);for(let h of p){if(h===m.domain)continue;s++,(await this.transferService.transferKnowledge(m,h)).success&&(a++,r++,i.includes(h)||i.push(h))}this.updateWorkflowProgress(e,Math.round(r/(l.length*2)*100))}let u=await this.learningService.getPatternStats();if(u.success){let m=u.value.topPatterns;if(m.length>=2){let p=this.findSimilarPatterns(m);for(let h of p)h.length>=2&&(await this.learningService.consolidatePatterns(h.map(b=>b.id))).success&&n++}}this.completeWorkflow(e);let d={knowledgeShared:r,domainsUpdated:i,transferSuccessRate:s>0?a/s:null,newPatternsCreated:n};return this.config.publishEvents&&r>0&&await this.publishTransferCompleted(d),f(d)}catch(r){return this.failWorkflow(e,String(r)),g(y(r))}}async getLearningDashboard(){try{let e=await this.learningService.getPatternStats(),r=e.success?e.value:null,i=await this.transferService.queryKnowledge({limit:1e3}),n=i.success?i.value.length:0,s=Vt.lastNDays(1),a=0;for(let v of Ne){let b=await this.getExperiencesForDomain(v,s);b.success&&(a+=b.value.length)}let o=await this.productionIntel.getProductionHealth(),l=o.success?o.value.trends:[],u=await this.productionIntel.getRecentMilestones(5),d=u.success?u.value:[],m=r&&r.totalPatterns>0?r.avgSuccessRate*.6+r.avgConfidence*.4:null,p=[];if(r){let v=Object.entries(r.byDomain).filter(([b,C])=>C>0).map(([b,C])=>({domain:b,score:C})).sort((b,C)=>C.score-b.score);p.push(...v.slice(0,3).map(b=>b.domain))}let h={overallLearningRate:m,totalPatterns:r?.totalPatterns||0,totalKnowledge:n,experiencesLast24h:a,topPerformingDomains:p,learningTrend:l,recentMilestones:d};return f(h)}catch(e){return g(y(e))}}learnPattern(e,r,i,n,s,a){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.createPattern(e,r,i,n,s,a)}ensureInitialized(){if(!this.initialized)throw new Error("[LearningOptimizationCoordinator] Not initialized. Call initialize() first.")}ensureSONAAvailable(){if(!this.sona)throw new Error("[LearningOptimizationCoordinator] SONA engine is not available. Pattern persistence failed during initialization.")}async adaptPattern(e,r,i){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.adaptPattern(e,r,i)}getSONAStats(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getStats()}async getSONAPersistedStats(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPersistedStats()}getSONAPatterns(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getAllPatterns()}getSONAPatternsByType(e){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPatternsByType(e)}getSONAPatternsByDomain(e){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPatternsByDomain(e)}updateSONAPattern(e,r,i){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.updatePattern(e,r,i)}forceSONALearning(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.forceLearn()}isSONAAvailable(){return this.initialized&&this.sona!==null}exportSONAPatterns(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.exportPatterns()}importSONAPatterns(e){this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.importPatterns(e)}async verifySONAPerformance(e=100){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.verifyPerformance(e)}async triggerDreamCycle(e){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");let r=await this.dreamScheduler.triggerDream(e);return this.config.publishEvents&&await this.publishDreamCycleCompleted(r.cycle.id,r.cycle.durationMs??0,r.cycle.conceptsProcessed,r.insights.map(i=>({id:i.id,type:i.type,description:i.description,noveltyScore:i.noveltyScore,confidenceScore:i.confidenceScore,actionable:i.actionable,suggestedAction:i.suggestedAction,sourceConcepts:i.sourceConcepts})),r.patternsCreated),r}getDreamStatus(){return this.dreamScheduler?.getStatus()??null}isDreamSchedulerAvailable(){return this.dreamScheduler!==null}getLastDreamResult(){return this.dreamScheduler?.getLastDreamResult()??null}async triggerQuickDream(){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");return this.dreamScheduler.triggerQuickDream()}async triggerFullDream(){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");return this.dreamScheduler.triggerFullDream()}async exportModels(e){let r=w();try{this.startWorkflow(r,"export");let i=e||Ne,n=[],s=[],a=[],o=await Ec(this.memory,{retrieve:Oe});for(let p of o)i.includes(p.domain)&&n.push(p);this.updateWorkflowProgress(r,30);let l=await this.transferService.queryKnowledge({limit:Number.POSITIVE_INFINITY});if(l.success)for(let p of l.value)i.includes(p.domain)&&s.push(p);this.updateWorkflowProgress(r,60);let u=await wr(this.memory,"learning:strategy:optimized:*",{retrieve:Oe});for(let p of u){let h=await this.memory.get(p,Oe);h&&i.includes(h.domain)&&a.push(h)}this.updateWorkflowProgress(r,90);let d=this.calculateChecksum(n,s,a);return this.completeWorkflow(r),f({version:"1.0.0",exportedAt:new Date,patterns:n,knowledge:s,strategies:a,checksum:d})}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async importModels(e){let r=w();try{if(this.startWorkflow(r,"import"),this.calculateChecksum(e.patterns,e.knowledge,e.strategies)!==e.checksum)return this.failWorkflow(r,"Checksum mismatch"),g(new Error("Import failed: checksum mismatch"));let n=0,s=0,a=0,o=[];for(let u of e.patterns){let d=await this.memory.get(`learning:pattern:${u.id}`,{namespace:"learning-optimization"});d?d.confidence<u.confidence?(await this.memory.set(`learning:pattern:${u.id}`,u,{namespace:"learning-optimization",persist:!0}),n++,o.push({type:"pattern",id:u.id,reason:"Existing pattern had lower confidence",resolution:"overwrite"})):o.push({type:"pattern",id:u.id,reason:"Existing pattern has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:pattern:${u.id}`,u,{namespace:"learning-optimization",persist:!0}),n++),this.updateWorkflowProgress(r,Math.round(n/e.patterns.length*30))}for(let u of e.knowledge){let d=await this.memory.get(`learning:knowledge:shared:${u.id}`,Oe);d?u.version>d.version?(await this.memory.set(`learning:knowledge:shared:${u.id}`,u,{namespace:"learning-optimization",persist:!0}),s++,o.push({type:"knowledge",id:u.id,reason:"Import has newer version",resolution:"overwrite"})):o.push({type:"knowledge",id:u.id,reason:"Existing knowledge is same or newer version",resolution:"skip"}):(await this.memory.set(`learning:knowledge:shared:${u.id}`,u,{namespace:"learning-optimization",persist:!0}),s++),this.updateWorkflowProgress(r,30+Math.round(s/e.knowledge.length*30))}for(let u of e.strategies){let d=await this.memory.get(`learning:strategy:optimized:${u.id}`,Oe);d?u.confidence>d.confidence?(await this.memory.set(`learning:strategy:optimized:${u.id}`,u,{namespace:"learning-optimization",persist:!0}),a++,o.push({type:"strategy",id:u.id,reason:"Import has higher confidence",resolution:"overwrite"})):o.push({type:"strategy",id:u.id,reason:"Existing strategy has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:strategy:optimized:${u.id}`,u,{namespace:"learning-optimization",persist:!0}),a++),this.updateWorkflowProgress(r,60+Math.round(a/e.strategies.length*40))}return this.completeWorkflow(r),f({patternsImported:n,knowledgeImported:s,strategiesImported:a,conflicts:o,resolved:!0})}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}subscribeToEvents(){this.eventBus.subscribe("learning.ExperienceCaptured",this.handleExperienceCaptured.bind(this))}async handleExperienceCaptured(e){let{experience:r}=e.payload;if(!r.success||r.quality<.7)return;let i=r.domain||"learning-optimization";if(await this.learningService.recordExperience({agentId:{value:r.agent||"unknown",domain:i,type:"specialist"},domain:i,action:r.task,state:{context:{experienceId:r.id,trajectoryId:r.trajectoryId,model:r.model},metrics:{durationMs:r.durationMs,stepCount:r.steps.length,quality:r.quality}},result:{success:r.success,outcome:{quality:r.quality,patterns_extracted:r.patterns?.length||0},duration:r.durationMs},reward:r.quality}),r.patterns&&r.patterns.length>0&&r.domain){let n=this.getRelatedDomains(r.domain);for(let s of n)s!==r.domain&&await this.transferService.transferKnowledge({id:`exp-${r.id}`,domain:r.domain,type:"workflow",content:{format:"json",data:{task:r.task,steps:r.steps,quality:r.quality,patterns:r.patterns}},sourceAgentId:{value:r.agent||"experience-capture",domain:r.domain,type:"specialist"},targetDomains:[s],relevanceScore:r.quality,version:1,createdAt:new Date(r.startedAt)},s);Be.info(`[LearningOptimizationCoordinator] Experience ${r.id} transferred to ${n.length} related domains`)}this.dreamScheduler&&this.dreamScheduler.recordExperience({id:r.id,agentType:r.agent||"unknown",domain:i,taskType:r.task,success:r.success,duration:r.durationMs,context:{quality:r.quality,steps:r.steps.length,patterns:r.patterns?.length||0},timestamp:new Date(r.startedAt)})}async publishPatternConsolidated(e,r){let i={patternCount:e,domains:r,improvements:0},n=N(bt.PatternConsolidated,"learning-optimization",i);await this.eventBus.publish(n)}async publishTransferCompleted(e){let r={sourceProject:"current",targetProject:"current",patternsTransferred:e.knowledgeShared,successRate:e.transferSuccessRate??0},i=N(bt.TransferCompleted,"learning-optimization",r);await this.eventBus.publish(i)}async publishOptimizationApplied(e){let r=N(bt.OptimizationApplied,"learning-optimization",{domainsOptimized:e.domainsOptimized,avgImprovement:e.avgImprovement});await this.eventBus.publish(r)}async publishDreamCycleCompleted(e,r,i,n,s){if(!this.config.publishEvents)return;let a={cycleId:e,durationMs:r,conceptsProcessed:i,insights:n,patternsCreated:s},o=N(bt.DreamCycleCompleted,"learning-optimization",a);await this.eventBus.publish(o),Be.info(`[LearningOptimizationCoordinator] Published dream cycle completion: ${n.length} insights for ${i} concepts`)}async spawnLearningAgent(e,r){if(!this.agentCoordinator.canSpawn())return g(new Error("Agent limit reached"));let i={name:`learning-agent-${e.slice(0,8)}`,domain:"learning-optimization",type:"optimizer",capabilities:["pattern-learning","experience-mining",r],config:{workflowId:e,targetDomain:r}};return this.agentCoordinator.spawn(i)}async loadWorkflowState(){let e=await this.memory.get("learning-optimization:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("learning-optimization:coordinator:workflows",e,{namespace:"learning-optimization",persist:!0})}async getExperiencesForDomain(e,r){let i=await this.memory.search(`learning:experience:index:domain:${e}:*`,500),n=[];for(let s of i){let a=await this.memory.get(s);if(a){let o=pe(await this.memory.get(`learning:experience:${a}`),["timestamp"]);o&&r.contains(o.timestamp)&&n.push(o)}}return f(n)}async getCurrentStrategy(e){let r=`learning:strategy:current:${e}`,i=await this.memory.get(r);return i||{name:`default-${e}`,parameters:{timeout:3e4,retryCount:3,concurrency:4},expectedOutcome:{}}}async storeStrategy(e,r){await tb(this.memory,e,r)}calculateMetricValue(e,r){return rb(e,r)}getRelatedDomains(e){return ib(e)}findSimilarPatterns(e){return nb(e)}calculateChecksum(e,r,i){return sb(e,r,i)}async verifyPatternRecommendation(e,r){return ab(e,r,this.consensusMixin,this.domainName)}async verifyOptimizationSuggestion(e,r){return ob(e,r,this.consensusMixin,this.domainName)}async verifyCrossDomainInsight(e,r){return cb(e,r,this.consensusMixin,this.domainName)}};k();var om=class extends te{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;learningService=null;transferService=null;optimizerService=null;productionIntel=null;pluginConfig;get name(){return"learning-optimization"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{isSONAAvailable:()=>this.coordinator?.isSONAAvailable()??!1,getSONAPersistedStats:async()=>this.coordinator?.isSONAAvailable()?this.coordinator.getSONAPersistedStats():null,runLearningCycle:this.runLearningCycle.bind(this),optimizeAllStrategies:this.optimizeAllStrategies.bind(this),shareCrossDomainLearnings:this.shareCrossDomainLearnings.bind(this),getLearningDashboard:this.getLearningDashboard.bind(this),exportModels:this.exportModels.bind(this),importModels:this.importModels.bind(this),learnPattern:this.learnPattern.bind(this),findMatchingPatterns:this.findMatchingPatterns.bind(this),applyPattern:this.applyPattern.bind(this),updatePatternFeedback:this.updatePatternFeedback.bind(this),getPatternStats:this.getPatternStats.bind(this),queryKnowledge:this.queryKnowledge.bind(this),transferKnowledge:this.transferKnowledge.bind(this),optimizeStrategy:this.optimizeStrategy.bind(this),runABTest:this.runABTest.bind(this),recommendStrategy:this.recommendStrategy.bind(this),evaluateStrategy:this.evaluateStrategy.bind(this),getCoordinator:()=>this.coordinator,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[],getLearningService:()=>this.learningService,getTransferService:()=>this.transferService,getOptimizerService:()=>this.optimizerService,getProductionIntelService:()=>this.productionIntel}}getTaskHandlers(){return new Map([["run-learning-cycle",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.domain;return r?this.coordinator.runLearningCycle(r):g(new Error("Invalid run-learning-cycle payload: missing domain"))}],["optimize-strategies",async e=>this.coordinator?this.coordinator.optimizeAllStrategies():g(new Error("Coordinator not initialized"))],["share-learnings",async e=>this.coordinator?this.coordinator.shareCrossDomainLearnings():g(new Error("Coordinator not initialized"))],["learn-pattern",async e=>{if(!this.learningService)return g(new Error("Learning service not initialized"));let r=e.experiences;return!r||r.length===0?g(new Error("Invalid learn-pattern payload: missing experiences")):this.learningService.learnPattern(r)}],["query-knowledge",async e=>{if(!this.transferService)return g(new Error("Transfer service not initialized"));let r=e.query;return r?this.transferService.queryKnowledge(r):g(new Error("Invalid query-knowledge payload: missing query"))}]])}async onInitialize(){this.learningService=new zr({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.learningService),this.transferService=new Br(this.memory,this.pluginConfig.transferService),this.optimizerService=new qr(this.memory,this.pluginConfig.optimizerService),this.productionIntel=new Gr(this.memory,this.pluginConfig.productionIntel),this.coordinator=new xc(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.learningService=null,this.transferService=null,this.optimizerService=null,this.productionIntel=null}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestGenerated",this.handleTestGenerated.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("defect-intelligence.DefectPredicted",this.handleDefectPredicted.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"test-generation.TestGenerated":await this.handleTestGenerated(e);break;case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(e);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;default:break}}async runLearningCycle(e){this.ensureInitialized();try{let r=await this.coordinator.runLearningCycle(e);return r.success?this.trackSuccessfulOperation("learning-cycle"):this.trackFailedOperation("learning-cycle",r.error),r}catch(r){return this.handleError(r)}}async optimizeAllStrategies(){this.ensureInitialized();try{let e=await this.coordinator.optimizeAllStrategies();return e.success?this.trackSuccessfulOperation("optimization"):this.trackFailedOperation("optimization",e.error),e}catch(e){return this.handleError(e)}}async shareCrossDomainLearnings(){this.ensureInitialized();try{return await this.coordinator.shareCrossDomainLearnings()}catch(e){return this.handleError(e)}}async getLearningDashboard(){this.ensureInitialized();try{return await this.coordinator.getLearningDashboard()}catch(e){return this.handleError(e)}}async exportModels(e){this.ensureInitialized();try{return await this.coordinator.exportModels(e)}catch(r){return this.handleError(r)}}async importModels(e){this.ensureInitialized();try{return await this.coordinator.importModels(e)}catch(r){return this.handleError(r)}}async learnPattern(e){this.ensureInitialized();try{return await this.learningService.learnPattern(e)}catch(r){return this.handleError(r)}}async findMatchingPatterns(e,r){this.ensureInitialized();try{return await this.learningService.findMatchingPatterns(e,r)}catch(i){return this.handleError(i)}}async applyPattern(e,r){this.ensureInitialized();try{return await this.learningService.applyPattern(e,r)}catch(i){return this.handleError(i)}}async updatePatternFeedback(e,r){this.ensureInitialized();try{return await this.learningService.updatePatternFeedback(e,r)}catch(i){return this.handleError(i)}}async getPatternStats(e){this.ensureInitialized();try{return await this.learningService.getPatternStats(e)}catch(r){return this.handleError(r)}}async queryKnowledge(e){this.ensureInitialized();try{return await this.transferService.queryKnowledge(e)}catch(r){return this.handleError(r)}}async transferKnowledge(e,r){this.ensureInitialized();try{return await this.transferService.transferKnowledge(e,r)}catch(i){return this.handleError(i)}}async optimizeStrategy(e,r,i){this.ensureInitialized();try{return await this.optimizerService.optimizeStrategy(e,r,i)}catch(n){return this.handleError(n)}}async runABTest(e,r,i){this.ensureInitialized();try{return await this.optimizerService.runABTest(e,r,i)}catch(n){return this.handleError(n)}}async recommendStrategy(e){this.ensureInitialized();try{return await this.optimizerService.recommendStrategy(e)}catch(r){return this.handleError(r)}}async evaluateStrategy(e,r){this.ensureInitialized();try{return await this.optimizerService.evaluateStrategy(e,r)}catch(i){return this.handleError(i)}}async handleTestGenerated(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"test-generation",domain:"test-generation",type:"generator"},domain:"test-generation",action:"test-generated",state:{context:{testId:r.testId,testType:r.testType},metrics:{}},result:{success:!0,outcome:{generated:1},duration:0},reward:.8,rewardSource:"assigned",appliedPatternIds:r.patternsUsed})}async handleTestRunCompleted(e){let r=e.payload,i=r.passed+r.failed>0?r.passed/(r.passed+r.failed):0;await this.learningService.recordExperience({agentId:{value:"test-execution",domain:"test-execution",type:"tester"},domain:"test-execution",action:"test-run",state:{context:{runId:r.runId},metrics:{passed:r.passed,failed:r.failed,duration:r.duration}},result:{success:i>.8,outcome:{success_rate:i,passed:r.passed,failed:r.failed},duration:r.duration},reward:i,rewardSource:"measured"}),await this.productionIntel.recordMetric("test_success_rate",i,"ratio","test-execution",["automated"])}async handleCoverageGap(e){if(!He(e.payload))return;let r=e.payload;await this.learningService.recordExperience({agentId:{value:"coverage-analysis",domain:"coverage-analysis",type:"analyzer"},domain:"coverage-analysis",action:"gap-detection",state:{context:{gapId:r.gapId,file:r.file},metrics:{riskScore:r.riskScore}},result:{success:!0,outcome:{risk_score:r.riskScore},duration:0},reward:1-r.riskScore,rewardSource:"assigned"})}async handleQualityGate(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"quality-assessment",domain:"quality-assessment",type:"validator"},domain:"quality-assessment",action:"gate-evaluation",state:{context:{gateId:r.gateId},metrics:{passed:r.passed?1:0}},result:{success:r.passed,outcome:{gate_passed:r.passed?1:0},duration:0},reward:r.passed?1:0,rewardSource:"measured"})}async handleDefectPredicted(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"defect-intelligence",domain:"defect-intelligence",type:"analyzer"},domain:"defect-intelligence",action:"defect-prediction",state:{context:{predictionId:r.predictionId},metrics:{probability:r.probability}},result:{success:!0,outcome:{probability:r.probability},duration:0},reward:.7,rewardSource:"assigned"})}async handleImpactAnalysis(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"code-intelligence",domain:"code-intelligence",type:"analyzer"},domain:"code-intelligence",action:"impact-analysis",state:{context:{analysisId:r.analysisId},metrics:{changedFiles:r.changedFiles.length,impactedFiles:r.impactedFiles.length}},result:{success:!0,outcome:{changed_count:r.changedFiles.length,impacted_count:r.impactedFiles.length},duration:0},reward:.8,rewardSource:"assigned"})}ensureInitialized(){if(!this._initialized)throw new Error("LearningOptimizationPlugin is not initialized");if(!this.coordinator||!this.learningService||!this.transferService||!this.optimizerService||!this.productionIntel)throw new Error("LearningOptimizationPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),g(r)}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,failed:i.agents.failed+1},errors:[...i.errors.slice(-9),r.message]})}};function lb(c,t,e,r,i){return new om(c,t,e,r,i)}var cm=class extends te{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;workflowOrchestrator=null;pluginConfig;get name(){return"coordination"}get version(){return"1.0.0"}get dependencies(){return Ne.filter(e=>e!=="coordination")}getAPI(){return{listWorkflows:async()=>{if(!this.workflowOrchestrator)throw new Error("Workflow orchestrator not initialized");return this.workflowOrchestrator.listWorkflows()}}}async onInitialize(){this.workflowOrchestrator=Ym(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.workflowConfig),await this.workflowOrchestrator.initialize(),this.updateHealth({status:"healthy",agents:{total:0,active:0,idle:0,failed:0}})}async onDispose(){this.workflowOrchestrator&&(await this.workflowOrchestrator.dispose(),this.workflowOrchestrator=null)}async onEvent(e){e.type.startsWith("coordination.")&&await this.handleCoordinationEvent(e)}subscribeToEvents(){this.eventBus.subscribe("coordination.workflow.execute",async e=>{await this.handleEvent(e)})}async handleCoordinationEvent(e){e.type.split(".")[1]==="workflow"&&await this.handleWorkflowEvent(e)}async handleWorkflowEvent(e){this.workflowOrchestrator}};function ub(c,t,e,r){return new cm(c,t,e,r)}var qe={CoverageAnalyzerService:"coverage-analysis.CoverageAnalyzerService",SecurityScannerService:"security-compliance.SecurityScannerService",isSemgrepAvailable:"security-compliance.isSemgrepAvailable",runSemgrepWithRules:"security-compliance.runSemgrepWithRules",convertSemgrepFindings:"security-compliance.convertSemgrepFindings",createTestGeneratorService:"test-generation.createTestGeneratorService",KnowledgeGraphService:"code-intelligence.KnowledgeGraphService",QualityAnalyzerService:"quality-assessment.QualityAnalyzerService"},lm=class{factories=new Map;register(t,e){this.factories.set(t,e)}resolve(t){let e=this.factories.get(t);if(!e)throw new Error(`DomainServiceRegistry: service '${t}' not registered. Ensure the domain module is initialized before coordination.`);return e}has(t){return this.factories.has(t)}clear(){this.factories.clear()}keys(){return Array.from(this.factories.keys())}},Ge=new lm;Ge.register(qe.createTestGeneratorService,(c,t)=>t?Sr({memory:c,llmRouter:t}):gl(c));Ge.register(qe.CoverageAnalyzerService,c=>new Xt(c));Ge.register(qe.SecurityScannerService,c=>new dt(c));Ge.register(qe.isSemgrepAvailable,rs);Ge.register(qe.runSemgrepWithRules,ko);Ge.register(qe.convertSemgrepFindings,Do);Ge.register(qe.KnowledgeGraphService,c=>new _t(c));k();Ge.register(qe.QualityAnalyzerService,c=>new Pt(c));k();_();k();var jr={SoapOperationTested:"enterprise-integration.SoapOperationTested",MessageFlowTested:"enterprise-integration.MessageFlowTested",BapiTested:"enterprise-integration.BapiTested",IDocValidated:"enterprise-integration.IDocValidated",ODataTested:"enterprise-integration.ODataTested",SodAnalyzed:"enterprise-integration.SodAnalyzed",MiddlewareFlowTested:"enterprise-integration.MiddlewareFlowTested",IntegrationValidationFailed:"enterprise-integration.IntegrationValidationFailed"},Pk={maxConcurrentWorkflows:8,defaultTimeout:12e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Pc=x.create("enterprise-integration"),kc=class extends ie{constructor(e,r,i,n={}){let s={...Pk,...n};super(e,"enterprise-integration",s,{verifyFindingTypes:["soap-fault","message-ordering-violation","rfc-compatibility-break","idoc-validation-failure","odata-contract-break","sod-conflict"],modelTimeout:12e4});this.memory=r;this.agentCoordinator=i}memory;agentCoordinator;async onInitialize(){this.subscribeToEvents(),Pc.info("Enterprise Integration Coordinator initialized")}async onDispose(){}subscribeToEvents(){this.eventBus.subscribe("contract-testing.ContractVerified",this.handleContractVerified.bind(this)),this.eventBus.subscribe("chaos-resilience.FaultInjected",this.handleFaultInjected.bind(this))}getActiveWorkflows(){return super.getActiveWorkflows()}async validateWsdl(e){let r=w();try{if(this.startWorkflow(r,"soap"),this.minCutMixin.shouldPauseOperations())return g(new Error("WSDL validation paused: topology is in critical state"));let i=await this.spawnAgent(r,"qe-soap-tester",{task:"validate-wsdl",url:e});if(!i.success)return this.failWorkflow(r,i.error.message),i;let n={url:e,version:"1.1",services:[],schemas:[]};return await this.memory.set(`enterprise-integration:wsdl:${encodeURIComponent(e)}`,n,{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(r),f(n)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async testSoapOperation(e,r,i){let n=w();try{this.startWorkflow(n,"soap");let s=await this.spawnAgent(n,"qe-soap-tester",{task:"test-operation",wsdl:e,operation:r,input:i});if(!s.success)return this.failWorkflow(n,s.error.message),g(s.error);let a={operation:r,passed:!0,request:JSON.stringify(i),response:"",validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(N(jr.SoapOperationTested,this.domainName,{operation:r,wsdlUrl:e.url,passed:a.passed,errors:a.validationErrors.length})),this.completeWorkflow(n),f(a)}catch(s){return this.failWorkflow(n,String(s)),g(y(s))}}async testMessageFlow(e,r){let i=w();try{this.startWorkflow(i,"messaging");let n=await this.spawnAgent(i,"qe-message-broker-tester",{task:"test-message-flow",brokerConfig:e,testCase:r});if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);let s={testCaseId:r.id,passed:!0,sentAt:new Date,receivedAt:new Date,latency:0,actualOutcome:r.expectedOutcome,errors:[]};return this.config.publishEvents&&await this.eventBus.publish(N(jr.MessageFlowTested,this.domainName,{protocol:e.protocol,queue:r.queue,passed:s.passed,latency:s.latency})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async testDlqHandling(e,r){let i=w();try{this.startWorkflow(i,"messaging");let n=await this.spawnAgent(i,"qe-message-broker-tester",{task:"test-dlq",brokerConfig:e,queue:r});if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);let s={queue:r,messageCount:0,poisonMessages:0,reprocessable:0,errors:[]};return this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async testBapiCall(e,r){let i=w();try{if(this.startWorkflow(i,"rfc"),this.minCutMixin.shouldPauseOperations())return g(new Error("BAPI testing paused: topology is in critical state"));let n=await this.spawnAgent(i,"qe-sap-rfc-tester",{task:"test-bapi",connection:e,bapi:r});if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);let s={bapiName:r.name,passed:!0,returnMessages:[],exportValues:{},tableData:{},duration:0,transactionCommitted:!1};return this.config.publishEvents&&await this.eventBus.publish(N(jr.BapiTested,this.domainName,{bapiName:r.name,passed:s.passed,returnType:s.returnMessages.length>0?s.returnMessages[0].type:"S"})),await this.memory.set(`enterprise-integration:bapi:${r.name}:${Date.now()}`,{bapiName:r.name,importParams:Object.keys(r.importParams),passed:s.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async validateIdoc(e,r){let i=w();try{this.startWorkflow(i,"idoc");let n=await this.spawnAgent(i,"qe-sap-idoc-tester",{task:"validate-idoc",definition:e,content:r});if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);let s={idocType:e.type,direction:"inbound",passed:!0,statusCode:3,statusMessage:"IDoc validated successfully",segmentValidation:[],processingTime:0};return this.config.publishEvents&&await this.eventBus.publish(N(jr.IDocValidated,this.domainName,{idocType:e.type,direction:s.direction,passed:s.passed,statusCode:s.statusCode})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async validateODataMetadata(e){let r=w();try{this.startWorkflow(r,"odata");let i=await this.spawnAgent(r,"qe-odata-contract-tester",{task:"validate-metadata",serviceUrl:e});if(!i.success)return this.failWorkflow(r,i.error.message),g(i.error);let n={version:"v4",serviceUrl:e,entitySets:[],functionImports:[],actions:[]};return await this.memory.set(`enterprise-integration:odata:${encodeURIComponent(e)}`,n,{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(r),f(n)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async testODataEntitySet(e,r){let i=w();try{this.startWorkflow(i,"odata");let n=await this.spawnAgent(i,"qe-odata-contract-tester",{task:"test-entity-set",metadata:e,entitySet:r});if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);let s={entitySet:r,operation:"CRUD",passed:!0,statusCode:200,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(N(jr.ODataTested,this.domainName,{entitySet:r,operation:s.operation,passed:s.passed,version:e.version})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async validateMessageFlow(e,r){let i=w();try{this.startWorkflow(i,"middleware");let n=await this.spawnAgent(i,"qe-middleware-validator",{task:"validate-flow",flow:e,input:r});if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);let s={flowName:e.name,passed:!0,routingCorrect:!0,transformationCorrect:!0,errorHandlingCorrect:!0,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(N(jr.MiddlewareFlowTested,this.domainName,{flowName:e.name,passed:s.passed,routingCorrect:s.routingCorrect,transformationCorrect:s.transformationCorrect})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async validateTransformation(e,r,i){let n=w();try{this.startWorkflow(n,"middleware");let s=await this.spawnAgent(n,"qe-middleware-validator",{task:"validate-transformation",spec:e,input:r,expectedOutput:i});return s.success?(this.completeWorkflow(n),f(!0)):(this.failWorkflow(n,s.error.message),g(s.error))}catch(s){return this.failWorkflow(n,String(s)),g(y(s))}}async analyzeSod(e,r){let i=w();try{this.startWorkflow(i,"sod");let n=await this.spawnAgent(i,"qe-sod-analyzer",{task:"analyze-sod",userId:e,ruleset:r});if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);let s={userId:e,conflicts:[],riskScore:0,compliant:!0,recommendations:[]};return this.config.publishEvents&&await this.eventBus.publish(N(jr.SodAnalyzed,this.domainName,{userId:e,conflicts:s.conflicts.length,compliant:s.compliant,riskScore:s.riskScore})),await this.memory.set(`enterprise-integration:sod:${e}:${Date.now()}`,{userId:e,ruleset:r.name,conflicts:s.conflicts.length,compliant:s.compliant,riskScore:s.riskScore,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async spawnAgent(e,r,i){let n={name:`${r}-${e.slice(0,8)}`,domain:"enterprise-integration",type:r,capabilities:[r],config:{workflowId:e,...i}},s=await this.agentCoordinator.spawn(n);return s.success&&this.addAgentToWorkflow(e,s.value),s}async verifyCriticalFinding(e,r){let i=U({id:w(),type:e.type,confidence:r,description:e.description,payload:e.payload,detectedBy:"enterprise-integration-coordinator",severity:r>.9?"critical":"high"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Pc.info(`Finding verified by consensus: ${e.type}`),!0):(Pc.warn(`Finding NOT verified: ${e.type}`),!1)}return!0}async handleContractVerified(e){let r=e.payload;(r?.contractType==="soap"||r?.contractType==="odata")&&await this.memory.set(`enterprise-integration:contract-event:${Date.now()}`,{contractId:r.contractId,type:r.contractType,passed:r.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleFaultInjected(e){let r=e.payload;(r?.targetService?.includes("middleware")||r?.targetService?.includes("esb"))&&Pc.info(`Middleware fault injection detected: ${r.targetService}`)}};var um=class extends te{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;pluginConfig;get name(){return"enterprise-integration"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{validateWsdl:this.validateWsdl.bind(this),testSoapOperation:this.testSoapOperation.bind(this),testMessageFlow:this.testMessageFlow.bind(this),testDlqHandling:this.testDlqHandling.bind(this),testBapiCall:this.testBapiCall.bind(this),validateIdoc:this.validateIdoc.bind(this),validateODataMetadata:this.validateODataMetadata.bind(this),testODataEntitySet:this.testODataEntitySet.bind(this),validateMessageFlow:this.validateMessageFlow.bind(this),validateTransformation:this.validateTransformation.bind(this),analyzeSod:this.analyzeSod.bind(this),getCoordinator:()=>this.coordinator,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[]}}getTaskHandlers(){return new Map([["enterprise-integration:soap-test",async e=>{if(!this.coordinator)return g(new Error("Enterprise integration coordinator not initialized"));let r=e.wsdl,i=e.operation,n=e.input;return e.url&&!r?this.coordinator.validateWsdl(e.url):!r||!i?g(new Error("Invalid soap-test payload: missing wsdl or operation")):this.coordinator.testSoapOperation(r,i,n)}],["enterprise-integration:message-broker-test",async e=>{if(!this.coordinator)return g(new Error("Enterprise integration coordinator not initialized"));let r=e.brokerConfig,i=e.testCase,n=e.queue;return r?n&&!i?this.coordinator.testDlqHandling(r,n):i?this.coordinator.testMessageFlow(r,i):g(new Error("Invalid message-broker-test payload: missing testCase")):g(new Error("Invalid message-broker-test payload: missing brokerConfig"))}],["enterprise-integration:sap-rfc-test",async e=>{if(!this.coordinator)return g(new Error("Enterprise integration coordinator not initialized"));let r=e.connection,i=e.bapi;return!r||!i?g(new Error("Invalid sap-rfc-test payload: missing connection or bapi")):this.coordinator.testBapiCall(r,i)}],["enterprise-integration:sap-idoc-validate",async e=>{if(!this.coordinator)return g(new Error("Enterprise integration coordinator not initialized"));let r=e.definition,i=e.content;return!r||!i?g(new Error("Invalid sap-idoc-validate payload: missing definition or content")):this.coordinator.validateIdoc(r,i)}],["enterprise-integration:odata-test",async e=>{if(!this.coordinator)return g(new Error("Enterprise integration coordinator not initialized"));let r=e.serviceUrl,i=e.metadata,n=e.entitySet;return r&&!i?this.coordinator.validateODataMetadata(r):!i||!n?g(new Error("Invalid odata-test payload: missing metadata or entitySet")):this.coordinator.testODataEntitySet(i,n)}],["enterprise-integration:esb-flow-test",async e=>{if(!this.coordinator)return g(new Error("Enterprise integration coordinator not initialized"));let r=e.flow,i=e.input,n=e.spec;if(n){let s=e.transformInput,a=e.expectedOutput;return!s||!a?g(new Error("Invalid esb-flow-test payload: missing transformInput or expectedOutput for transformation")):this.coordinator.validateTransformation(n,s,a)}return!r||!i?g(new Error("Invalid esb-flow-test payload: missing flow or input")):this.coordinator.validateMessageFlow(r,i)}],["enterprise-integration:sod-analyze",async e=>{if(!this.coordinator)return g(new Error("Enterprise integration coordinator not initialized"));let r=e.userId,i=e.ruleset;return!r||!i?g(new Error("Invalid sod-analyze payload: missing userId or ruleset")):this.coordinator.analyzeSod(r,i)}]])}async onInitialize(){this.coordinator=new kc(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null}subscribeToEvents(){this.eventBus.subscribe("contract-testing.ContractVerified",this.handleContractVerified.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("chaos-resilience.FaultInjected",this.handleFaultInjected.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"contract-testing.ContractVerified":await this.handleContractVerified(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGate(e);break;case"chaos-resilience.FaultInjected":await this.handleFaultInjected(e);break;default:break}}async validateWsdl(e){this.ensureInitialized();try{let r=await this.coordinator.validateWsdl(e);return r.success?this.trackSuccessfulOperation("validateWsdl"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async testSoapOperation(e,r,i){this.ensureInitialized();try{let n=await this.coordinator.testSoapOperation(e,r,i);return n.success?this.trackSuccessfulOperation("testSoapOperation"):this.trackFailedOperation(new Error(n.error.message)),n}catch(n){return this.handleError(n)}}async testMessageFlow(e,r){this.ensureInitialized();try{let i=await this.coordinator.testMessageFlow(e,r);return i.success?this.trackSuccessfulOperation("testMessageFlow"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async testDlqHandling(e,r){this.ensureInitialized();try{let i=await this.coordinator.testDlqHandling(e,r);return i.success?this.trackSuccessfulOperation("testDlqHandling"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async testBapiCall(e,r){this.ensureInitialized();try{let i=await this.coordinator.testBapiCall(e,r);return i.success?this.trackSuccessfulOperation("testBapiCall"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateIdoc(e,r){this.ensureInitialized();try{let i=await this.coordinator.validateIdoc(e,r);return i.success?this.trackSuccessfulOperation("validateIdoc"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateODataMetadata(e){this.ensureInitialized();try{let r=await this.coordinator.validateODataMetadata(e);return r.success?this.trackSuccessfulOperation("validateODataMetadata"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async testODataEntitySet(e,r){this.ensureInitialized();try{let i=await this.coordinator.testODataEntitySet(e,r);return i.success?this.trackSuccessfulOperation("testODataEntitySet"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateMessageFlow(e,r){this.ensureInitialized();try{let i=await this.coordinator.validateMessageFlow(e,r);return i.success?this.trackSuccessfulOperation("validateMessageFlow"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateTransformation(e,r,i){this.ensureInitialized();try{let n=await this.coordinator.validateTransformation(e,r,i);return n.success?this.trackSuccessfulOperation("validateTransformation"):this.trackFailedOperation(new Error(n.error.message)),n}catch(n){return this.handleError(n)}}async analyzeSod(e,r){this.ensureInitialized();try{let i=await this.coordinator.analyzeSod(e,r);return i.success?this.trackSuccessfulOperation("analyzeSod"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async handleContractVerified(e){let r=e.payload;(r.contractType==="soap"||r.contractType==="odata")&&await this.memory.set(`enterprise-integration:contract-verified:${r.contractId}`,{contractId:r.contractId,type:r.contractType,passed:r.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleQualityGate(e){let r=e.payload;r.checks.find(n=>n.name==="enterprise-integration")||await this.memory.set(`enterprise-integration:quality-gate-warning:${r.gateId}`,{warning:"Enterprise integration testing not included in quality gate",timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleFaultInjected(e){let r=e.payload;(r.targetService?.includes("middleware")||r.targetService?.includes("esb")||r.targetService?.includes("broker")||r.targetService?.includes("mq"))&&await this.memory.set(`enterprise-integration:fault-correlation:${r.faultId||Date.now()}`,{targetService:r.targetService,faultType:r.faultType,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:3600})}ensureInitialized(){if(!this._initialized)throw new Error("EnterpriseIntegrationPlugin is not initialized");if(!this.coordinator)throw new Error("EnterpriseIntegrationPlugin coordinator is not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function mb(c,t,e,r){return new um(c,t,e,r)}var gb={"test-generation":(c,t,e,r)=>Kl(c,t,e,void 0,r),"test-execution":(c,t,e,r)=>yg(c,t,r),"coverage-analysis":(c,t,e,r)=>xu(c,t,r),"quality-assessment":(c,t,e,r)=>_u(c,t,e,void 0,r),"defect-intelligence":(c,t,e,r)=>ch(c,t,e,void 0,r),"requirements-validation":(c,t,e,r)=>ph(c,t,e,void 0,r),"code-intelligence":(c,t,e,r)=>nd(c,t,e,void 0,r),"security-compliance":(c,t,e,r)=>Yd(c,t,e,void 0,r),"contract-testing":(c,t,e,r)=>kv(c,t,e,void 0,r),"visual-accessibility":(c,t,e,r)=>jv(c,t,e,void 0,r),"chaos-resilience":(c,t,e,r)=>Uv(c,t,e,void 0,r),"learning-optimization":(c,t,e,r)=>lb(c,t,e,void 0,r),"enterprise-integration":(c,t,e,r)=>mb(c,t,e),coordination:(c,t,e,r)=>ub(c,t,e)},kk={maxConcurrentAgents:Hi.MAX_CONCURRENT_AGENTS,memoryBackend:"hybrid",hnswEnabled:!0,lazyLoading:!0,enabledDomains:[...Ne],dataDir:void 0,enableExperienceBridge:!0,enableDreamScheduler:!0},dm=class{_eventBus;_coordinator;_plugins;_memory;_config;_startTime;_initialized=!1;_loopTracker;_experienceBridge;_dreamScheduler;_llmRouter;_llmRouterBuild;constructor(t={}){this._config={...kk,...t},this._startTime=new Date,this._memory=new Oc,this._eventBus=new Bs,this._coordinator=new qs(this._config.maxConcurrentAgents),this._plugins=new sn(this._eventBus,this._memory,this._config.lazyLoading),this._loopTracker=new Gs}get eventBus(){return this._eventBus}get coordinator(){return this._coordinator}get plugins(){return this._plugins}get memory(){return this._memory}get llmRouter(){return this._llmRouter}async initialize(){if(this._initialized)return;let t=Ce(),e=this._config.dataDir||Gi.join(t,".agentic-qe");if(this._config.memoryBackend!=="memory"&&!Dc.existsSync(e)&&Dc.mkdirSync(e,{recursive:!0}),this._config.memoryBackend==="memory"){let i=Gi.join(mm("os").tmpdir(),`aqe-test-${Date.now()}-${pb().slice(0,12)}.db`);await Rm({dbPath:i})}else this._memory=pm(e),this._plugins=new sn(this._eventBus,this._memory,this._config.lazyLoading);await this._initializeLLMRouter(t);for(let i of this._config.enabledDomains){let n=gb[i];n&&this._plugins.registerFactory(i,async(s,a)=>Promise.resolve(n(s,a,this._coordinator,this._llmRouter)))}await this._memory.initialize();let r=new Hs({agentId:"qe-kernel"});this._eventBus.registerMiddleware(r);try{let i=Gi.join(e,"plugins"),n=new Tm({cacheDir:i}),a=new Em({cache:n}).resolveLoadOrder();for(let o of a.errors)console.warn(`[QEKernel] External plugin ${o.plugin}: ${o.code}: ${o.message}`);for(let o of a.ordered){let l=o.manifest,u=n.get(l.name,l.version);if(!u)continue;let d=Gi.join(u.path,l.entryPoint);for(let m of l.domains){let p=m;if(gb[p])continue;this._plugins.registerFactory(p,async(v,b)=>{let C=await import(d),S=C.default??C.createPlugin;if(typeof S!="function")throw new Error(`Plugin "${l.name}" entry point must export a default function or "createPlugin" function`);return S(v,b,this._coordinator,this._llmRouter)})}}}catch(i){console.warn("[QEKernel] External plugin discovery failed:",i)}this._config.lazyLoading||await this._plugins.loadAll();try{let{isAgentMemoryBranchingEnabled:i,isRVFPatternStoreEnabled:n}=await import("./feature-flags-O7ZXDDCD.js");if(i()&&n()){let{getSharedRvfAdapter:s}=await import("./shared-rvf-adapter-DROMBRV2.js"),{AgentMemoryBranch:a}=await import("./agent-memory-branch-ARC5C7GW.js"),o=s(e,384);if(o){let l=new a(o,{branchDir:Gi.join(e,"branches")});this._coordinator.setMemoryBranch(l)}}}catch{}try{let{getRvfMigrationStage:i}=await import("./feature-flags-O7ZXDDCD.js"),n=i();if(n>=2){let{RvfMigrationCoordinator:s}=await import("./rvf-migration-coordinator-7CHEV35N.js");await s.getInstance({stage:n}).initialize()}}catch{}if(this._config.enableExperienceBridge!==!1){try{await this._plugins.loadAll()}catch(i){console.warn("[QEKernel] domain plugin pre-load (for bridge subscribers) failed:",i instanceof Error?i.message:i)}try{this._experienceBridge=new Ws(this._eventBus,this._memory),await this._experienceBridge.start()}catch(i){console.warn("[QEKernel] CapturedExperienceBridge failed to start:",i instanceof Error?i.message:i),this._experienceBridge=void 0}}if(this._config.enableDreamScheduler!==!1)try{let i=Rs({maxDurationMs:1e4,minConceptsRequired:3});await i.initialize(),this._dreamScheduler=new km({dreamEngine:i,eventBus:this._eventBus,memoryBackend:this._memory}),await this._dreamScheduler.initialize(),this._dreamScheduler.start()}catch(i){if(console.warn("[QEKernel] DreamScheduler failed to start:",i instanceof Error?i.message:i),this._dreamScheduler)try{await this._dreamScheduler.dispose()}catch{}this._dreamScheduler=void 0}this._initialized=!0}async _initializeLLMRouter(t){let e=(process.env.AQE_LLM_ROUTER_DISABLED??"").trim().toLowerCase();if(e&&e!=="false"&&e!=="0"&&e!=="no"&&e!=="off"){this._llmRouter=void 0;return}let r=this._config.llmRouter??{},i=r.enabled??"auto";if(i===!1){this._llmRouter=void 0;return}try{let n=await Cm({projectRoot:t,override:r.configOverride,providerManager:r.providerManager});if(!n){i===!0&&(console.warn("[QEKernel] llmRouter.enabled=true but no provider available \u2014 continuing without LLM router (domain services will skip LLM enhancement)"),await this._publishLLMRouterEvent("init-no-provider",{reason:"no provider available in env or disk config"})),this._llmRouter=void 0;return}this._llmRouterBuild=n,this._llmRouter=n.router;try{let{setSharedLLMRouter:s}=await import("./base-AK7BXBX2.js");s(n.router)}catch{}}catch(n){let s=n instanceof Error?n.message:String(n);console.warn("[QEKernel] LLM router init failed; continuing without LLM enhancement:",s),await this._publishLLMRouterEvent("init-failed",{error:s,stack:n instanceof Error?n.stack:void 0}),this._llmRouter=void 0}}async _publishLLMRouterEvent(t,e){try{await this._eventBus.publish({id:pb(),type:`kernel.llm-router.${t}`,timestamp:new Date,source:"qe-kernel",payload:e})}catch{}}async dispose(){if(this._dreamScheduler){try{await this._dreamScheduler.dispose()}catch(t){console.warn("[QEKernel] DreamScheduler dispose failed:",t instanceof Error?t.message:t)}this._dreamScheduler=void 0}if(this._experienceBridge&&(await this._experienceBridge.stop(),this._experienceBridge=void 0),await this._plugins.disposeAll(),await this._coordinator.dispose(),await this._eventBus.dispose(),await this._memory.dispose(),this._llmRouter){try{let{resetSharedLLMRouter:t}=await import("./base-AK7BXBX2.js");t()}catch{}this._llmRouter=void 0,this._llmRouterBuild=void 0}this._initialized=!1}getDomainAPI(t){return this._plugins.getPlugin(t)?.getAPI()}async getDomainAPIAsync(t){let e=this._plugins.getPlugin(t);if(!e&&this._config.lazyLoading&&this._config.enabledDomains.includes(t))try{e=await this._plugins.load(t)}catch(r){console.error(`[QEKernel] Failed to lazy load domain ${t}:`,Mc(r));return}return e?.getAPI()}async ensureDomainLoaded(t){if(this._plugins.isLoaded(t))return!0;if(!this._config.enabledDomains.includes(t))return console.warn(`[QEKernel] Domain ${t} is not enabled`),!1;try{return await this._plugins.load(t),!0}catch(e){return console.error(`[QEKernel] Failed to load domain ${t}:`,Mc(e)),!1}}isDomainLoaded(t){return this._plugins.isLoaded(t)}getLoadedDomains(){return this._plugins.getLoaded()}getPendingDomains(){let t=new Set(this._plugins.getLoaded());return this._config.enabledDomains.filter(e=>!t.has(e))}getHealth(){let t=this._coordinator.listAgents(),e={};for(let l of this._plugins.getLoaded()){let u=this._plugins.getPlugin(l);u&&(e[l]=u.getHealth())}for(let l of Ne)if(!e[l]){let u=this._config.enabledDomains.includes(l),d=this._config.lazyLoading&&u;e[l]={status:d?"healthy":u?"degraded":"healthy",agents:{total:0,active:0,idle:0,failed:0},errors:d?[]:u?["Domain not yet loaded"]:[],loaded:!1,lazyLoadable:d}}let r=this._coordinator.getActiveCount(),i=0,n=Number.MAX_SAFE_INTEGER;if(this._memory instanceof Oc){let l=this._memory.getStats();i=l.entries+l.vectors}else i=0;let a=this._eventBus.getMiddlewares().find(l=>l.name==="semantic-anti-drift"),o=a?a.getStats():void 0;return{status:this.determineOverallStatus(e),uptime:Date.now()-this._startTime.getTime(),domains:e,agents:{total:t.length,active:r,maxAllowed:this._config.maxConcurrentAgents},memory:{used:i,available:n},...o?{antiDrift:o}:{}}}determineOverallStatus(t){let e=Object.values(t).map(r=>r.status);return e.some(r=>r==="unhealthy")?"unhealthy":e.some(r=>r==="degraded")?"degraded":"healthy"}getConfig(){return{...this._config}}checkToolCall(t,e,r){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return this._loopTracker.trackCall(t,e,r);let i=this._loopTracker.trackCall(t,e,r);if(i.action==="warn"){let n={id:`loop-warn-${t}-${Date.now()}`,type:el.LOOP_WARNING,timestamp:new Date,source:"coordination",correlationId:t,payload:{agentId:t,toolName:e,callCount:i.callCount,signature:i.signature}};this._eventBus.publish(n)}else if(i.action==="steer"){let n={id:`loop-detected-${t}-${Date.now()}`,type:el.LOOP_DETECTED,timestamp:new Date,source:"coordination",correlationId:t,payload:{agentId:t,toolName:e,callCount:i.callCount,signature:i.signature,steeringMessage:i.steeringMessage}};this._eventBus.publish(n)}return i}get loopTracker(){return this._loopTracker}};function _ce(c){return new dm(c)}export{Bs as a,ul as b,Ob as c,ei as d,Sr as e,Wp as f,Kp as g,Xt as h,di as i,iq as j,ze as k,nq as l,sq as m,aq as n,oq as o,gi as p,gh as q,wo as r,Co as s,Th as t,Fr as u,rd as v,sd as w,cd as x,Po as y,Fi as z,Li as A,yc as B,Ni as C,Vi as D,It as E,zr as F,Br as G,qr as H,qe as I,Ge as J,dm as K,_ce as L};
3011
+ // Execute action: {{action}}`,variables:r}}extractPatternContext(t){let e=new Set,r,i;for(let n of t){let s=n.state.context;if(s.language&&(r=s.language),s.framework&&(i=s.framework),s.tags&&Array.isArray(s.tags))for(let a of s.tags)e.add(a)}return{language:r,framework:i,tags:Array.from(e)}}detectAnomalies(t){let e=[],r=this.calculateAverageReward(t),i=this.calculateStdDev(t.map(n=>n.reward));for(let n of t){let s=Math.abs(n.reward-r)/(i||1);if(s>this.config.anomalyDeviationThreshold){let a="outlier-reward";n.result.success&&n.reward<r?a="unexpected-success":!n.result.success&&n.reward>r&&(a="unexpected-failure"),e.push({experienceId:n.id,type:a,description:`Reward ${n.reward.toFixed(2)} deviates ${s.toFixed(2)} std from mean ${r.toFixed(2)}`,deviation:s})}}return e}calculateStdDev(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n,0)/t.length,r=t.map(i=>Math.pow(i-e,2));return Math.sqrt(r.reduce((i,n)=>i+n,0)/t.length)}generateRecommendations(t,e,r){let i=[];return e<.5&&i.push("Low success rate detected. Consider reviewing the approach or gathering more training data."),r.length>t.length*.1&&i.push("High anomaly rate detected. Investigate unexpected outcomes for potential improvements."),t.reduce((s,a)=>s+a.result.duration,0)/t.length>6e4&&i.push("Average operation duration is high. Consider optimizing performance."),t.length<10&&i.push("Limited experience data. Collect more data points for better insights."),i.length===0&&i.push("Performance metrics are within acceptable ranges. Continue monitoring."),i}actionsSimilar(t,e){let r=s=>s.toLowerCase().replace(/[^a-z]/g,""),i=r(t),n=r(e);return!!(i===n||i.includes(n)||n.includes(i))}calculateCentroid(t){let e=Ve(),r=Ve();for(let i of t)for(let[n,s]of Object.entries(i.state.metrics))e[n]=(e[n]||0)+s,r[n]=(r[n]||0)+1;for(let i of Object.keys(e))e[i]/=r[i];return{context:{},metrics:e}}isConstraintViolated(t,e){switch(t.operator){case"lt":return e>=t.value;case"gt":return e<=t.value;case"lte":return e>t.value;case"gte":return e<t.value;case"eq":return e!==t.value;default:return!1}}};k();var fk={maxKnowledgeItems:1e3,relevanceThreshold:.5,transferDecayFactor:.1,crossDomainBoost:.2},Br=class{constructor(t,e={}){this.memory=t;this.config={...fk,...e}}memory;config;async shareKnowledge(t,e){try{await this.memory.set(`learning:knowledge:shared:${t.id}`,t,{namespace:"learning-optimization",persist:!0});for(let r of e)await this.memory.set(`learning:knowledge:access:${r.value}:${t.id}`,{knowledgeId:t.id,agentId:r.value,sharedAt:new Date,accessed:!1},{namespace:"learning-optimization",ttl:86400*7});return await this.recordSharingEvent(t,e),f(void 0)}catch(r){return g(y(r))}}async queryKnowledge(t){try{let e=[],r=await wr(this.memory,"learning:knowledge:shared:*",{retrieve:Oe,pageSize:this.config.maxKnowledgeItems});for(let i of r){let n=pe(await this.memory.get(i,{namespace:"learning-optimization"}),["createdAt","expiresAt"]);n&&this.matchesQuery(n,t)&&e.push(n)}if(e.sort((i,n)=>n.relevanceScore-i.relevanceScore||(i.id<n.id?-1:i.id>n.id?1:0)),t.embedding&&t.embedding.length>0){let i=await this.memory.vectorSearch(t.embedding,t.limit||10);for(let n of i){let s=pe(await this.memory.get(n.key,{namespace:"learning-optimization"}),["createdAt","expiresAt"]);s&&!e.some(a=>a.id===s.id)&&this.matchesQuery(s,t)&&e.push(s)}}return f(e.slice(0,t.limit||100))}catch(e){return g(y(e))}}async synthesizeKnowledge(t){try{if(t.length<2)return g(new Error("Need at least 2 knowledge items to synthesize"));let e=[];for(let l of t){let u=await this.getKnowledgeById(l);u&&e.push(u)}if(e.length<2)return g(new Error("Not enough valid knowledge items found"));let r=this.determineSynthesizedType(e),i=this.determineSynthesizedDomain(e),n=this.mergeKnowledgeContent(e),s=e.reduce((l,u)=>l+u.relevanceScore,0)/e.length,a=Math.min(1,s+this.config.crossDomainBoost),o={id:w(),type:r,domain:i,content:n,sourceAgentId:e[0].sourceAgentId,targetDomains:this.mergeTargetDomains(e),relevanceScore:a,version:1,createdAt:new Date};return await this.storeKnowledge(o),await this.recordSynthesisEvent(o,t),f(o)}catch(e){return g(y(e))}}async transferKnowledge(t,e){try{if(t.domain===e)return g(new Error("Cannot transfer knowledge to the same domain"));let r=this.calculateTransferredRelevance(t,e);if(r<this.config.relevanceThreshold)return g(new Error(`Transferred relevance ${r} below threshold ${this.config.relevanceThreshold}`));let i=await this.adaptContentForDomain(t.content,t.domain,e),n={id:w(),type:t.type,domain:e,content:i,sourceAgentId:t.sourceAgentId,targetDomains:[e],relevanceScore:r,version:t.version+1,createdAt:new Date};return await this.storeKnowledge(n),await this.recordTransferEvent(t,n),f(n)}catch(r){return g(y(r))}}async validateRelevance(t,e){try{let r=t.relevanceScore;if(e.language&&t.content.metadata?.language===e.language&&(r+=.1),e.framework&&t.content.metadata?.framework===e.framework&&(r+=.1),e.tags.length>0&&t.content.metadata?.tags){let a=t.content.metadata.tags,o=e.tags.filter(l=>a.includes(l));r+=o.length/e.tags.length*.2}let n=(Date.now()-t.createdAt.getTime())/(1e3*60*60*24),s=Math.exp(-this.config.transferDecayFactor*n/30);return r*=s,t.expiresAt&&new Date>t.expiresAt&&(r*=.5),f(Math.min(1,Math.max(0,r)))}catch(r){return g(y(r))}}async createKnowledge(t,e,r,i,n=[],s){try{let a={id:w(),type:t,domain:e,content:{format:this.inferContentFormat(r),data:r,metadata:s},sourceAgentId:i,targetDomains:n,relevanceScore:1,version:1,createdAt:new Date};return await this.storeKnowledge(a),t==="embedding"&&Array.isArray(r)&&await this.memory.storeVector(`learning:knowledge:vector:${a.id}`,r,{knowledgeId:a.id}),f(a)}catch(a){return g(y(a))}}async getKnowledgeById(t){return pe(await this.memory.get(`learning:knowledge:shared:${t}`,{namespace:"learning-optimization"}),["createdAt","expiresAt"])||null}async bulkTransfer(t,e,r){try{let i=`learning:knowledge:project:${t}:`,n=(await wr(this.memory,`${i}*`,{retrieve:Oe})).filter(a=>a.startsWith(i)&&!a.slice(i.length).includes(":")),s=[];for(let a of n){let o=pe(await this.memory.get(a,Oe),["createdAt","expiresAt"]);if(!o||r?.types&&!r.types.includes(o.type)||r?.minRelevance&&o.relevanceScore<r.minRelevance)continue;let l=await this.adaptContentForProject(o.content,t,e),u={...o,id:w(),content:l,relevanceScore:o.relevanceScore*(1-this.config.transferDecayFactor),version:o.version+1,createdAt:new Date};await this.memory.set(`learning:knowledge:project:${e}:${u.id}`,u,{namespace:"learning-optimization",persist:!0}),s.push({knowledgeId:u.id,sourceDomain:o.domain,targetDomain:o.domain,originalRelevance:o.relevanceScore,transferredRelevance:u.relevanceScore,adaptations:["project-context-adapted"]})}return f(s)}catch(i){return g(y(i))}}async storeKnowledge(t){await this.memory.set(`learning:knowledge:shared:${t.id}`,t,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:knowledge:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:knowledge:type:${t.type}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}matchesQuery(t,e){if(e.type&&t.type!==e.type||e.domain&&t.domain!==e.domain||e.minRelevance!==void 0&&t.relevanceScore<e.minRelevance)return!1;if(e.tags&&e.tags.length>0){let r=t.content.metadata?.tags||[];if(!e.tags.some(n=>r.includes(n)))return!1}return!0}determineSynthesizedType(t){let e=new Map;for(let n of t)e.set(n.type,(e.get(n.type)||0)+1);let r=t[0].type,i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}determineSynthesizedDomain(t){let e=new Map;for(let n of t)e.set(n.domain,(e.get(n.domain)||0)+1);let r=t[0].domain,i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}mergeKnowledgeContent(t){let e={},r=[];for(let i of t)if(r.push(i.content.data),i.content.metadata)for(let[n,s]of Object.entries(i.content.metadata))if(Array.isArray(s)){let a=e[n]||[];e[n]=[...new Set([...a,...s])]}else e[n]=s;return{format:"json",data:{synthesized:!0,sources:r},metadata:{...e,synthesizedFrom:t.map(i=>i.id),synthesizedAt:new Date().toISOString()}}}mergeTargetDomains(t){let e=new Set;for(let r of t){e.add(r.domain);for(let i of r.targetDomains)e.add(i)}return Array.from(e)}calculateTransferredRelevance(t,e){let r=t.relevanceScore;r*=1-this.config.transferDecayFactor;let i=this.getDomainCompatibility(t.domain,e);return r*=i,t.targetDomains.includes(e)&&(r+=this.config.crossDomainBoost),Math.min(1,Math.max(0,r))}getDomainCompatibility(t,e){let r={"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"],"enterprise-integration":["contract-testing","security-compliance","quality-assessment"],coordination:Ne.filter(i=>i!=="coordination")};return t===e?1:r[t]?.includes(e)?.8:.5}async adaptContentForDomain(t,e,r){return{...t,metadata:{...t.metadata||{},adaptedFrom:e,adaptedTo:r,adaptedAt:new Date().toISOString()}}}async adaptContentForProject(t,e,r){return{...t,metadata:{...t.metadata||{},sourceProject:e,targetProject:r,transferredAt:new Date().toISOString()}}}inferContentFormat(t){return typeof t=="string"?"text":Array.isArray(t)&&t.every(e=>typeof e=="number")?"embedding":"json"}async recordSharingEvent(t,e){await this.memory.set(`learning:knowledge:events:share:${t.id}:${Date.now()}`,{type:"share",knowledgeId:t.id,targetAgents:e.map(r=>r.value),timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}async recordSynthesisEvent(t,e){await this.memory.set(`learning:knowledge:events:synthesis:${t.id}`,{type:"synthesis",synthesizedId:t.id,sourceIds:e,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}async recordTransferEvent(t,e){await this.memory.set(`learning:knowledge:events:transfer:${e.id}`,{type:"transfer",originalId:t.id,transferredId:e.id,originalDomain:t.domain,targetDomain:e.domain,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}};k();var yk={defaultConfidenceLevel:.95,minSamplesForOptimization:20,maxOptimizationIterations:100,improvementThreshold:.05,explorationRate:.1},fs={namespace:"learning-optimization"},vk=.2,bk=.2,wk=["__proto__","constructor","prototype"];function ys(c){return!wk.includes(c)}var qr=class{constructor(t,e={}){this.memory=t;this.config={...yk,...e}}memory;config;async optimizeStrategy(t,e,r){try{let{measured:i,assignedExcluded:n}=It(r);if(i.length<this.config.minSamplesForOptimization){let R=n>0?` (${n} with an assigned reward excluded)`:"";return g(new Error(`Need at least ${this.config.minSamplesForOptimization} measured experiences for optimization${R}`))}let s=[...i].sort((R,E)=>eb(R)-eb(E)),a=Math.max(1,Math.floor(s.length*vk)),o=s.slice(0,-a),l=s.slice(-a),u=await this.optimizeParameters(t.parameters,o,e),d={name:`${t.name}-optimized`,parameters:u,expectedOutcome:this.predictOutcome(u,o)},m=await this.validateOptimization(t,d,l),p=this.calculateImprovement(this.scoreParameters(t.parameters,l,e),this.scoreParameters(u,l,e),e),h=m.length>0?m.filter(R=>R.passed).length/m.length:0,v=[];p===void 0&&v.push("improvement"),m.length===0&&v.push("confidence");let b={method:"held-out",trainingSamples:o.length,heldOutSamples:l.length,estimated:p===void 0?[]:["improvement"],...v.length>0?{unmeasured:v}:{}},C=this.inferDomainFromExperiences(i),S={id:w(),domain:C,objective:e,currentStrategy:t,optimizedStrategy:d,improvement:p??0,confidence:h,validationResults:m,evaluation:b};return await this.storeOptimizationResult(S),f(S)}catch(i){return g(y(i))}}async runABTest(t,e,r){try{let i=await this.collectStrategyMetrics(t,r.metric),n=await this.collectStrategyMetrics(e,r.metric),s=Math.max(1,r.minSamples);if(i.length<s||n.length<s){let h={winner:"inconclusive",evidenceStatus:"insufficient-evidence",unmeasured:[r.metric,"stdDev","pValue"],strategyAMetrics:{samples:i.length},strategyBMetrics:{samples:n.length},sampleSizeA:i.length,sampleSizeB:n.length};return await this.storeABTestResult(t,e,h),f(h)}let a=this.calculateMean(i),o=this.calculateMean(n),l=this.calculateStdDev(i),u=this.calculateStdDev(n),d=this.calculatePValue(i,n),m;d!==void 0&&d<1-r.confidenceLevel?m=a>o?"A":"B":m="inconclusive";let p={winner:m,strategyAMetrics:{[r.metric]:a,stdDev:l,samples:i.length},strategyBMetrics:{[r.metric]:o,stdDev:u,samples:n.length},...d===void 0?{unmeasured:["pValue"],pValueUnavailableReason:"zero-variance"}:{pValue:d},sampleSizeA:i.length,sampleSizeB:n.length};return await this.storeABTestResult(t,e,p),f(p)}catch(i){return g(y(i))}}async recommendStrategy(t){try{let e=await this.memory.search("learning:strategy:optimized:*",100,{namespace:"learning-optimization"}),r=[];for(let i of e){let n="learning-optimization:",s=i.startsWith(n)?i.slice(n.length):i,a=await this.memory.get(s,{namespace:"learning-optimization"});if(a&&t.tags.includes(a.domain)&&t.tags.includes(a.objective.metric)&&(!t.objective||t.tags.includes(t.objective.metric)&&a.objective.metric===t.objective.metric&&a.objective.direction===t.objective.direction)&&a.confidence>.6){let o=this.scoreContextMatch(a,t),l=a.improvement*a.confidence;r.push({strategy:a.optimizedStrategy,score:o*.4+l*.6})}}return r.length===0?f({name:"default-strategy",parameters:this.getDefaultParameters(t),expectedOutcome:{}}):(r.sort((i,n)=>n.score-i.score),f(r[0].strategy))}catch(e){return g(y(e))}}async evaluateStrategy(t,e){try{let{measured:r,assignedExcluded:i}=It(e);if(r.length===0)return f({strategy:t,metrics:{},strengths:[],weaknesses:[],improvementAreas:[],evidenceStatus:"insufficient-evidence",...i>0?{assignedRewardsExcluded:i}:{}});let n={},s=this.calculateSuccessRate(r),a=this.calculateAverageDuration(r),o=this.calculateAverageReward(r);n.success_rate=s,n.avg_duration_ms=a,n.avg_reward=o;let l=[];s>.8&&l.push("High success rate"),a<5e3&&l.push("Fast execution"),o>.7&&l.push("Consistently good rewards");let u=[];s<.5&&u.push("Low success rate needs investigation"),a>3e4&&u.push("Slow execution time"),o<.3&&u.push("Low reward values");let d=this.identifyImprovementAreas(t,n,r),m={strategy:t,metrics:n,strengths:l,weaknesses:u,improvementAreas:d};return await this.storeStrategyEvaluation(m),f(m)}catch(r){return g(y(r))}}async trackMetrics(t,e){try{let r={strategyId:t,metrics:e,timestamp:new Date,samples:1},i=`learning:metrics:history:${t}:${Date.now()}`;return await this.memory.set(i,r,{namespace:"learning-optimization",ttl:86400*30}),await this.updateAggregatedMetrics(t,e),f(void 0)}catch(r){return g(y(r))}}async getMetricsHistory(t,e=100){try{let r=await this.searchLearningKeys(`learning:metrics:history:${t}:*`,e),i=[];for(let n of r){let s=pe(await this.memory.get(n,fs),["timestamp"]);s&&i.push(s)}return i.sort((n,s)=>n.timestamp.getTime()-s.timestamp.getTime()),f(i)}catch(r){return g(y(r))}}async gridSearchOptimize(t,e,r){try{let i=this.generateParameterCombinations(t),n={},s=e.direction==="maximize"?-1/0:1/0;for(let a of i){let o=this.scoreParameters(a,r,e);(e.direction==="maximize"?o>s:o<s)&&(s=o,n=a)}return f(n)}catch(i){return g(y(i))}}async searchLearningKeys(t,e){let r=`${fs.namespace}:`;return(await this.memory.search(t,e,fs)).map(n=>n.startsWith(r)?n.slice(r.length):n)}async optimizeParameters(t,e,r){let i={...t};for(let[n,s]of Object.entries(t))if(ys(n)&&typeof s=="number"){let a=[-.1,-.05,0,.05,.1],o=0,l=this.scoreParameters(i,e,r);for(let u of a){let d={...i,[n]:s*(1+u)},m=this.scoreParameters(d,e,r);(r.direction==="maximize"?m>l:m<l)&&(l=m,o=u)}i[n]=s*(1+o)}return i}scoreParameters(t,e,r){let i=0,n=0;for(let s of e){let a=s.result.success?1:.5,o=this.calculateParamSimilarity(t,s.state.context),l=s.result.outcome[r.metric]??0;i+=o*l*a,n+=a}return n>0?i/n:0}calculateParamSimilarity(t,e){let r=0,i=0;for(let[n,s]of Object.entries(t))if(e[n]!==void 0)if(i++,typeof s=="number"&&typeof e[n]=="number"){let a=Math.abs(s-e[n]),o=Math.max(Math.abs(s),Math.abs(e[n]),1);r+=1-a/o}else s===e[n]&&r++;return i>0?r/i:.5}predictOutcome(t,e){let r={},i={},n={};for(let s of e)if(s.result.success)for(let[a,o]of Object.entries(s.result.outcome))ys(a)&&typeof o=="number"&&(i[a]=(i[a]||0)+o,n[a]=(n[a]||0)+1);for(let[s,a]of Object.entries(i))ys(s)&&(r[s]=a/n[s]);return r}async validateOptimization(t,e,r){let i=[],n=Object.entries(e.expectedOutcome);if(n.length===0)return i;for(let s of r){let a=n.filter(([l])=>typeof s.result.outcome[l]=="number");if(a.length===0)continue;let o=a.every(([l,u])=>{let d=s.result.outcome[l];return Math.abs(d-u)/Math.max(u,1)<bk});i.push({testId:s.id,passed:o,metrics:s.state.metrics})}return i}calculateImprovement(t,e,r){if(t===0)return;let i=e-t,n=r.direction==="maximize"?i/t:-i/t;return Math.max(-1,Math.min(1,n))}inferDomainFromExperiences(t){let e=new Map;for(let n of t)e.set(n.domain,(e.get(n.domain)||0)+1);let r="learning-optimization",i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}async collectStrategyMetrics(t,e){let r=await this.searchLearningKeys(`learning:metrics:history:${t.name}:*`,1e3),i=[];for(let n of r){let a=(await this.memory.get(n,fs))?.metrics[e];typeof a=="number"&&Number.isFinite(a)&&i.push(a)}return i}calculateMean(t){return t.length===0?0:t.reduce((e,r)=>e+r,0)/t.length}calculateStdDev(t){if(t.length===0)return 0;let e=this.calculateMean(t),r=t.map(i=>Math.pow(i-e,2));return Math.sqrt(r.reduce((i,n)=>i+n,0)/t.length)}calculatePValue(t,e){let r=this.calculateMean(t),i=this.calculateMean(e),n=Math.pow(this.calculateStdDev(t),2),s=Math.pow(this.calculateStdDev(e),2),a=t.length,o=e.length,l=Math.sqrt(n/a+s/o);if(l===0)return;let u=Math.abs(r-i)/l,d=2*(1-this.normalCDF(u));return Math.max(0,Math.min(1,d))}normalCDF(t){let e=.254829592,r=-.284496736,i=1.421413741,n=-1.453152027,s=1.061405429,a=.3275911,o=t<0?-1:1;t=Math.abs(t)/Math.sqrt(2);let l=1/(1+a*t),u=1-((((s*l+n)*l+i)*l+r)*l+e)*l*Math.exp(-t*t);return .5*(1+o*u)}scoreContextMatch(t,e){let r=0,i=0;return e.tags.some(n=>n===t.objective.metric)&&(r+=1),i+=1,e.tags.some(n=>n===t.domain)&&(r+=1),i+=1,i>0?r/i:.5}getDefaultParameters(t){let e={timeout:3e4,retryCount:3,concurrency:4};return t.framework&&(e.framework=t.framework),t.language&&(e.language=t.language),e}calculateSuccessRate(t){return t.length===0?0:t.filter(e=>e.result.success).length/t.length}calculateAverageDuration(t){return t.length===0?0:t.reduce((e,r)=>e+r.result.duration,0)/t.length}calculateAverageReward(t){return t.length===0?0:t.reduce((e,r)=>e+r.reward,0)/t.length}identifyImprovementAreas(t,e,r){let i=[];e.success_rate<.8&&i.push("Increase success rate by tuning parameters"),e.avg_duration_ms>1e4&&i.push("Optimize for faster execution"),e.avg_reward<.5&&i.push("Improve reward through better strategy selection");let n=t.parameters;return n.retryCount<2&&i.push("Consider increasing retry count for resilience"),n.concurrency>8&&i.push("High concurrency may cause resource contention"),i}generateParameterCombinations(t){let e=Object.keys(t);if(e.length===0)return[{}];let r=[];function i(n,s){if(n===e.length){r.push({...s});return}let a=e[n];if(!ys(a)){i(n+1,s);return}for(let o of t[a])s[a]=o,i(n+1,s)}return i(0,{}),r}async updateAggregatedMetrics(t,e){let r=`learning:metrics:aggregated:${t}`,n=(await this.memory.get(r,fs))?.metrics||{};for(let[s,a]of Object.entries(e))ys(s)&&(n[s]||(n[s]={sum:0,count:0}),n[s].sum+=a,n[s].count+=1);await this.memory.set(r,{metrics:n,updatedAt:new Date},{namespace:"learning-optimization",persist:!0})}async storeOptimizationResult(t){await this.memory.set(`learning:strategy:optimized:${t.id}`,t,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:strategy:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}async storeABTestResult(t,e,r){let i=w();await this.memory.set(`learning:abtest:${i}`,{testId:i,strategyA:t.name,strategyB:e.name,result:r,timestamp:new Date},{namespace:"learning-optimization",persist:!0})}async storeStrategyEvaluation(t){let e=w();await this.memory.set(`learning:evaluation:${e}`,{...t,evaluatedAt:new Date},{namespace:"learning-optimization",ttl:86400*7})}};function eb(c){let t=new Date(c.timestamp).getTime();return Number.isNaN(t)?0:t}k();hr();var Ck={metricsRetentionDays:90,anomalyThreshold:2.5,trendWindowSize:7,alertThresholds:{error_rate:.05,latency_p99:5e3,memory_usage:.9,cpu_usage:.8}},Gr=class{constructor(t,e={}){this.memory=t;this.config={...Ck,...e}}memory;config;async recordMetric(t,e,r,i,n=[]){try{let s={id:w(),name:t,value:e,unit:r,domain:i,tags:n,timestamp:new Date};return await this.memory.set(`production:metric:${s.id}`,s,{namespace:"learning-optimization",ttl:this.config.metricsRetentionDays*86400}),await this.indexMetric(s),await this.checkForAnomalies(s),f(s.id)}catch(s){return g(y(s))}}async recordMetricsBatch(t){try{let e=[];for(let r of t){let i=await this.recordMetric(r.name,r.value,r.unit,r.domain,r.tags);i.success&&e.push(i.value)}return f(e)}catch(e){return g(y(e))}}async getMetricsHistory(t,e,r){try{let i=r?`production:metric:index:${t}:${r}:*`:`production:metric:index:${t}:*`,n=await this.memory.search(i,1e3),s=[];for(let a of n){let o=await this.memory.get(a);if(o){let l=pe(await this.memory.get(`production:metric:${o}`),["timestamp"]);l&&e.contains(l.timestamp)&&s.push(l)}}return s.sort((a,o)=>a.timestamp.getTime()-o.timestamp.getTime()),f(s)}catch(i){return g(y(i))}}async recordIncident(t,e,r,i,n){try{let s={id:w(),severity:t,title:e,description:r,domain:i,metrics:n,startedAt:new Date};return await this.memory.set(`production:incident:${s.id}`,s,{namespace:"learning-optimization",persist:!0}),await this.indexIncident(s),await this.createExperienceFromIncident(s),f(s)}catch(s){return g(y(s))}}async resolveIncident(t,e,r){try{let i=pe(await this.memory.get(`production:incident:${t}`),["startedAt","resolvedAt"]);if(!i)return g(new Error(`Incident ${t} not found`));let n={...i,rootCause:e,resolution:r,resolvedAt:new Date};return await this.memory.set(`production:incident:${t}`,n,{namespace:"learning-optimization",persist:!0}),await this.updateExperienceWithResolution(n),f(n)}catch(i){return g(y(i))}}async getRecentIncidents(t=10,e){try{let r=e?`production:incident:index:domain:${e}:*`:"production:incident:*",i=await this.memory.search(r,t*2),n=[];for(let a of i)if(a.includes(":index:")){let o=await this.memory.get(a);if(o){let l=pe(await this.memory.get(`production:incident:${o}`),["startedAt","resolvedAt"]);l&&n.push(l)}}else{let o=pe(await this.memory.get(a),["startedAt","resolvedAt"]);o&&n.push(o)}n.sort((a,o)=>o.startedAt.getTime()-a.startedAt.getTime());let s=Array.from(new Map(n.map(a=>[a.id,a])).values());return f(s.slice(0,t))}catch(r){return g(y(r))}}async getProductionHealth(){try{let t=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","code-intelligence","security-compliance","learning-optimization"],e={},r={},i="healthy",n=0,s=0;for(let d of t){let m=await this.getDomainHealth(d);e[d]=m,m.status==="degraded"&&n++,m.status==="unhealthy"&&s++;for(let[p,h]of Object.entries(m.metrics))r[`${d}_${p}`]=h}s>0?i="unhealthy":n>t.length/3&&(i="degraded");let a=await this.calculateTrends(),o=await this.getRecentIncidents(5),l=o.success?o.value:[],u=this.generateHealthRecommendations(e,r,l);return f({overall:i,domains:e,metrics:r,trends:a,recentIncidents:l,recommendations:u})}catch(t){return g(y(t))}}async getDomainHealth(t){let e=Vt.lastNDays(1),r=await this.getMetricsHistory("*",e,t),i=Ve();if(r.success)for(let o of r.value)i[o.name],i[o.name]=o.value;let n=await this.getRecentIncidents(100,t),s=n.success?n.value.filter(o=>!o.resolvedAt).length:0,a="healthy";return s>2?a="unhealthy":s>0&&(a="degraded"),i.error_rate>this.config.alertThresholds.error_rate?a="unhealthy":i.latency_p99>this.config.alertThresholds.latency_p99&&(a="degraded"),{status:a,metrics:i,activeIncidents:s}}async calculateTrends(){let t=[],e=["error_rate","latency_p99","success_rate"],r=this.config.trendWindowSize;for(let i of e)for(let n=0;n<r;n++){let s=new Date;s.setDate(s.getDate()-n),s.setHours(0,0,0,0);let a=new Date(s);a.setHours(23,59,59,999);let o=Vt.create(s,a),l=await this.getMetricsHistory(i,o);if(l.success&&l.value.length>0){let u=l.value.reduce((d,m)=>d+m.value,0)/l.value.length;t.push({timestamp:s,metric:i,value:u})}}return t}generateHealthRecommendations(t,e,r){let i=[];for(let[a,o]of Object.entries(t))o.status==="unhealthy"?i.push(`Domain ${a} is unhealthy. Review active incidents and metrics.`):o.status==="degraded"&&i.push(`Domain ${a} is degraded. Monitor closely.`);for(let[a,o]of Object.entries(e)){let l=a.split("_").slice(-2).join("_"),u=this.config.alertThresholds[l];u&&o>u&&i.push(`Metric ${a} (${o.toFixed(2)}) exceeds threshold (${u})`)}let n=r.filter(a=>!a.resolvedAt);return n.length>3&&i.push(`${n.length} unresolved incidents require attention`),r.reduce((a,o)=>(a[o.severity]=(a[o.severity]||0)+1,a),{}).critical>2&&i.push("Multiple critical incidents detected. Consider system-wide review."),i.length===0&&i.push("All systems operating within normal parameters."),i}async extractInsights(t,e){try{let r=await this.getMetricsHistory("*",t,e),i=r.success?r.value:[],n=await this.getRecentIncidents(50,e),s=n.success?n.value:[],a=i.length,o=s.filter(p=>p.resolvedAt),l=s.length>0?o.length/s.length:1,u=this.calculateRewardFromIncidents(s),d=this.generateInsightRecommendations(i,s),m=this.detectMetricAnomalies(i);return f({experienceCount:a,successRate:l,avgReward:u,patterns:[],anomalies:m,recommendations:d})}catch(r){return g(y(r))}}async recordMilestone(t,e,r){try{let i={name:t,achievedAt:new Date,domain:e};return await this.memory.set(`production:milestone:${w()}`,{...i,metrics:r},{namespace:"learning-optimization",persist:!0}),f(i)}catch(i){return g(y(i))}}async getRecentMilestones(t=10){try{let e=await this.memory.search("production:milestone:*",t),r=[];for(let i of e){let n=pe(await this.memory.get(i),["achievedAt"]);n&&r.push(n)}return r.sort((i,n)=>n.achievedAt.getTime()-i.achievedAt.getTime()),f(r.slice(0,t))}catch(e){return g(y(e))}}async indexMetric(t){await this.memory.set(`production:metric:index:${t.name}:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",ttl:this.config.metricsRetentionDays*86400})}async indexIncident(t){await this.memory.set(`production:incident:index:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`production:incident:index:severity:${t.severity}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}async checkForAnomalies(t){let e=Vt.lastNDays(7),r=await this.getMetricsHistory(t.name,e,t.domain);if(!r.success||r.value.length<10)return;let i=r.value.map(o=>o.value),n=i.reduce((o,l)=>o+l,0)/i.length,s=Math.sqrt(i.reduce((o,l)=>o+Math.pow(l-n,2),0)/i.length),a=Math.abs(t.value-n)/(s||1);a>this.config.anomalyThreshold&&await this.memory.set(`production:anomaly:${w()}`,{metricId:t.id,metricName:t.name,value:t.value,mean:n,stdDev:s,deviation:a,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*7})}async createExperienceFromIncident(t){let e={context:{incidentId:t.id,severity:t.severity,domain:t.domain},metrics:t.metrics},r={success:!1,outcome:t.metrics,duration:0},i={id:w(),agentId:{value:"production-intel",domain:"learning-optimization",type:"analyzer"},domain:t.domain,action:`incident-${t.severity}`,state:e,result:r,reward:this.calculateIncidentReward(t),timestamp:t.startedAt};await this.memory.set(`learning:experience:${i.id}`,i,{namespace:"learning-optimization",ttl:86400*30})}async updateExperienceWithResolution(t){if(!t.resolvedAt)return;let e={context:{incidentId:t.id,rootCause:t.rootCause,resolution:t.resolution},metrics:t.metrics},r=t.resolvedAt.getTime()-t.startedAt.getTime(),i={success:!0,outcome:{...t.metrics,resolution_time_ms:r},duration:r},n={id:w(),agentId:{value:"production-intel",domain:"learning-optimization",type:"analyzer"},domain:t.domain,action:`resolution-${t.severity}`,state:e,result:i,reward:1-this.calculateIncidentReward(t),timestamp:t.resolvedAt};await this.memory.set(`learning:experience:${n.id}`,n,{namespace:"learning-optimization",ttl:86400*30})}calculateIncidentReward(t){return-({critical:.9,high:.7,medium:.4,low:.2}[t.severity]||.5)}calculateRewardFromIncidents(t){if(t.length===0)return .8;let e={critical:.1,high:.3,medium:.6,low:.8},r=0,i=0;for(let n of t){let s=e[n.severity]||.5,a=n.resolvedAt?.2:0;r+=s+a,i++}return i>0?r/i:.8}generateInsightRecommendations(t,e){let r=[],i=new Map;for(let n of t){let s=i.get(n.name)||[];s.push(n.value),i.set(n.name,s)}for(let[n,s]of i){let a=this.calculateTrendDirection(s);a==="increasing"&&n.includes("error")?r.push(`${n} is trending upward. Investigate root causes.`):a==="decreasing"&&n.includes("success")&&r.push(`${n} is declining. Review recent changes.`)}if(e.length>0){let n=new Map;for(let s of e)n.set(s.domain,(n.get(s.domain)||0)+1);for(let[s,a]of n)a>3&&r.push(`Domain ${s} has ${a} incidents. Consider preventive measures.`)}return r}detectMetricAnomalies(t){let e=[],r=new Map;for(let i of t){let n=r.get(i.name)||[];n.push(i),r.set(i.name,n)}for(let[i,n]of r){if(n.length<5)continue;let s=n.map(l=>l.value),a=s.reduce((l,u)=>l+u,0)/s.length,o=Math.sqrt(s.reduce((l,u)=>l+Math.pow(u-a,2),0)/s.length);for(let l of n){let u=Math.abs(l.value-a)/(o||1);u>this.config.anomalyThreshold&&e.push({experienceId:l.id,type:"outlier-reward",description:`${i} value ${l.value.toFixed(2)} is ${u.toFixed(1)} std deviations from mean`,deviation:u})}}return e}calculateTrendDirection(t){if(t.length<3)return"stable";let e=t.slice(0,Math.floor(t.length/2)),r=t.slice(Math.floor(t.length/2)),i=e.reduce((a,o)=>a+o,0)/e.length,s=(r.reduce((a,o)=>a+o,0)/r.length-i)/(i||1);return s>.1?"increasing":s<-.1?"decreasing":"stable"}};async function tb(c,t,e){await c.set(`learning:strategy:current:${t}`,e,{namespace:"learning-optimization",persist:!0})}function rb(c,t){let e=c.map(r=>r.result.outcome[t]??0).filter(r=>!isNaN(r));return e.length===0?0:e.reduce((r,i)=>r+i,0)/e.length}function ib(c){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":Ne.filter(e=>e!=="learning-optimization"),"enterprise-integration":["contract-testing","security-compliance","quality-assessment"],coordination:Ne.filter(e=>e!=="coordination")}[c]||[]}function nb(c){let t=[],e=new Set;for(let r of c){if(e.has(r.id))continue;let i=[r];e.add(r.id);for(let n of c)e.has(n.id)||r.type===n.type&&r.domain===n.domain&&Sk(r.context,n.context)&&(i.push(n),e.add(n.id));i.length>=2&&t.push(i)}return t}function Sk(c,t){return c.tags.some(e=>t.tags.includes(e))}function sb(c,t,e){let r=JSON.stringify({patternCount:c.length,knowledgeCount:t.length,strategyCount:e.length,patternIds:c.map(n=>n.id).sort(),knowledgeIds:t.map(n=>n.id).sort(),strategyIds:e.map(n=>n.id).sort()}),i=0;for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);i=(i<<5)-i+s,i=i&i}return Math.abs(i).toString(16)}_();var qi=x.create("learning-optimization/consensus");async function ab(c,t,e,r){let i=U({id:w(),type:"pattern-recommendation",confidence:t,description:`Verify pattern recommendation: ${c.name} (${c.type}) for domain ${c.domain}`,payload:c,detectedBy:"learning-optimization-coordinator",severity:t>.9?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(qi.info(`Pattern recommendation '${c.name}' verified by consensus`),!0):(qi.warn(`Pattern recommendation '${c.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function ob(c,t,e,r){let i=U({id:w(),type:"optimization-suggestion",confidence:t,description:`Verify optimization: ${c.metric} from ${c.currentValue} to ${c.targetValue} via ${c.strategy}`,payload:c,detectedBy:"learning-optimization-coordinator",severity:t>.85?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(qi.info(`Optimization suggestion for '${c.metric}' verified by consensus`),!0):(qi.warn(`Optimization suggestion for '${c.metric}' NOT verified`),!1)}return!0}async function cb(c,t,e,r){let i=U({id:w(),type:"cross-domain-insight",confidence:t,description:`Verify cross-domain insight: ${c.description}`,payload:c,detectedBy:"learning-optimization-coordinator",severity:"high"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(qi.info(`Cross-domain insight verified by consensus for ${c.targetDomains.length} target domains`),!0):(qi.warn(`Cross-domain insight NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}var Ek={maxConcurrentWorkflows:3,defaultTimeout:12e4,enableAutoOptimization:!0,publishEvents:!0,learningCycleIntervalMs:36e5,enableDreamScheduler:!0,dreamCycleIntervalMs:36e5,enableExperienceTrigger:!0,experienceThreshold:50,enableQualityGateFailureTrigger:!0,autoApplyHighConfidenceInsights:!1,autoApplyConfidenceThreshold:.8,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Be=x.create("learning-optimization"),xc=class extends ie{constructor(e,r,i,n={},s){let a={...Ek,...n};super(e,"learning-optimization",a,{verifyFindingTypes:["pattern-recommendation","optimization-suggestion","cross-domain-insight"]});this.memory=r;this.agentCoordinator=i;this.learningService=new zr({memory:r,llmRouter:s}),this.transferService=new Br(r),this.optimizerService=new qr(r),this.productionIntel=new Gr(r)}memory;agentCoordinator;learningService;transferService;optimizerService;productionIntel;sona=null;dreamScheduler=null;async onInitialize(){try{this.sona=await De({domain:"learning-optimization",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.5}),Be.info("PersistentSONAEngine initialized for pattern learning")}catch(e){Be.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),Be.warn("Continuing without SONA pattern persistence"),this.sona=null}if(this.config.enableDreamScheduler)try{let e=await Rs();await e.initialize(),this.dreamScheduler=Dm({dreamEngine:e,eventBus:this.eventBus,memoryBackend:this.memory},{autoScheduleIntervalMs:this.config.dreamCycleIntervalMs,enableExperienceTrigger:this.config.enableExperienceTrigger,experienceThreshold:this.config.experienceThreshold,enableQualityGateFailureTrigger:this.config.enableQualityGateFailureTrigger,autoApplyHighConfidenceInsights:this.config.autoApplyHighConfidenceInsights,insightConfidenceThreshold:this.config.autoApplyConfidenceThreshold}),await this.dreamScheduler.initialize(),this.dreamScheduler.start(),Be.info("DreamScheduler initialized and started")}catch{Be.warn("Failed to initialize DreamScheduler:")}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){if(await this.saveWorkflowState(),this.dreamScheduler){try{await this.dreamScheduler.dispose(),Be.info("DreamScheduler disposed")}catch(e){Be.error("Error disposing DreamScheduler:",e instanceof Error?e:void 0)}this.dreamScheduler=null}if(this.initialized&&this.sona)try{await this.sona.close()}catch(e){Be.error("Error closing SONA engine:",e instanceof Error?e:void 0)}}getActiveWorkflows(){return super.getActiveWorkflows()}async runLearningCycle(e){let r=w();try{if(this.startWorkflow(r,"learning-cycle"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Be.warn("Topology degraded, using conservative strategy for learning cycle"),this.minCutMixin.shouldPauseOperations())return g(new Error("Learning cycle paused: topology is in critical state"));let i=await this.spawnLearningAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),g(i.error);this.addAgentToWorkflow(r,i.value);let n=Vt.lastNDays(1),s=await this.getExperiencesForDomain(e,n),a=s.success?It(s.value).measured:[];this.updateWorkflowProgress(r,20);let o=await this.learningService.mineExperiences(e,n),l=o.success?o.value.patterns.length:0;this.updateWorkflowProgress(r,50);let u=0,d=[];if(a.length>=10){let h={metric:"success_rate",direction:"maximize",constraints:[]},v=await this.getCurrentStrategy(e),b=await this.optimizerService.optimizeStrategy(v,h,a);if(b.success){u=1;let C=b.value.optimizedStrategy.expectedOutcome[h.metric];typeof C=="number"&&d.push({metric:h.metric,before:this.calculateMetricValue(a,h.metric),after:C,percentChange:b.value.improvement*100,estimated:!0})}}this.updateWorkflowProgress(r,80);let m=0;o.success&&o.value.recommendations.length>0&&(await this.transferService.createKnowledge("heuristic",e,o.value.recommendations,{value:`learning-agent-${r.slice(0,8)}`,domain:"learning-optimization",type:"analyzer"},[e])).success&&(m=1),this.completeWorkflow(r),await this.agentCoordinator.stop(i.value);let p={domain:e,experiencesProcessed:a.length,patternsLearned:l,strategiesOptimized:u,knowledgeGenerated:m,improvements:d};return this.config.publishEvents&&l>0&&await this.publishPatternConsolidated(l,[e]),f(p)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async optimizeAllStrategies(){let e=w();try{if(this.startWorkflow(e,"optimization"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Be.warn("Topology degraded, using conservative optimization strategy"),this.minCutMixin.shouldPauseOperations())return g(new Error("Optimization paused: topology is in critical state"));let r={},i=0,n=0,s=0,a=Ne.filter(l=>l!=="learning-optimization");for(let l=0;l<a.length;l++){let u=a[l];this.updateWorkflowProgress(e,Math.round(l/a.length*100));let d=Vt.lastNDays(7),m=await this.getExperiencesForDomain(u,d);if(!m.success||m.value.length<10)continue;let p=m.value,h={metric:"success_rate",direction:"maximize",constraints:[]},v=await this.getCurrentStrategy(u),b=await this.optimizerService.optimizeStrategy(v,h,p);b.success&&(i++,n+=b.value.improvement,s++,r[u]={strategiesOptimized:1,avgImprovement:b.value.improvement,bestStrategy:b.value.optimizedStrategy},await this.storeStrategy(u,b.value.optimizedStrategy))}this.completeWorkflow(e);let o={domainsOptimized:s,totalStrategies:i,avgImprovement:i>0?n/i:0,improvementEstimated:!0,byDomain:r};return this.config.publishEvents&&i>0&&await this.publishOptimizationApplied(o),f(o)}catch(r){return this.failWorkflow(e,String(r)),g(y(r))}}async shareCrossDomainLearnings(){let e=w();try{if(this.startWorkflow(e,"transfer"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Be.warn("Topology degraded, limiting cross-domain transfer scope"),this.minCutMixin.shouldPauseOperations())return g(new Error("Cross-domain sharing paused: topology is in critical state"));let r=0,i=[],n=0,s=0,a=0,o=await this.transferService.queryKnowledge({minRelevance:.7,limit:100});if(!o.success)return this.failWorkflow(e,o.error.message),g(o.error);let l=o.value;for(let m of l){let p=this.getRelatedDomains(m.domain);for(let h of p){if(h===m.domain)continue;s++,(await this.transferService.transferKnowledge(m,h)).success&&(a++,r++,i.includes(h)||i.push(h))}this.updateWorkflowProgress(e,Math.round(r/(l.length*2)*100))}let u=await this.learningService.getPatternStats();if(u.success){let m=u.value.topPatterns;if(m.length>=2){let p=this.findSimilarPatterns(m);for(let h of p)h.length>=2&&(await this.learningService.consolidatePatterns(h.map(b=>b.id))).success&&n++}}this.completeWorkflow(e);let d={knowledgeShared:r,domainsUpdated:i,transferSuccessRate:s>0?a/s:null,newPatternsCreated:n};return this.config.publishEvents&&r>0&&await this.publishTransferCompleted(d),f(d)}catch(r){return this.failWorkflow(e,String(r)),g(y(r))}}async getLearningDashboard(){try{let e=await this.learningService.getPatternStats(),r=e.success?e.value:null,i=await this.transferService.queryKnowledge({limit:1e3}),n=i.success?i.value.length:0,s=Vt.lastNDays(1),a=0;for(let v of Ne){let b=await this.getExperiencesForDomain(v,s);b.success&&(a+=b.value.length)}let o=await this.productionIntel.getProductionHealth(),l=o.success?o.value.trends:[],u=await this.productionIntel.getRecentMilestones(5),d=u.success?u.value:[],m=r&&r.totalPatterns>0?r.avgSuccessRate*.6+r.avgConfidence*.4:null,p=[];if(r){let v=Object.entries(r.byDomain).filter(([b,C])=>C>0).map(([b,C])=>({domain:b,score:C})).sort((b,C)=>C.score-b.score);p.push(...v.slice(0,3).map(b=>b.domain))}let h={overallLearningRate:m,totalPatterns:r?.totalPatterns||0,totalKnowledge:n,experiencesLast24h:a,topPerformingDomains:p,learningTrend:l,recentMilestones:d};return f(h)}catch(e){return g(y(e))}}learnPattern(e,r,i,n,s,a){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.createPattern(e,r,i,n,s,a)}ensureInitialized(){if(!this.initialized)throw new Error("[LearningOptimizationCoordinator] Not initialized. Call initialize() first.")}ensureSONAAvailable(){if(!this.sona)throw new Error("[LearningOptimizationCoordinator] SONA engine is not available. Pattern persistence failed during initialization.")}async adaptPattern(e,r,i){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.adaptPattern(e,r,i)}getSONAStats(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getStats()}async getSONAPersistedStats(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPersistedStats()}getSONAPatterns(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getAllPatterns()}getSONAPatternsByType(e){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPatternsByType(e)}getSONAPatternsByDomain(e){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPatternsByDomain(e)}updateSONAPattern(e,r,i){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.updatePattern(e,r,i)}forceSONALearning(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.forceLearn()}isSONAAvailable(){return this.initialized&&this.sona!==null}exportSONAPatterns(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.exportPatterns()}importSONAPatterns(e){this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.importPatterns(e)}async verifySONAPerformance(e=100){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.verifyPerformance(e)}async triggerDreamCycle(e){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");let r=await this.dreamScheduler.triggerDream(e);return this.config.publishEvents&&await this.publishDreamCycleCompleted(r.cycle.id,r.cycle.durationMs??0,r.cycle.conceptsProcessed,r.insights.map(i=>({id:i.id,type:i.type,description:i.description,noveltyScore:i.noveltyScore,confidenceScore:i.confidenceScore,actionable:i.actionable,suggestedAction:i.suggestedAction,sourceConcepts:i.sourceConcepts})),r.patternsCreated),r}getDreamStatus(){return this.dreamScheduler?.getStatus()??null}isDreamSchedulerAvailable(){return this.dreamScheduler!==null}getLastDreamResult(){return this.dreamScheduler?.getLastDreamResult()??null}async triggerQuickDream(){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");return this.dreamScheduler.triggerQuickDream()}async triggerFullDream(){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");return this.dreamScheduler.triggerFullDream()}async exportModels(e){let r=w();try{this.startWorkflow(r,"export");let i=e||Ne,n=[],s=[],a=[],o=await Ec(this.memory,{retrieve:Oe});for(let p of o)i.includes(p.domain)&&n.push(p);this.updateWorkflowProgress(r,30);let l=await this.transferService.queryKnowledge({limit:Number.POSITIVE_INFINITY});if(l.success)for(let p of l.value)i.includes(p.domain)&&s.push(p);this.updateWorkflowProgress(r,60);let u=await wr(this.memory,"learning:strategy:optimized:*",{retrieve:Oe});for(let p of u){let h=await this.memory.get(p,Oe);h&&i.includes(h.domain)&&a.push(h)}this.updateWorkflowProgress(r,90);let d=this.calculateChecksum(n,s,a);return this.completeWorkflow(r),f({version:"1.0.0",exportedAt:new Date,patterns:n,knowledge:s,strategies:a,checksum:d})}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async importModels(e){let r=w();try{if(this.startWorkflow(r,"import"),this.calculateChecksum(e.patterns,e.knowledge,e.strategies)!==e.checksum)return this.failWorkflow(r,"Checksum mismatch"),g(new Error("Import failed: checksum mismatch"));let n=0,s=0,a=0,o=[];for(let u of e.patterns){let d=await this.memory.get(`learning:pattern:${u.id}`,{namespace:"learning-optimization"});d?d.confidence<u.confidence?(await this.memory.set(`learning:pattern:${u.id}`,u,{namespace:"learning-optimization",persist:!0}),n++,o.push({type:"pattern",id:u.id,reason:"Existing pattern had lower confidence",resolution:"overwrite"})):o.push({type:"pattern",id:u.id,reason:"Existing pattern has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:pattern:${u.id}`,u,{namespace:"learning-optimization",persist:!0}),n++),this.updateWorkflowProgress(r,Math.round(n/e.patterns.length*30))}for(let u of e.knowledge){let d=await this.memory.get(`learning:knowledge:shared:${u.id}`,Oe);d?u.version>d.version?(await this.memory.set(`learning:knowledge:shared:${u.id}`,u,{namespace:"learning-optimization",persist:!0}),s++,o.push({type:"knowledge",id:u.id,reason:"Import has newer version",resolution:"overwrite"})):o.push({type:"knowledge",id:u.id,reason:"Existing knowledge is same or newer version",resolution:"skip"}):(await this.memory.set(`learning:knowledge:shared:${u.id}`,u,{namespace:"learning-optimization",persist:!0}),s++),this.updateWorkflowProgress(r,30+Math.round(s/e.knowledge.length*30))}for(let u of e.strategies){let d=await this.memory.get(`learning:strategy:optimized:${u.id}`,Oe);d?u.confidence>d.confidence?(await this.memory.set(`learning:strategy:optimized:${u.id}`,u,{namespace:"learning-optimization",persist:!0}),a++,o.push({type:"strategy",id:u.id,reason:"Import has higher confidence",resolution:"overwrite"})):o.push({type:"strategy",id:u.id,reason:"Existing strategy has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:strategy:optimized:${u.id}`,u,{namespace:"learning-optimization",persist:!0}),a++),this.updateWorkflowProgress(r,60+Math.round(a/e.strategies.length*40))}return this.completeWorkflow(r),f({patternsImported:n,knowledgeImported:s,strategiesImported:a,conflicts:o,resolved:!0})}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}subscribeToEvents(){this.eventBus.subscribe("learning.ExperienceCaptured",this.handleExperienceCaptured.bind(this))}async handleExperienceCaptured(e){let{experience:r}=e.payload;if(!r.success||r.quality<.7)return;let i=r.domain||"learning-optimization";if(await this.learningService.recordExperience({agentId:{value:r.agent||"unknown",domain:i,type:"specialist"},domain:i,action:r.task,state:{context:{experienceId:r.id,trajectoryId:r.trajectoryId,model:r.model},metrics:{durationMs:r.durationMs,stepCount:r.steps.length,quality:r.quality}},result:{success:r.success,outcome:{quality:r.quality,patterns_extracted:r.patterns?.length||0},duration:r.durationMs},reward:r.quality}),r.patterns&&r.patterns.length>0&&r.domain){let n=this.getRelatedDomains(r.domain);for(let s of n)s!==r.domain&&await this.transferService.transferKnowledge({id:`exp-${r.id}`,domain:r.domain,type:"workflow",content:{format:"json",data:{task:r.task,steps:r.steps,quality:r.quality,patterns:r.patterns}},sourceAgentId:{value:r.agent||"experience-capture",domain:r.domain,type:"specialist"},targetDomains:[s],relevanceScore:r.quality,version:1,createdAt:new Date(r.startedAt)},s);Be.info(`[LearningOptimizationCoordinator] Experience ${r.id} transferred to ${n.length} related domains`)}this.dreamScheduler&&this.dreamScheduler.recordExperience({id:r.id,agentType:r.agent||"unknown",domain:i,taskType:r.task,success:r.success,duration:r.durationMs,context:{quality:r.quality,steps:r.steps.length,patterns:r.patterns?.length||0},timestamp:new Date(r.startedAt)})}async publishPatternConsolidated(e,r){let i={patternCount:e,domains:r,improvements:0},n=N(bt.PatternConsolidated,"learning-optimization",i);await this.eventBus.publish(n)}async publishTransferCompleted(e){let r={sourceProject:"current",targetProject:"current",patternsTransferred:e.knowledgeShared,successRate:e.transferSuccessRate??0},i=N(bt.TransferCompleted,"learning-optimization",r);await this.eventBus.publish(i)}async publishOptimizationApplied(e){let r=N(bt.OptimizationApplied,"learning-optimization",{domainsOptimized:e.domainsOptimized,avgImprovement:e.avgImprovement});await this.eventBus.publish(r)}async publishDreamCycleCompleted(e,r,i,n,s){if(!this.config.publishEvents)return;let a={cycleId:e,durationMs:r,conceptsProcessed:i,insights:n,patternsCreated:s},o=N(bt.DreamCycleCompleted,"learning-optimization",a);await this.eventBus.publish(o),Be.info(`[LearningOptimizationCoordinator] Published dream cycle completion: ${n.length} insights for ${i} concepts`)}async spawnLearningAgent(e,r){if(!this.agentCoordinator.canSpawn())return g(new Error("Agent limit reached"));let i={name:`learning-agent-${e.slice(0,8)}`,domain:"learning-optimization",type:"optimizer",capabilities:["pattern-learning","experience-mining",r],config:{workflowId:e,targetDomain:r}};return this.agentCoordinator.spawn(i)}async loadWorkflowState(){let e=await this.memory.get("learning-optimization:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("learning-optimization:coordinator:workflows",e,{namespace:"learning-optimization",persist:!0})}async getExperiencesForDomain(e,r){let i=await this.memory.search(`learning:experience:index:domain:${e}:*`,500),n=[];for(let s of i){let a=await this.memory.get(s);if(a){let o=pe(await this.memory.get(`learning:experience:${a}`),["timestamp"]);o&&r.contains(o.timestamp)&&n.push(o)}}return f(n)}async getCurrentStrategy(e){let r=`learning:strategy:current:${e}`,i=await this.memory.get(r);return i||{name:`default-${e}`,parameters:{timeout:3e4,retryCount:3,concurrency:4},expectedOutcome:{}}}async storeStrategy(e,r){await tb(this.memory,e,r)}calculateMetricValue(e,r){return rb(e,r)}getRelatedDomains(e){return ib(e)}findSimilarPatterns(e){return nb(e)}calculateChecksum(e,r,i){return sb(e,r,i)}async verifyPatternRecommendation(e,r){return ab(e,r,this.consensusMixin,this.domainName)}async verifyOptimizationSuggestion(e,r){return ob(e,r,this.consensusMixin,this.domainName)}async verifyCrossDomainInsight(e,r){return cb(e,r,this.consensusMixin,this.domainName)}};k();var om=class extends te{constructor(e,r,i,n={},s){super(e,r);this.agentCoordinator=i;this.llmRouter=s;this.pluginConfig=n}agentCoordinator;llmRouter;coordinator=null;learningService=null;transferService=null;optimizerService=null;productionIntel=null;pluginConfig;get name(){return"learning-optimization"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{isSONAAvailable:()=>this.coordinator?.isSONAAvailable()??!1,getSONAPersistedStats:async()=>this.coordinator?.isSONAAvailable()?this.coordinator.getSONAPersistedStats():null,runLearningCycle:this.runLearningCycle.bind(this),optimizeAllStrategies:this.optimizeAllStrategies.bind(this),shareCrossDomainLearnings:this.shareCrossDomainLearnings.bind(this),getLearningDashboard:this.getLearningDashboard.bind(this),exportModels:this.exportModels.bind(this),importModels:this.importModels.bind(this),learnPattern:this.learnPattern.bind(this),findMatchingPatterns:this.findMatchingPatterns.bind(this),applyPattern:this.applyPattern.bind(this),updatePatternFeedback:this.updatePatternFeedback.bind(this),getPatternStats:this.getPatternStats.bind(this),queryKnowledge:this.queryKnowledge.bind(this),transferKnowledge:this.transferKnowledge.bind(this),optimizeStrategy:this.optimizeStrategy.bind(this),runABTest:this.runABTest.bind(this),recommendStrategy:this.recommendStrategy.bind(this),evaluateStrategy:this.evaluateStrategy.bind(this),getCoordinator:()=>this.coordinator,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[],getLearningService:()=>this.learningService,getTransferService:()=>this.transferService,getOptimizerService:()=>this.optimizerService,getProductionIntelService:()=>this.productionIntel}}getTaskHandlers(){return new Map([["run-learning-cycle",async e=>{if(!this.coordinator)return g(new Error("Coordinator not initialized"));let r=e.domain;return r?this.coordinator.runLearningCycle(r):g(new Error("Invalid run-learning-cycle payload: missing domain"))}],["optimize-strategies",async e=>this.coordinator?this.coordinator.optimizeAllStrategies():g(new Error("Coordinator not initialized"))],["share-learnings",async e=>this.coordinator?this.coordinator.shareCrossDomainLearnings():g(new Error("Coordinator not initialized"))],["learn-pattern",async e=>{if(!this.learningService)return g(new Error("Learning service not initialized"));let r=e.experiences;return!r||r.length===0?g(new Error("Invalid learn-pattern payload: missing experiences")):this.learningService.learnPattern(r)}],["query-knowledge",async e=>{if(!this.transferService)return g(new Error("Transfer service not initialized"));let r=e.query;return r?this.transferService.queryKnowledge(r):g(new Error("Invalid query-knowledge payload: missing query"))}]])}async onInitialize(){this.learningService=new zr({memory:this.memory,llmRouter:this.llmRouter},this.pluginConfig.learningService),this.transferService=new Br(this.memory,this.pluginConfig.transferService),this.optimizerService=new qr(this.memory,this.pluginConfig.optimizerService),this.productionIntel=new Gr(this.memory,this.pluginConfig.productionIntel),this.coordinator=new xc(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.llmRouter),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.learningService=null,this.transferService=null,this.optimizerService=null,this.productionIntel=null}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestGenerated",this.handleTestGenerated.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("defect-intelligence.DefectPredicted",this.handleDefectPredicted.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"test-generation.TestGenerated":await this.handleTestGenerated(e);break;case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(e);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;default:break}}async runLearningCycle(e){this.ensureInitialized();try{let r=await this.coordinator.runLearningCycle(e);return r.success?this.trackSuccessfulOperation("learning-cycle"):this.trackFailedOperation("learning-cycle",r.error),r}catch(r){return this.handleError(r)}}async optimizeAllStrategies(){this.ensureInitialized();try{let e=await this.coordinator.optimizeAllStrategies();return e.success?this.trackSuccessfulOperation("optimization"):this.trackFailedOperation("optimization",e.error),e}catch(e){return this.handleError(e)}}async shareCrossDomainLearnings(){this.ensureInitialized();try{return await this.coordinator.shareCrossDomainLearnings()}catch(e){return this.handleError(e)}}async getLearningDashboard(){this.ensureInitialized();try{return await this.coordinator.getLearningDashboard()}catch(e){return this.handleError(e)}}async exportModels(e){this.ensureInitialized();try{return await this.coordinator.exportModels(e)}catch(r){return this.handleError(r)}}async importModels(e){this.ensureInitialized();try{return await this.coordinator.importModels(e)}catch(r){return this.handleError(r)}}async learnPattern(e){this.ensureInitialized();try{return await this.learningService.learnPattern(e)}catch(r){return this.handleError(r)}}async findMatchingPatterns(e,r){this.ensureInitialized();try{return await this.learningService.findMatchingPatterns(e,r)}catch(i){return this.handleError(i)}}async applyPattern(e,r){this.ensureInitialized();try{return await this.learningService.applyPattern(e,r)}catch(i){return this.handleError(i)}}async updatePatternFeedback(e,r){this.ensureInitialized();try{return await this.learningService.updatePatternFeedback(e,r)}catch(i){return this.handleError(i)}}async getPatternStats(e){this.ensureInitialized();try{return await this.learningService.getPatternStats(e)}catch(r){return this.handleError(r)}}async queryKnowledge(e){this.ensureInitialized();try{return await this.transferService.queryKnowledge(e)}catch(r){return this.handleError(r)}}async transferKnowledge(e,r){this.ensureInitialized();try{return await this.transferService.transferKnowledge(e,r)}catch(i){return this.handleError(i)}}async optimizeStrategy(e,r,i){this.ensureInitialized();try{return await this.optimizerService.optimizeStrategy(e,r,i)}catch(n){return this.handleError(n)}}async runABTest(e,r,i){this.ensureInitialized();try{return await this.optimizerService.runABTest(e,r,i)}catch(n){return this.handleError(n)}}async recommendStrategy(e){this.ensureInitialized();try{return await this.optimizerService.recommendStrategy(e)}catch(r){return this.handleError(r)}}async evaluateStrategy(e,r){this.ensureInitialized();try{return await this.optimizerService.evaluateStrategy(e,r)}catch(i){return this.handleError(i)}}async handleTestGenerated(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"test-generation",domain:"test-generation",type:"generator"},domain:"test-generation",action:"test-generated",state:{context:{testId:r.testId,testType:r.testType},metrics:{}},result:{success:!0,outcome:{generated:1},duration:0},reward:.8,rewardSource:"assigned",appliedPatternIds:r.patternsUsed})}async handleTestRunCompleted(e){let r=e.payload,i=r.passed+r.failed>0?r.passed/(r.passed+r.failed):0;await this.learningService.recordExperience({agentId:{value:"test-execution",domain:"test-execution",type:"tester"},domain:"test-execution",action:"test-run",state:{context:{runId:r.runId},metrics:{passed:r.passed,failed:r.failed,duration:r.duration}},result:{success:i>.8,outcome:{success_rate:i,passed:r.passed,failed:r.failed},duration:r.duration},reward:i,rewardSource:"measured"}),await this.productionIntel.recordMetric("test_success_rate",i,"ratio","test-execution",["automated"])}async handleCoverageGap(e){if(!He(e.payload))return;let r=e.payload;await this.learningService.recordExperience({agentId:{value:"coverage-analysis",domain:"coverage-analysis",type:"analyzer"},domain:"coverage-analysis",action:"gap-detection",state:{context:{gapId:r.gapId,file:r.file},metrics:{riskScore:r.riskScore}},result:{success:!0,outcome:{risk_score:r.riskScore},duration:0},reward:1-r.riskScore,rewardSource:"assigned"})}async handleQualityGate(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"quality-assessment",domain:"quality-assessment",type:"validator"},domain:"quality-assessment",action:"gate-evaluation",state:{context:{gateId:r.gateId},metrics:{passed:r.passed?1:0}},result:{success:r.passed,outcome:{gate_passed:r.passed?1:0},duration:0},reward:r.passed?1:0,rewardSource:"measured"})}async handleDefectPredicted(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"defect-intelligence",domain:"defect-intelligence",type:"analyzer"},domain:"defect-intelligence",action:"defect-prediction",state:{context:{predictionId:r.predictionId},metrics:{probability:r.probability}},result:{success:!0,outcome:{probability:r.probability},duration:0},reward:.7,rewardSource:"assigned"})}async handleImpactAnalysis(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"code-intelligence",domain:"code-intelligence",type:"analyzer"},domain:"code-intelligence",action:"impact-analysis",state:{context:{analysisId:r.analysisId},metrics:{changedFiles:r.changedFiles.length,impactedFiles:r.impactedFiles.length}},result:{success:!0,outcome:{changed_count:r.changedFiles.length,impacted_count:r.impactedFiles.length},duration:0},reward:.8,rewardSource:"assigned"})}ensureInitialized(){if(!this._initialized)throw new Error("LearningOptimizationPlugin is not initialized");if(!this.coordinator||!this.learningService||!this.transferService||!this.optimizerService||!this.productionIntel)throw new Error("LearningOptimizationPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),g(r)}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,failed:i.agents.failed+1},errors:[...i.errors.slice(-9),r.message]})}};function lb(c,t,e,r,i){return new om(c,t,e,r,i)}var cm=class extends te{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;workflowOrchestrator=null;pluginConfig;get name(){return"coordination"}get version(){return"1.0.0"}get dependencies(){return Ne.filter(e=>e!=="coordination")}getAPI(){return{listWorkflows:async()=>{if(!this.workflowOrchestrator)throw new Error("Workflow orchestrator not initialized");return this.workflowOrchestrator.listWorkflows()}}}async onInitialize(){this.workflowOrchestrator=Ym(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.workflowConfig),await this.workflowOrchestrator.initialize(),this.updateHealth({status:"healthy",agents:{total:0,active:0,idle:0,failed:0}})}async onDispose(){this.workflowOrchestrator&&(await this.workflowOrchestrator.dispose(),this.workflowOrchestrator=null)}async onEvent(e){e.type.startsWith("coordination.")&&await this.handleCoordinationEvent(e)}subscribeToEvents(){this.eventBus.subscribe("coordination.workflow.execute",async e=>{await this.handleEvent(e)})}async handleCoordinationEvent(e){e.type.split(".")[1]==="workflow"&&await this.handleWorkflowEvent(e)}async handleWorkflowEvent(e){this.workflowOrchestrator}};function ub(c,t,e,r){return new cm(c,t,e,r)}var qe={CoverageAnalyzerService:"coverage-analysis.CoverageAnalyzerService",SecurityScannerService:"security-compliance.SecurityScannerService",isSemgrepAvailable:"security-compliance.isSemgrepAvailable",runSemgrepWithRules:"security-compliance.runSemgrepWithRules",convertSemgrepFindings:"security-compliance.convertSemgrepFindings",createTestGeneratorService:"test-generation.createTestGeneratorService",KnowledgeGraphService:"code-intelligence.KnowledgeGraphService",QualityAnalyzerService:"quality-assessment.QualityAnalyzerService"},lm=class{factories=new Map;register(t,e){this.factories.set(t,e)}resolve(t){let e=this.factories.get(t);if(!e)throw new Error(`DomainServiceRegistry: service '${t}' not registered. Ensure the domain module is initialized before coordination.`);return e}has(t){return this.factories.has(t)}clear(){this.factories.clear()}keys(){return Array.from(this.factories.keys())}},Ge=new lm;Ge.register(qe.createTestGeneratorService,(c,t)=>t?Sr({memory:c,llmRouter:t}):gl(c));Ge.register(qe.CoverageAnalyzerService,c=>new Xt(c));Ge.register(qe.SecurityScannerService,c=>new dt(c));Ge.register(qe.isSemgrepAvailable,rs);Ge.register(qe.runSemgrepWithRules,ko);Ge.register(qe.convertSemgrepFindings,Do);Ge.register(qe.KnowledgeGraphService,c=>new _t(c));k();Ge.register(qe.QualityAnalyzerService,c=>new Pt(c));k();_();k();var jr={SoapOperationTested:"enterprise-integration.SoapOperationTested",MessageFlowTested:"enterprise-integration.MessageFlowTested",BapiTested:"enterprise-integration.BapiTested",IDocValidated:"enterprise-integration.IDocValidated",ODataTested:"enterprise-integration.ODataTested",SodAnalyzed:"enterprise-integration.SodAnalyzed",MiddlewareFlowTested:"enterprise-integration.MiddlewareFlowTested",IntegrationValidationFailed:"enterprise-integration.IntegrationValidationFailed"},kk={maxConcurrentWorkflows:8,defaultTimeout:12e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Pc=x.create("enterprise-integration"),kc=class extends ie{constructor(e,r,i,n={}){let s={...kk,...n};super(e,"enterprise-integration",s,{verifyFindingTypes:["soap-fault","message-ordering-violation","rfc-compatibility-break","idoc-validation-failure","odata-contract-break","sod-conflict"],modelTimeout:12e4});this.memory=r;this.agentCoordinator=i}memory;agentCoordinator;async onInitialize(){this.subscribeToEvents(),Pc.info("Enterprise Integration Coordinator initialized")}async onDispose(){}subscribeToEvents(){this.eventBus.subscribe("contract-testing.ContractVerified",this.handleContractVerified.bind(this)),this.eventBus.subscribe("chaos-resilience.FaultInjected",this.handleFaultInjected.bind(this))}getActiveWorkflows(){return super.getActiveWorkflows()}async validateWsdl(e){let r=w();try{if(this.startWorkflow(r,"soap"),this.minCutMixin.shouldPauseOperations())return g(new Error("WSDL validation paused: topology is in critical state"));let i=await this.spawnAgent(r,"qe-soap-tester",{task:"validate-wsdl",url:e});if(!i.success)return this.failWorkflow(r,i.error.message),i;let n={url:e,version:"1.1",services:[],schemas:[]};return await this.memory.set(`enterprise-integration:wsdl:${encodeURIComponent(e)}`,n,{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(r),f(n)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async testSoapOperation(e,r,i){let n=w();try{this.startWorkflow(n,"soap");let s=await this.spawnAgent(n,"qe-soap-tester",{task:"test-operation",wsdl:e,operation:r,input:i});if(!s.success)return this.failWorkflow(n,s.error.message),g(s.error);let a={operation:r,passed:!0,request:JSON.stringify(i),response:"",validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(N(jr.SoapOperationTested,this.domainName,{operation:r,wsdlUrl:e.url,passed:a.passed,errors:a.validationErrors.length})),this.completeWorkflow(n),f(a)}catch(s){return this.failWorkflow(n,String(s)),g(y(s))}}async testMessageFlow(e,r){let i=w();try{this.startWorkflow(i,"messaging");let n=await this.spawnAgent(i,"qe-message-broker-tester",{task:"test-message-flow",brokerConfig:e,testCase:r});if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);let s={testCaseId:r.id,passed:!0,sentAt:new Date,receivedAt:new Date,latency:0,actualOutcome:r.expectedOutcome,errors:[]};return this.config.publishEvents&&await this.eventBus.publish(N(jr.MessageFlowTested,this.domainName,{protocol:e.protocol,queue:r.queue,passed:s.passed,latency:s.latency})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async testDlqHandling(e,r){let i=w();try{this.startWorkflow(i,"messaging");let n=await this.spawnAgent(i,"qe-message-broker-tester",{task:"test-dlq",brokerConfig:e,queue:r});if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);let s={queue:r,messageCount:0,poisonMessages:0,reprocessable:0,errors:[]};return this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async testBapiCall(e,r){let i=w();try{if(this.startWorkflow(i,"rfc"),this.minCutMixin.shouldPauseOperations())return g(new Error("BAPI testing paused: topology is in critical state"));let n=await this.spawnAgent(i,"qe-sap-rfc-tester",{task:"test-bapi",connection:e,bapi:r});if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);let s={bapiName:r.name,passed:!0,returnMessages:[],exportValues:{},tableData:{},duration:0,transactionCommitted:!1};return this.config.publishEvents&&await this.eventBus.publish(N(jr.BapiTested,this.domainName,{bapiName:r.name,passed:s.passed,returnType:s.returnMessages.length>0?s.returnMessages[0].type:"S"})),await this.memory.set(`enterprise-integration:bapi:${r.name}:${Date.now()}`,{bapiName:r.name,importParams:Object.keys(r.importParams),passed:s.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async validateIdoc(e,r){let i=w();try{this.startWorkflow(i,"idoc");let n=await this.spawnAgent(i,"qe-sap-idoc-tester",{task:"validate-idoc",definition:e,content:r});if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);let s={idocType:e.type,direction:"inbound",passed:!0,statusCode:3,statusMessage:"IDoc validated successfully",segmentValidation:[],processingTime:0};return this.config.publishEvents&&await this.eventBus.publish(N(jr.IDocValidated,this.domainName,{idocType:e.type,direction:s.direction,passed:s.passed,statusCode:s.statusCode})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async validateODataMetadata(e){let r=w();try{this.startWorkflow(r,"odata");let i=await this.spawnAgent(r,"qe-odata-contract-tester",{task:"validate-metadata",serviceUrl:e});if(!i.success)return this.failWorkflow(r,i.error.message),g(i.error);let n={version:"v4",serviceUrl:e,entitySets:[],functionImports:[],actions:[]};return await this.memory.set(`enterprise-integration:odata:${encodeURIComponent(e)}`,n,{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(r),f(n)}catch(i){return this.failWorkflow(r,String(i)),g(y(i))}}async testODataEntitySet(e,r){let i=w();try{this.startWorkflow(i,"odata");let n=await this.spawnAgent(i,"qe-odata-contract-tester",{task:"test-entity-set",metadata:e,entitySet:r});if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);let s={entitySet:r,operation:"CRUD",passed:!0,statusCode:200,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(N(jr.ODataTested,this.domainName,{entitySet:r,operation:s.operation,passed:s.passed,version:e.version})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async validateMessageFlow(e,r){let i=w();try{this.startWorkflow(i,"middleware");let n=await this.spawnAgent(i,"qe-middleware-validator",{task:"validate-flow",flow:e,input:r});if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);let s={flowName:e.name,passed:!0,routingCorrect:!0,transformationCorrect:!0,errorHandlingCorrect:!0,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(N(jr.MiddlewareFlowTested,this.domainName,{flowName:e.name,passed:s.passed,routingCorrect:s.routingCorrect,transformationCorrect:s.transformationCorrect})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async validateTransformation(e,r,i){let n=w();try{this.startWorkflow(n,"middleware");let s=await this.spawnAgent(n,"qe-middleware-validator",{task:"validate-transformation",spec:e,input:r,expectedOutput:i});return s.success?(this.completeWorkflow(n),f(!0)):(this.failWorkflow(n,s.error.message),g(s.error))}catch(s){return this.failWorkflow(n,String(s)),g(y(s))}}async analyzeSod(e,r){let i=w();try{this.startWorkflow(i,"sod");let n=await this.spawnAgent(i,"qe-sod-analyzer",{task:"analyze-sod",userId:e,ruleset:r});if(!n.success)return this.failWorkflow(i,n.error.message),g(n.error);let s={userId:e,conflicts:[],riskScore:0,compliant:!0,recommendations:[]};return this.config.publishEvents&&await this.eventBus.publish(N(jr.SodAnalyzed,this.domainName,{userId:e,conflicts:s.conflicts.length,compliant:s.compliant,riskScore:s.riskScore})),await this.memory.set(`enterprise-integration:sod:${e}:${Date.now()}`,{userId:e,ruleset:r.name,conflicts:s.conflicts.length,compliant:s.compliant,riskScore:s.riskScore,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),g(y(n))}}async spawnAgent(e,r,i){let n={name:`${r}-${e.slice(0,8)}`,domain:"enterprise-integration",type:r,capabilities:[r],config:{workflowId:e,...i}},s=await this.agentCoordinator.spawn(n);return s.success&&this.addAgentToWorkflow(e,s.value),s}async verifyCriticalFinding(e,r){let i=U({id:w(),type:e.type,confidence:r,description:e.description,payload:e.payload,detectedBy:"enterprise-integration-coordinator",severity:r>.9?"critical":"high"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Pc.info(`Finding verified by consensus: ${e.type}`),!0):(Pc.warn(`Finding NOT verified: ${e.type}`),!1)}return!0}async handleContractVerified(e){let r=e.payload;(r?.contractType==="soap"||r?.contractType==="odata")&&await this.memory.set(`enterprise-integration:contract-event:${Date.now()}`,{contractId:r.contractId,type:r.contractType,passed:r.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleFaultInjected(e){let r=e.payload;(r?.targetService?.includes("middleware")||r?.targetService?.includes("esb"))&&Pc.info(`Middleware fault injection detected: ${r.targetService}`)}};var um=class extends te{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;pluginConfig;get name(){return"enterprise-integration"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{validateWsdl:this.validateWsdl.bind(this),testSoapOperation:this.testSoapOperation.bind(this),testMessageFlow:this.testMessageFlow.bind(this),testDlqHandling:this.testDlqHandling.bind(this),testBapiCall:this.testBapiCall.bind(this),validateIdoc:this.validateIdoc.bind(this),validateODataMetadata:this.validateODataMetadata.bind(this),testODataEntitySet:this.testODataEntitySet.bind(this),validateMessageFlow:this.validateMessageFlow.bind(this),validateTransformation:this.validateTransformation.bind(this),analyzeSod:this.analyzeSod.bind(this),getCoordinator:()=>this.coordinator,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[]}}getTaskHandlers(){return new Map([["enterprise-integration:soap-test",async e=>{if(!this.coordinator)return g(new Error("Enterprise integration coordinator not initialized"));let r=e.wsdl,i=e.operation,n=e.input;return e.url&&!r?this.coordinator.validateWsdl(e.url):!r||!i?g(new Error("Invalid soap-test payload: missing wsdl or operation")):this.coordinator.testSoapOperation(r,i,n)}],["enterprise-integration:message-broker-test",async e=>{if(!this.coordinator)return g(new Error("Enterprise integration coordinator not initialized"));let r=e.brokerConfig,i=e.testCase,n=e.queue;return r?n&&!i?this.coordinator.testDlqHandling(r,n):i?this.coordinator.testMessageFlow(r,i):g(new Error("Invalid message-broker-test payload: missing testCase")):g(new Error("Invalid message-broker-test payload: missing brokerConfig"))}],["enterprise-integration:sap-rfc-test",async e=>{if(!this.coordinator)return g(new Error("Enterprise integration coordinator not initialized"));let r=e.connection,i=e.bapi;return!r||!i?g(new Error("Invalid sap-rfc-test payload: missing connection or bapi")):this.coordinator.testBapiCall(r,i)}],["enterprise-integration:sap-idoc-validate",async e=>{if(!this.coordinator)return g(new Error("Enterprise integration coordinator not initialized"));let r=e.definition,i=e.content;return!r||!i?g(new Error("Invalid sap-idoc-validate payload: missing definition or content")):this.coordinator.validateIdoc(r,i)}],["enterprise-integration:odata-test",async e=>{if(!this.coordinator)return g(new Error("Enterprise integration coordinator not initialized"));let r=e.serviceUrl,i=e.metadata,n=e.entitySet;return r&&!i?this.coordinator.validateODataMetadata(r):!i||!n?g(new Error("Invalid odata-test payload: missing metadata or entitySet")):this.coordinator.testODataEntitySet(i,n)}],["enterprise-integration:esb-flow-test",async e=>{if(!this.coordinator)return g(new Error("Enterprise integration coordinator not initialized"));let r=e.flow,i=e.input,n=e.spec;if(n){let s=e.transformInput,a=e.expectedOutput;return!s||!a?g(new Error("Invalid esb-flow-test payload: missing transformInput or expectedOutput for transformation")):this.coordinator.validateTransformation(n,s,a)}return!r||!i?g(new Error("Invalid esb-flow-test payload: missing flow or input")):this.coordinator.validateMessageFlow(r,i)}],["enterprise-integration:sod-analyze",async e=>{if(!this.coordinator)return g(new Error("Enterprise integration coordinator not initialized"));let r=e.userId,i=e.ruleset;return!r||!i?g(new Error("Invalid sod-analyze payload: missing userId or ruleset")):this.coordinator.analyzeSod(r,i)}]])}async onInitialize(){this.coordinator=new kc(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null}subscribeToEvents(){this.eventBus.subscribe("contract-testing.ContractVerified",this.handleContractVerified.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("chaos-resilience.FaultInjected",this.handleFaultInjected.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"contract-testing.ContractVerified":await this.handleContractVerified(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGate(e);break;case"chaos-resilience.FaultInjected":await this.handleFaultInjected(e);break;default:break}}async validateWsdl(e){this.ensureInitialized();try{let r=await this.coordinator.validateWsdl(e);return r.success?this.trackSuccessfulOperation("validateWsdl"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async testSoapOperation(e,r,i){this.ensureInitialized();try{let n=await this.coordinator.testSoapOperation(e,r,i);return n.success?this.trackSuccessfulOperation("testSoapOperation"):this.trackFailedOperation(new Error(n.error.message)),n}catch(n){return this.handleError(n)}}async testMessageFlow(e,r){this.ensureInitialized();try{let i=await this.coordinator.testMessageFlow(e,r);return i.success?this.trackSuccessfulOperation("testMessageFlow"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async testDlqHandling(e,r){this.ensureInitialized();try{let i=await this.coordinator.testDlqHandling(e,r);return i.success?this.trackSuccessfulOperation("testDlqHandling"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async testBapiCall(e,r){this.ensureInitialized();try{let i=await this.coordinator.testBapiCall(e,r);return i.success?this.trackSuccessfulOperation("testBapiCall"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateIdoc(e,r){this.ensureInitialized();try{let i=await this.coordinator.validateIdoc(e,r);return i.success?this.trackSuccessfulOperation("validateIdoc"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateODataMetadata(e){this.ensureInitialized();try{let r=await this.coordinator.validateODataMetadata(e);return r.success?this.trackSuccessfulOperation("validateODataMetadata"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async testODataEntitySet(e,r){this.ensureInitialized();try{let i=await this.coordinator.testODataEntitySet(e,r);return i.success?this.trackSuccessfulOperation("testODataEntitySet"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateMessageFlow(e,r){this.ensureInitialized();try{let i=await this.coordinator.validateMessageFlow(e,r);return i.success?this.trackSuccessfulOperation("validateMessageFlow"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateTransformation(e,r,i){this.ensureInitialized();try{let n=await this.coordinator.validateTransformation(e,r,i);return n.success?this.trackSuccessfulOperation("validateTransformation"):this.trackFailedOperation(new Error(n.error.message)),n}catch(n){return this.handleError(n)}}async analyzeSod(e,r){this.ensureInitialized();try{let i=await this.coordinator.analyzeSod(e,r);return i.success?this.trackSuccessfulOperation("analyzeSod"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async handleContractVerified(e){let r=e.payload;(r.contractType==="soap"||r.contractType==="odata")&&await this.memory.set(`enterprise-integration:contract-verified:${r.contractId}`,{contractId:r.contractId,type:r.contractType,passed:r.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleQualityGate(e){let r=e.payload;r.checks.find(n=>n.name==="enterprise-integration")||await this.memory.set(`enterprise-integration:quality-gate-warning:${r.gateId}`,{warning:"Enterprise integration testing not included in quality gate",timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleFaultInjected(e){let r=e.payload;(r.targetService?.includes("middleware")||r.targetService?.includes("esb")||r.targetService?.includes("broker")||r.targetService?.includes("mq"))&&await this.memory.set(`enterprise-integration:fault-correlation:${r.faultId||Date.now()}`,{targetService:r.targetService,faultType:r.faultType,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:3600})}ensureInitialized(){if(!this._initialized)throw new Error("EnterpriseIntegrationPlugin is not initialized");if(!this.coordinator)throw new Error("EnterpriseIntegrationPlugin coordinator is not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function mb(c,t,e,r){return new um(c,t,e,r)}var gb={"test-generation":(c,t,e,r)=>Kl(c,t,e,void 0,r),"test-execution":(c,t,e,r)=>yg(c,t,r),"coverage-analysis":(c,t,e,r)=>xu(c,t,r),"quality-assessment":(c,t,e,r)=>_u(c,t,e,void 0,r),"defect-intelligence":(c,t,e,r)=>ch(c,t,e,void 0,r),"requirements-validation":(c,t,e,r)=>ph(c,t,e,void 0,r),"code-intelligence":(c,t,e,r)=>nd(c,t,e,void 0,r),"security-compliance":(c,t,e,r)=>Yd(c,t,e,void 0,r),"contract-testing":(c,t,e,r)=>kv(c,t,e,void 0,r),"visual-accessibility":(c,t,e,r)=>jv(c,t,e,void 0,r),"chaos-resilience":(c,t,e,r)=>Uv(c,t,e,void 0,r),"learning-optimization":(c,t,e,r)=>lb(c,t,e,void 0,r),"enterprise-integration":(c,t,e,r)=>mb(c,t,e),coordination:(c,t,e,r)=>ub(c,t,e)},Dk={maxConcurrentAgents:Hi.MAX_CONCURRENT_AGENTS,memoryBackend:"hybrid",hnswEnabled:!0,lazyLoading:!0,enabledDomains:[...Ne],dataDir:void 0,enableExperienceBridge:!0,enableDreamScheduler:!0},dm=class{_eventBus;_coordinator;_plugins;_memory;_config;_startTime;_initialized=!1;_loopTracker;_experienceBridge;_dreamScheduler;_llmRouter;_llmRouterBuild;constructor(t={}){this._config={...Dk,...t},this._startTime=new Date,this._memory=new Oc,this._eventBus=new Bs,this._coordinator=new qs(this._config.maxConcurrentAgents),this._plugins=new sn(this._eventBus,this._memory,this._config.lazyLoading),this._loopTracker=new Gs}get eventBus(){return this._eventBus}get coordinator(){return this._coordinator}get plugins(){return this._plugins}get memory(){return this._memory}get llmRouter(){return this._llmRouter}async initialize(){if(this._initialized)return;let t=Ce(),e=this._config.dataDir||Gi.join(t,".agentic-qe");if(this._config.memoryBackend!=="memory"&&!Dc.existsSync(e)&&Dc.mkdirSync(e,{recursive:!0}),this._config.memoryBackend==="memory"){let i=Gi.join(mm("os").tmpdir(),`aqe-test-${Date.now()}-${pb().slice(0,12)}.db`);await Rm({dbPath:i})}else this._memory=pm(e),this._plugins=new sn(this._eventBus,this._memory,this._config.lazyLoading);await this._initializeLLMRouter(t);for(let i of this._config.enabledDomains){let n=gb[i];n&&this._plugins.registerFactory(i,async(s,a)=>Promise.resolve(n(s,a,this._coordinator,this._llmRouter)))}await this._memory.initialize();let r=new Hs({agentId:"qe-kernel"});this._eventBus.registerMiddleware(r);try{let i=Gi.join(e,"plugins"),n=new Tm({cacheDir:i}),a=new Em({cache:n}).resolveLoadOrder();for(let o of a.errors)console.warn(`[QEKernel] External plugin ${o.plugin}: ${o.code}: ${o.message}`);for(let o of a.ordered){let l=o.manifest,u=n.get(l.name,l.version);if(!u)continue;let d=Gi.join(u.path,l.entryPoint);for(let m of l.domains){let p=m;if(gb[p])continue;this._plugins.registerFactory(p,async(v,b)=>{let C=await import(d),S=C.default??C.createPlugin;if(typeof S!="function")throw new Error(`Plugin "${l.name}" entry point must export a default function or "createPlugin" function`);return S(v,b,this._coordinator,this._llmRouter)})}}}catch(i){console.warn("[QEKernel] External plugin discovery failed:",i)}this._config.lazyLoading||await this._plugins.loadAll();try{let{isAgentMemoryBranchingEnabled:i,isRVFPatternStoreEnabled:n}=await import("./feature-flags-DKXMDVPE.js");if(i()&&n()){let{getSharedRvfAdapter:s}=await import("./shared-rvf-adapter-SIZMEHPM.js"),{AgentMemoryBranch:a}=await import("./agent-memory-branch-NVFQ25WS.js"),o=s(e,384);if(o){let l=new a(o,{branchDir:Gi.join(e,"branches")});this._coordinator.setMemoryBranch(l)}}}catch{}try{let{getRvfMigrationStage:i}=await import("./feature-flags-DKXMDVPE.js"),n=i();if(n>=2){let{RvfMigrationCoordinator:s}=await import("./rvf-migration-coordinator-T4RY7L53.js");await s.getInstance({stage:n}).initialize()}}catch{}if(this._config.enableExperienceBridge!==!1){try{await this._plugins.loadAll()}catch(i){console.warn("[QEKernel] domain plugin pre-load (for bridge subscribers) failed:",i instanceof Error?i.message:i)}try{this._experienceBridge=new Ws(this._eventBus,this._memory),await this._experienceBridge.start()}catch(i){console.warn("[QEKernel] CapturedExperienceBridge failed to start:",i instanceof Error?i.message:i),this._experienceBridge=void 0}}if(this._config.enableDreamScheduler!==!1)try{let i=Rs({maxDurationMs:1e4,minConceptsRequired:3});await i.initialize(),this._dreamScheduler=new km({dreamEngine:i,eventBus:this._eventBus,memoryBackend:this._memory}),await this._dreamScheduler.initialize(),this._dreamScheduler.start()}catch(i){if(console.warn("[QEKernel] DreamScheduler failed to start:",i instanceof Error?i.message:i),this._dreamScheduler)try{await this._dreamScheduler.dispose()}catch{}this._dreamScheduler=void 0}this._initialized=!0}async _initializeLLMRouter(t){let e=(process.env.AQE_LLM_ROUTER_DISABLED??"").trim().toLowerCase();if(e&&e!=="false"&&e!=="0"&&e!=="no"&&e!=="off"){this._llmRouter=void 0;return}let r=this._config.llmRouter??{},i=r.enabled??"auto";if(i===!1){this._llmRouter=void 0;return}try{let n=await Cm({projectRoot:t,override:r.configOverride,providerManager:r.providerManager});if(!n){i===!0&&(console.warn("[QEKernel] llmRouter.enabled=true but no provider available \u2014 continuing without LLM router (domain services will skip LLM enhancement)"),await this._publishLLMRouterEvent("init-no-provider",{reason:"no provider available in env or disk config"})),this._llmRouter=void 0;return}this._llmRouterBuild=n,this._llmRouter=n.router;try{let{setSharedLLMRouter:s}=await import("./base-WIM7G3HC.js");s(n.router)}catch{}}catch(n){let s=n instanceof Error?n.message:String(n);console.warn("[QEKernel] LLM router init failed; continuing without LLM enhancement:",s),await this._publishLLMRouterEvent("init-failed",{error:s,stack:n instanceof Error?n.stack:void 0}),this._llmRouter=void 0}}async _publishLLMRouterEvent(t,e){try{await this._eventBus.publish({id:pb(),type:`kernel.llm-router.${t}`,timestamp:new Date,source:"qe-kernel",payload:e})}catch{}}async dispose(){if(this._dreamScheduler){try{await this._dreamScheduler.dispose()}catch(t){console.warn("[QEKernel] DreamScheduler dispose failed:",t instanceof Error?t.message:t)}this._dreamScheduler=void 0}if(this._experienceBridge&&(await this._experienceBridge.stop(),this._experienceBridge=void 0),await this._plugins.disposeAll(),await this._coordinator.dispose(),await this._eventBus.dispose(),await this._memory.dispose(),this._llmRouter){try{let{resetSharedLLMRouter:t}=await import("./base-WIM7G3HC.js");t()}catch{}this._llmRouter=void 0,this._llmRouterBuild=void 0}this._initialized=!1}getDomainAPI(t){return this._plugins.getPlugin(t)?.getAPI()}async getDomainAPIAsync(t){let e=this._plugins.getPlugin(t);if(!e&&this._config.lazyLoading&&this._config.enabledDomains.includes(t))try{e=await this._plugins.load(t)}catch(r){console.error(`[QEKernel] Failed to lazy load domain ${t}:`,Mc(r));return}return e?.getAPI()}async ensureDomainLoaded(t){if(this._plugins.isLoaded(t))return!0;if(!this._config.enabledDomains.includes(t))return console.warn(`[QEKernel] Domain ${t} is not enabled`),!1;try{return await this._plugins.load(t),!0}catch(e){return console.error(`[QEKernel] Failed to load domain ${t}:`,Mc(e)),!1}}isDomainLoaded(t){return this._plugins.isLoaded(t)}getLoadedDomains(){return this._plugins.getLoaded()}getPendingDomains(){let t=new Set(this._plugins.getLoaded());return this._config.enabledDomains.filter(e=>!t.has(e))}getHealth(){let t=this._coordinator.listAgents(),e={};for(let l of this._plugins.getLoaded()){let u=this._plugins.getPlugin(l);u&&(e[l]=u.getHealth())}for(let l of Ne)if(!e[l]){let u=this._config.enabledDomains.includes(l),d=this._config.lazyLoading&&u;e[l]={status:d?"healthy":u?"degraded":"healthy",agents:{total:0,active:0,idle:0,failed:0},errors:d?[]:u?["Domain not yet loaded"]:[],loaded:!1,lazyLoadable:d}}let r=this._coordinator.getActiveCount(),i=0,n=Number.MAX_SAFE_INTEGER;if(this._memory instanceof Oc){let l=this._memory.getStats();i=l.entries+l.vectors}else i=0;let a=this._eventBus.getMiddlewares().find(l=>l.name==="semantic-anti-drift"),o=a?a.getStats():void 0;return{status:this.determineOverallStatus(e),uptime:Date.now()-this._startTime.getTime(),domains:e,agents:{total:t.length,active:r,maxAllowed:this._config.maxConcurrentAgents},memory:{used:i,available:n},...o?{antiDrift:o}:{}}}determineOverallStatus(t){let e=Object.values(t).map(r=>r.status);return e.some(r=>r==="unhealthy")?"unhealthy":e.some(r=>r==="degraded")?"degraded":"healthy"}getConfig(){return{...this._config}}checkToolCall(t,e,r){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return this._loopTracker.trackCall(t,e,r);let i=this._loopTracker.trackCall(t,e,r);if(i.action==="warn"){let n={id:`loop-warn-${t}-${Date.now()}`,type:el.LOOP_WARNING,timestamp:new Date,source:"coordination",correlationId:t,payload:{agentId:t,toolName:e,callCount:i.callCount,signature:i.signature}};this._eventBus.publish(n)}else if(i.action==="steer"){let n={id:`loop-detected-${t}-${Date.now()}`,type:el.LOOP_DETECTED,timestamp:new Date,source:"coordination",correlationId:t,payload:{agentId:t,toolName:e,callCount:i.callCount,signature:i.signature,steeringMessage:i.steeringMessage}};this._eventBus.publish(n)}return i}get loopTracker(){return this._loopTracker}};function zce(c){return new dm(c)}export{Bs as a,ul as b,Ob as c,ei as d,Sr as e,Wp as f,Kp as g,Xt as h,di as i,nq as j,ze as k,sq as l,aq as m,oq as n,cq as o,gi as p,gh as q,wo as r,Co as s,Th as t,Fr as u,rd as v,sd as w,cd as x,Po as y,Fi as z,Li as A,yc as B,Ni as C,Vi as D,It as E,zr as F,Br as G,qr as H,qe as I,Ge as J,dm as K,zce as L};